React to PDF printing

J Riyana
Nerd For Tech
Published in
2 min readNov 9, 2020

--

In this article, I am going to show How to download React components in the browser using a few simple steps.

Let's go step by step.

Step 01|

First, you need to create a react app. Open your terminal and run the following command to create a react app.

npx create-react-app pdf-download

Step 02|

Now there appears a folder named pdf-download. Move into that folder. To move to that folder run the following command in your terminal.

cd pdf-download

Step 03|

Now you need to install the react package which allows you to print react components as PDF. This package aims to solve that by popping up a print window with CSS styles copied over as well.

For that run the following command in your terminal

npm install -s react-to-print

Step 04|

For the demo, I am showing a paragraph, a table, and an image.

Now open the index.js which is inside the src folder. Replace the code with the following code as shown in the diagram below.

index.js

As you can see in the diagram you need to import useReactToPrint from the package react-to-print and also you need to import useRef from react package. This allows you to print the component as a pdf. We can add any CSS to our component as shown in the above diagram.

Step 05|

Now, let's run the react app to see the output. To run the react app run the following command in your terminal.

npm start

Output

You can see a button as “Print this out!”. Click it!!!

There appears a pop up as shown in the diagram below.

pop up

You can see the preview of your pdf file. You can change the size as you want.

Click Print again!!! So now you can save this file anywhere as you want and rename the file as you want.

For more functions in this package, please refer to the following link.

Hope you got something from my article. Thanks for reading!

--

--

J Riyana
Nerd For Tech

I am an undergraduate in the Faculty of Information Technology University of Moratuwa, Sri Lanka.