Convert HTML string to PDF in ReactJs

Matheswaaran
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:

  1. Create an iframe with visibility: hidden and add it to the DOM
  2. Append the html string to the iframe’s body.
  3. Convert the iframe into a PNG image using html2canvas npm package.
  4. Create a PDF document using jsPDF npm package.
  5. Attach the PNG image as a page in the PDF document.
  6. 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

--

--

Responses (1)