Generating a PDF in a web app can sound complicated — but in React, it’s surprisingly easy thanks to the react-to-pdf
library. This post explores two approaches for generating PDFs from specific sections of your UI.
✅ Option 1: Using generatePDF
with useRef
This method gives you direct control using a ref
and a manual function call.
📄 Example Code
javascript
import { useRef } from 'react';
import generatePDF from 'react-to-pdf';
const Component = () => {
const targetRef = useRef();
return (
<div>
<button onClick={() => generatePDF(targetRef, { filename: 'page.pdf' })}>
Download PDF
</button>
<div ref={targetRef}>
Content to be included in the PDF
</div>
</div>
);
};
🔍 How It Works
useRef()
: This hook creates a mutable reference targetRef
, which you attach to the DOM element you want to convert to PDF.generatePDF(targetRef, { filename })
: This function scans the referenced element and downloads it as a PDF.- Button Click: When the user clicks "Download PDF", the PDF is generated and downloaded with the specified filename.
✅ Option 2: Using the usePDF
Hook
This method is more idiomatic for React functional components and abstracts away some details.
📄 Example Code
javascript
import React from 'react';
import { usePDF } from 'react-to-pdf';
import './App.css';
function App() {
const { toPDF, targetRef } = usePDF({ filename: 'page.pdf' });
return (
<div>
<button onClick={() => toPDF()}>Download PDF</button>
<div ref={targetRef}>
Content to be generated to PDF
</div>
</div>
);
}
export default App;
🔍 How It Works
usePDF()
: A hook provided by react-to-pdf
, returning:toPDF
: A function that, when invoked, generates the PDF.targetRef
: A ref to attach to the element to be converted.- Auto Configuration: Just pass the desired filename when initializing the hook.
- Cleaner Syntax: No need to manually pass
ref
and options into the generate function.
⚖️ Which Should You Use?
FeaturegeneratePDF + useRefusePDF
HookSetup StyleManualReact-friendly (hook-based)Ideal ForQuick, simple useClean code in modern ReactCustomizationHighModerate (through hook)ReadabilityMediumHigh
🔐 Bonus Tip
Make sure the content you're exporting is fully rendered and visible when generating the PDF — hidden or lazy-loaded elements may not appear correctly.
📦 Installation
To use either approach, make sure you’ve installed the library:
bash
npm install react-to-pdf
🧠 Final Thoughts
The react-to-pdf
library provides a simple and intuitive way to export UI components as downloadable PDFs. Whether you're building invoices, reports, or certificates, you can now do it with a single button click.