Skip to content
  • Home
  • Contact
  • My Portfolio
Sonahang RaiPersonal Blogs
  • Home
  • Contact
  • My Portfolio
Javascript . React

PDF from React

On April 26, 2023 by Sonahang Rai

Creating 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.

PDF from React

Package’s on Action

  • html2canvas
  • jsPDF

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.

jspdf

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

  • April 2023
  • November 2022
  • November 2021
  • August 2021
  • April 2021
  • March 2021
  • August 2020
  • July 2020
  • April 2020

Calendar

October 2023
S M T W T F S
1234567
891011121314
15161718192021
22232425262728
293031  
« Apr    

Categories

  • Javascript
  • Next
  • React
  • SEO
  • Web Design (Slicing)
  • Web Design Tutorials
  • Wordpress

Copyright Sonahang Rai 2023 | Theme by ThemeinProgress | Proudly powered by WordPress