Convert HTML string to PDF in ReactJs
1 min readAug 24, 2022
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
For npm:
npm install html2canvas jspdf
For yarn:
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: hidden
and add it to the DOM - Append the html string to the iframe’s body.
- Convert the iframe into a PNG image using
html2canvas
npm package. - Create a PDF document using
jsPDF
npm package. - 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:
Be Amazed!
Hooray! We have successfully converted the HTML string to PDF.
Say Hi, It’s free at @matheswaaran_S or https://matheswaaran.com