PDF from React
On April 26, 2023 by Sonahang RaiCreating PDF from React frontend along with a dynamic data can be a challenging task for a frontend developers. I as a frontend developer in ReactJS got this challenge during one of my project where I had to create a PDF file of a component which would also consist of a dynamic datas.
I started doing research on google. During that time ChatGPT was not born so I had to manually search for ideas on google. After some great amount of time doing research I was finally able to acheive my goal. I am not sure if its the best way to do it but still it did the task so I am going to share how I did this.
Package’s on Action
The Idea
So what I finally thought is to first create a component ready that has already been filled with dynamic datas and when the component is fully cooked I thought of making it as an image and downloading it as pdf file. This idea made me research about various packages that is related. So i came to find the above listed packages which are very famous and being used a lot of time.
How it works
So at first just make your components ready that needs to be downloaded as pdf. Fetch all the desired data and do all processing. After all things ready we will use the `useRef` hook to that element that needs to be downloaded as pdf.
In the above code sample you can see there is a cooked and ready component that needs to be downloaded as pdf. We are creating a parent div where we will use useRef hook later.
Here we now have implemented the function that utilized the html2canvas and jsPdf packages. When on a button click the PDF is downloaded. In the utils function `exportPdf` you can see that 2 params are taken. One for the dom and another for the file name. You can see first the component is being changed into a canvas and that canvas is used to create the pdf. For various options please visit the pacakges official documentation sites.
In this way I was able to achieve a task of creating pdf from react frontend. I hope this was a great help.
You can get the demo from codesandbox as well.
Archives
Calendar
S | M | T | W | T | F | S |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |