2 Things:

  1. When getting access to a DOM Element in react you should always use useRef

  2. It appears that .html method is async and requires a callback

A working example would be something like this:

import { useRef } from 'react';
import { jsPDF } from 'jspdf';

export default function PDF() {
    const pdfRef = useRef(null);

    const handleDownload = () => {
        const content = pdfRef.current;

        const doc = new jsPDF();
        doc.html(content, {
            callback: function (doc) {
                doc.save('sample.pdf');
            }
        });
    };

    return (
        <div>
            <header ref={pdfRef}>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
            </header>
            <footer>
                <button onClick={handleDownload}>Download</button>
            </footer>
        </div>
    );
}

Update

If you need to control the size you can add additional properties as per documentation cited above:

Option 1 - use the html2canvas option and control the scale:

const handleDownload = () => {
    const content = pdfRef.current;

    const doc = new jsPDF();
    doc.html(content, {
        callback: function (doc) {
            doc.save('sample.pdf');
        },
        html2canvas: { scale: 0.5 } // change the scale to whatever number you need
    });
};

Option 2 - use width and windowWidth:

const handleDownload = () => {
    const content = pdfRef.current;

    const doc = new jsPDF();
    doc.html(content, {
        callback: function (doc) {
            doc.save('sample.pdf');
        },
        width: 200, // <- here
        windowWidth: 200 // <- here
    });
};
Answer from SakoBu on Stack Overflow
🌐
Nutrient
nutrient.io › blog › sdk › how to convert html to pdf using react
Generate PDFs from HTML in React with jsPDF
May 14, 2025 - If you want to change any of these ... in the jsPDF documentation(opens in a new tab). jsPDF provides a method called html()(opens in a new tab) to convert HTML to PDF....
Top answer
1 of 3
6

2 Things:

  1. When getting access to a DOM Element in react you should always use useRef

  2. It appears that .html method is async and requires a callback

A working example would be something like this:

import { useRef } from 'react';
import { jsPDF } from 'jspdf';

export default function PDF() {
    const pdfRef = useRef(null);

    const handleDownload = () => {
        const content = pdfRef.current;

        const doc = new jsPDF();
        doc.html(content, {
            callback: function (doc) {
                doc.save('sample.pdf');
            }
        });
    };

    return (
        <div>
            <header ref={pdfRef}>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
                <div>l kldfjlkasjfld asjflkajf ljfasd'flksdasjf lsdasjfsadf</div>
            </header>
            <footer>
                <button onClick={handleDownload}>Download</button>
            </footer>
        </div>
    );
}

Update

If you need to control the size you can add additional properties as per documentation cited above:

Option 1 - use the html2canvas option and control the scale:

const handleDownload = () => {
    const content = pdfRef.current;

    const doc = new jsPDF();
    doc.html(content, {
        callback: function (doc) {
            doc.save('sample.pdf');
        },
        html2canvas: { scale: 0.5 } // change the scale to whatever number you need
    });
};

Option 2 - use width and windowWidth:

const handleDownload = () => {
    const content = pdfRef.current;

    const doc = new jsPDF();
    doc.html(content, {
        callback: function (doc) {
            doc.save('sample.pdf');
        },
        width: 200, // <- here
        windowWidth: 200 // <- here
    });
};
2 of 3
1
// use can you ReactDOMServer.renderToString(element) 

import { renderToString } from "react-dom/server";
import { jsPDF } from "jspdf";
export const dow = () => {
  let htmlElement = <div>Hello </div> 
  let elementAsString = renderToString(htmlElement);
  var doc = new jsPDF();
  doc.html(elementAsString, {
    callback: function (doc) {
      doc.save("test.pdf");
    },
    x: 10,
    y: 10,
  });
};

// use can use this code as function to handle an event 
People also ask

What Are the Steps to Integrate jsPDF with React?
Install the jsPDF library using `npm`, import it into your React component, and use it to capture and convert the HTML content to PDF by triggering the conversion on a specific user action.
🌐
pspdfkit.com
pspdfkit.com › blog › 2022 › how-to-convert-html-to-pdf-using-react
How to Convert HTML to PDF in React - PSPDFKit
How Can I Convert HTML to PDF in a React Application?
You can use the jsPDF library to convert HTML to PDF in a React application. This library helps render HTML content to a PDF format.
🌐
pspdfkit.com
pspdfkit.com › blog › 2022 › how-to-convert-html-to-pdf-using-react
How to Convert HTML to PDF in React - PSPDFKit
What Are the Benefits of Using React for HTML-to-PDF Conversion?
React allows for a dynamic and interactive UI, making it easy to create and manage the content that will be converted to PDF. React’s component-based architecture helps in reusing and maintaining the code efficiently.
🌐
pspdfkit.com
pspdfkit.com › blog › 2022 › how-to-convert-html-to-pdf-using-react
How to Convert HTML to PDF in React - PSPDFKit
🌐
DEV Community
dev.to › hulyamasharipov › how-to-convert-html-to-pdf-using-react-37j4
How to Convert HTML to PDF Using React - DEV Community
November 28, 2023 - In this tutorial, you’ll learn how to convert HTML into PDF using React, one of the most popular JavaScript libraries. To achieve this, you’ll use an open source package called jsPDF, which is a client-side library that doesn’t require any server-side processing.
🌐
GitHub
gist.github.com › brenopolanski › a316515d1b48f2d5ed6c5f71e638d510
Convert HTML to a PDF in React.JS · GitHub
import React, { Component } from 'react'; export default class Export extends Component { constructor(props) { super(props); } printDocument() { const input = document.getElementById('divToPrint'); html2canvas(input) .then((canvas) => { const imgData = canvas.toDataURL('image/png'); const pdf = new jsPDF(); pdf.addImage(imgData, 'JPEG', 0, 0); // pdf.output('dataurlnewwindow'); pdf.save('download.pdf'); }); } render() { return (<div> <div className="mb5"> <button onClick={this.printDocument}>Print</button> </div> <div id="divToPrint" className="mt4" {...css({ backgroundColor: '#f5f5f5', width: '210mm', minHeight: '297mm', marginLeft: 'auto', marginRight: 'auto' })}> <div>Note: Here the dimensions of div are same as A4</div> <div>You Can add any component here</div> </div> </div>); } } Sign up for free to join this conversation on GitHub.
🌐
Nutrient
nutrient.io › blog › sdk › how to convert html to pdf using html2df and react
HTML to PDF in React: Convert HTML to PDF using html2pdf.js
May 7, 2025 - Learn how to convert HTML to PDF in React using html2pdf.js. This step-by-step guide covers setup, customization options, and PDF download functionality.
🌐
npm
npmjs.com › package › jspdf-react
jspdf-react - npm
npm install --save jspdf-react · If you want to convert an html in pdf, I recommend using the library. https://github.com/eKoopmans/html2pdf.js ·
      » npm install jspdf-react
    
Published   Jul 17, 2019
Version   1.0.11
Author   apipemc
🌐
PSPDFKit
pspdfkit.com › blog › 2022 › how-to-convert-html-to-pdf-using-react
How to Convert HTML to PDF in React - PSPDFKit
May 14, 2025 - If you want to change any of these ... in the jsPDF documentation(opens in a new tab). jsPDF provides a method called html()(opens in a new tab) to convert HTML to PDF....
Find elsewhere
🌐
GitHub
github.com › apipemc › jspdf-react
GitHub - apipemc/jspdf-react: Wrapper jsPDF for React
If you want to convert an html in pdf, I recommend using the library. https://github.com/eKoopmans/html2pdf.js · import React, { Component } from 'react' import PDF, { Text, AddPage, Line, Image, Table, Html } from 'jspdf-react' import OctoCatImage ...
Starred by 34 users
Forked by 11 users
Languages   JavaScript 96.8% | HTML 3.2%
Top answer
1 of 13
168

Rendering react as pdf is generally a pain, but there is a way around it using canvas.

The idea is to convert : HTML -> Canvas -> PNG (or JPEG) -> PDF

To achieve the above, you'll need :

  1. html2canvas &
  2. jsPDF

import React, {Component, PropTypes} from 'react';

// download html2canvas and jsPDF and save the files in app/ext, or somewhere else
// the built versions are directly consumable
// import {html2canvas, jsPDF} from 'app/ext';


export default class Export extends Component {
  constructor(props) {
    super(props);
  }

  printDocument() {
    const input = document.getElementById('divToPrint');
    html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'JPEG', 0, 0);
        // pdf.output('dataurlnewwindow');
        pdf.save("download.pdf");
      })
    ;
  }

  render() {
    return (<div>
      <div className="mb5">
        <button onClick={this.printDocument}>Print</button>
      </div>
      <div id="divToPrint" className="mt4" {...css({
        backgroundColor: '#f5f5f5',
        width: '210mm',
        minHeight: '297mm',
        marginLeft: 'auto',
        marginRight: 'auto'
      })}>
        <div>Note: Here the dimensions of div are same as A4</div> 
        <div>You Can add any component here</div>
      </div>
    </div>);
  }
}

The snippet will not work here because the required files are not imported.

An alternate approach is being used in this answer, where the middle steps are dropped and you can simply convert from HTML to PDF. There is an option to do this in the jsPDF documentation as well, but from personal observation, I feel that better accuracy is achieved when dom is converted into png first.

Update 0: September 14, 2018

The text on the pdfs created by this approach will not be selectable. If that's a requirement, you might find this article helpful.

2 of 13
19

@react-pdf/renderer is a great resource for this.

It is a bit time consuming converting your markup and CSS to React-PDF's format, but it is easy to understand. Exporting a PDF and from it is fairly straightforward.

To allow a user to download a PDF generated by react-PDF, use their on the fly rendering, which provides a customizable download link. When clicked, the site renders and downloads the PDF for the user.

Here's their REPL which will familiarize you with the markup and styling required. They have a download link for the PDF too, but they don't show the code for that here.

🌐
w3collective
w3collective.com › category: tutorial › exporting a react component to a pdf file on click
Exporting a React component to a PDF file on click - w3collective
February 18, 2022 - If you do want external CSS styles to appear in the PDF you’ll either need to use CSS in JS or another library called html2canvas which captures the HTML as image before exporting to PDF. Let modify our component to capture external CSS by first installing html2canvas: <code>npm install html2canvas</code>Code language: HTML, XML (xml) ... import html2canvas from "html2canvas"; import { jsPDF } from "jspdf"; import Barcode from "./barcode.png"; Code language: JavaScript (javascript)
🌐
Medium
matheswaaran.medium.com › convert-html-string-to-pdf-using-jspdf-in-reactjs-255aba2d76a2
Convert HTML string to PDF in ReactJs | by Matheswaaran | Medium
August 28, 2022 - This article discusses how to convert a HTML string into a PDF document in client side apps which uses ReactJs using jsPDF package.
🌐
Mdfaisal
mdfaisal.com › blog › download-html-as-a-pdf-in-react
Download HTML as a PDF in React | Mohammad Faisal
February 18, 2021 - Here is the full code for a custom PDF downloader which takes two arguments: ... import React from 'react'; import html2canvas from "html2canvas"; import { jsPDF } from "jspdf"; const GenericPdfDownloader = ({rootElementId , downloadFileName}) ...
🌐
npm
npmjs.com › package › react-to-pdf
react-to-pdf - npm
You probably will not need this and things can break, // so use with caution. overrides: { // see https://artskydj.github.io/jsPDF/docs/jsPDF.html for more options pdf: { compress: true }, // see https://html2canvas.hertzen.com/configuration for more options canvas: { useCORS: true } }, }; // you can use a function to return the target element besides using React refs const getTargetElement = () => document.getElementById('content-id'); const Component = () => { return ( <div> <button onClick={() => generatePDF(getTargetElement, options)}>Generate PDF</button> <div id="content-id"> Content to be generated to PDF </div> </div> ); } Stackblitz demo ·
      » npm install react-to-pdf
    
Published   Nov 25, 2025
Version   2.0.3
Author   Marcos Andrei Ivanechtchuk
🌐
YouTube
youtube.com › technical rajni
How to Convert HTML to PDF Using React - YouTube
How to Convert HTML to PDF Using React Convert HTML string to PDF in ReactJs Download HTML as a PDF in ReactGenerating a PDF file from React ComponentsHTML t...
Published   December 9, 2023
Views   3K
🌐
Medium
medium.com › wesionary-team › pdf-generation-in-react-1f5bb8064c5f
PDF generation in React.. Discussion on PDF generation in React.
December 15, 2021 - We take the canvas obtained from html2canvas and then convert it to a PNG image. And finally, render it to the PDF using jspdf.
🌐
IronPDF
ironpdf.com › ironpdf blog › node pdf tools › html to pdf react
Convert HTML to PDF in React (Developer Tutorial) | IronPDF
July 29, 2025 - we'll explore various libraries to generate PDFs and learn how to use the popular jsPDF library to create PDF files directly from your React components
🌐
Stack Overflow
stackoverflow.com › questions › 68593655 › react-convert-the-component-as-pdf-using-jspdf
React convert the component as pdf using jspdf
const els = document.getElementsByClassName('App'); const pdf = new jsPDF("p", "px", "a4"); pdf.html(els[0]).then(() => { pdf.save("download.pdf"); }); ... Find the answer to your question by asking.
🌐
Stack Overflow
stackoverflow.com › questions › 79047908 › html-to-pdf-in-react-application
HTML to PDF in react application
import { useContext, useEffect, useState, useRef } from "react"; import html2canvas from "html2canvas"; import jsPDF from "jspdf"; export default function Component() { const pdfRef = useRef(); async function downloadPDF() { const element = pdfRef.current; console.log(element.innerHTML); // Sprawdź zawartość elementu if (!element.innerHTML) { console.log("Element is empty"); return; } setTimeout(async () => { try { console.log("Starting PDF generation"); const canvas = await html2canvas(element); console.log("Canvas generated"); const imgData = canvas.toDataURL('image/png'); console.log("Im