Convert HTML string to PDF in ReactJs
This article discusses how to convert a HTML string into a PDF document in client side apps which uses ReactJs using jsPDF package.
Install the required packages:
To install the package, type one of the following commands based on your package manager
npm install html2canvas jspdf
yarn add html2canvas jspdf
Converting the HTML string to PDF Document:
The HTML string can be converted into a PDF by adding them to an hidden iframe in the DOM from which the PDF document is exported.
The steps to do this are:
- Create an iframe with
visibility: hiddenand add it to the DOM
- Append the html string to the iframe’s body.
- Convert the iframe into a PNG image using
- Create a PDF document using
- Attach the PNG image as a page in the PDF document.
- Repeat step 5 for more than one page.
The full example is available below:
Hooray! We have successfully converted the HTML string to PDF.