How to use html2pdf with React


This post goes over how to export HTML to PDF with html2pdf and React.

Prerequisites

Given you have html2pdf.js installed:

npm install html2pdf.js

And a React app:

export default function App() {
  return <div>{/* ... */}</div>;
}

Ref

Add a ref for the PDF export area:

import { useRef } from 'react';

export default function App() {
  const exportAreaRef = useRef<HTMLDivElement>(null);
  return <div ref={exportAreaRef}>{/* ... */}</div>;
}

html2pdf

Add a button that triggers the export via onClick:

import { useRef } from 'react';

export default function App() {
  const exportAreaRef = useRef<HTMLDivElement>(null);
  return (
    <div ref={exportAreaRef}>
      {/* ... */}
      <button
        onClick={() => {
          if (exportAreaRef.current) {
            html2pdf().from(exportAreaRef.current).save();
          }
        }}
      >
        Export
      </button>
    </div>
  );
}

If you want to exclude an element from the PDF export, add the data attribute:

data-html2canvas-ignore="true"

So to ignore the button:

<button data-html2canvas-ignore="true">Export</button>

You can also set html2pdf options:

html2pdf()
  .set({
    filename: 'test.pdf',
  })
  .from(exportAreaRef.current)
  .save();

To export a PDF that matches the screen size:

html2pdf()
  .set({
    html2canvas: {
      scale: 2,
      width: window.innerWidth,
      height: window.innerHeight,
    },
    jsPDF: {
      format: [window.innerWidth, window.innerHeight],
      orientation: 'landscape',
    },
  })
  .from(exportAreaRef.current)
  .save();

Demo

StackBlitz:



Please support this site and join our Discord!