React to PDF
Easily create PDF documents from React components.
Install
# Yarn
yarn add react-to-pdf
# NPM
npm install --save react-to-pdf
Important Notes
- Not vectorized - the pdf is created from a screenshot of the component and therefore is not vectorized. If you are looking for something more advanced to generate pdf using React components, please check out other popular alternatives packages listed below.
- No SSR
Alternatives and Similars Packages
- @react-pdf/renderer - React renderer to create PDF files on the browser and server
- react-pdf - Display PDFs in your React app as easily as if they were images.
Examples
Usage
Using usePDF
hook
import { usePDF } from 'react-to-pdf';
const Component = () => {
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>
)
}
Code Sandbox demo
Using default function
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>
)
}
Code Sandbox demo
Advanced options
import generatePDF, { Resolution, Margin } from 'react-to-pdf';
const options = {
method: 'open',
resolution: Resolution.HIGH,
page: {
margin: Margin.SMALL,
format: 'letter',
orientation: 'landscape',
},
canvas: {
mimeType: 'image/png',
qualityRatio: 1
},
overrides: {
pdf: {
compress: true
},
canvas: {
useCORS: true
}
},
};
const getTargetElement = () => document.getElementById('content-id');
const Component = () => {
return (
<div>
<button onClick={() => generatePDF(getTargetElement, options)}>Generate PDF</button>
<div id="content-id">
Content to be generated to PDF
</div>
</div>
);
}
Code Sandbox demo