Export React Component As a PDF

Uditha Janadara
2 min readJul 2, 2021

--

React in a most popular frontend development framework. While developing web applications sometimes we need to generate PDF documents. It may be a entire web page or a component. Here I’m going to show you how we can export a react component as a PDF file.

First we need to install jspdf npm package using below command.

npm install jspdf --save

After the installation, you need to import that package in your relevant react component

import JsPDF from 'jspdf';

Now we are going to implement a function for generate and export the PDF.

const generatePDF = () => {

const report = new JsPDF('portrait','pt','a4');
report.html(document.querySelector('#report')).then(() => {
report.save('report.pdf');
});

Here I have declared a function named generatePDF.

You can call this function with a button click in the component.

<button onClick={generatePDF} type="button">Export PDF</button>

In the function I have declared a new JsPDF object named report.

It has accept three parameters.

  1. PDF file orientation — default is potrait
  2. Units (px/pt/mm..) — default is mm
  3. PDF file size(A4/A2/A3..) — default is A4

Then using querySelector I have passed the div id as ‘#report’.

#report is the component wrapping div tag id. So here I’m exporting the every content inside this div tag as a PDF document.

Finally in the save function I have passed the file name I want to give to the PDF file.

That’s It. Ones you click the button, it will generate and download the PDF file for you.

Happy Hacking …!

--

--

Uditha Janadara
Uditha Janadara

Written by Uditha Janadara

Undergraduate Software Engineer at Sri Lanka Institute of Information Technology

Responses (1)