HTML to PDF converter for your React Application

Here, I’ll show you how to use jsPDF (html to pdf converter) in your React application which supports all modern CSS including flexbox.

Consider the below one as your sample App component.

import React from 'react';

const App = () => {
    return (
      <div>
        <h1>Hello World</h1>
      </div>
    );
}

export default App;

Now, install jspdf library by using the below command.

npm i --save jspdf

Then, you can import jspdf in the App component.

import { jsPDF } from "jspdf";

Now, I’m going to replace my JSX with the below code.

      <div>
        <div id="pdf-view">
          <h1 style={{color: '#33959a'}}>Testing html to pdf converter</h1>
        </div>
      </div>

Here, I have added a div with the id “pdf-view” so that I can convert all content inside this specific div into pdf. Now, I’m going to add a button below the div.

      <button onClick={pdfDownload}>Download as pdf</button>

Clicking on the button invokes the below function

   const pdfDownload = e => {
      e.preventDefault()
      let doc = new jsPDF("landscape", 'pt', 'A4');
      doc.html(document.getElementById('pdf-view'), {
        callback: () => {
          doc.save('test.pdf');
        }
      });
  }

Here, I make use of jspdf library to convert all content inside the div (with id pdf-view) into pdf and save it as test.pdf. You can find all the properties of jsPDF here. By clicking on the button you can see the below pdf opened in a new tab.

Final Code

import React from 'react';
import { jsPDF } from "jspdf";


const App = () => {

  const pdfDownload = e => {
      e.preventDefault()
      let doc = new jsPDF("landscape", 'pt', 'A4');
      doc.html(document.getElementById('pdf-view'), {
        callback: () => {
          doc.save('test.pdf');
        }
      });
  }
    return (
      <div>
        <div id="pdf-view">
          <h1 style={{color: '#33959a'}}>Testing html to pdf converter</h1>
        </div>
        <button onClick={pdfDownload}>Download as pdf</button>
      </div>
    );
}

export default App;

One Comment on “HTML to PDF converter for your React Application”

Leave a Reply