This comparison evaluates four distinct approaches to handling PDFs in web applications. jspdf serves as the low-level engine for programmatically drawing PDF content. html2pdf.js and react-to-pdf act as higher-level wrappers that convert HTML DOM elements into PDF files using snapshots. react-pdf is primarily designed for rendering and viewing existing PDF files within a React interface, rather than generating new ones. Understanding these roles is critical for selecting the right tool for creation versus display tasks.
Handling PDFs in modern web applications usually falls into two categories: creating new documents from app data or displaying existing files to users. The packages jspdf, html2pdf.js, react-to-pdf, and react-pdf address these needs differently. Some focus on low-level drawing, others on HTML snapshots, and one specializes in viewing. Let's break down how they work in real engineering scenarios.
jspdf is the core engine. It does not know about HTML or CSS. You draw text and lines using coordinates.
// jspdf: Manual drawing
import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.text("Hello World", 10, 10);
doc.save("document.pdf");
html2pdf.js wraps jspdf and html2canvas. It takes a DOM element and snapshots it.
// html2pdf.js: HTML snapshot
import html2pdf from "html2pdf.js";
const element = document.getElementById("content");
html2pdf().from(element).save();
react-to-pdf is a React hook wrapper around similar snapshot technology. It simplifies ref handling.
// react-to-pdf: Hook-based capture
import { useReactToPdf } from "react-to-pdf";
const { toPdf } = useReactToPdf();
const handlePrint = () => toPdf({ targetRef: ref });
react-pdf is a viewer. It loads existing PDF files and renders them as React components.
// react-pdf: Viewing existing files
import { Document, Page } from "react-pdf";
<Document file="/sample.pdf">{({ pageNum }) => <Page pageNumber={pageNum} />}</Document>
Integration styles vary from declarative components to imperative function calls. This affects how you manage state and triggers.
jspdf requires imperative logic. You call methods inside event handlers or effects.
// jspdf: Imperative function call
const generate = () => {
const doc = new jsPDF();
doc.text("Data", 10, 10);
doc.save();
};
html2pdf.js also uses imperative chains but targets DOM nodes directly.
// html2pdf.js: Imperative chain
const generate = () => {
html2pdf().from(document.getElementById("root")).save();
};
react-to-pdf offers a hook that fits naturally into React function components.
// react-to-pdf: React hook usage
const Component = () => {
const { toPdf } = useReactToPdf();
return <button onClick={() => toPdf({ targetRef: ref })}>Download</button>;
};
react-pdf uses declarative components to manage the view state.
// react-pdf: Declarative component
const Viewer = () => {
return <Document file="/file.pdf"><Page pageNumber={1} /></Document>;
};
How the library handles styles determines if your PDF looks like your website or a custom report.
jspdf ignores CSS. You must define fonts and positions manually.
// jspdf: No CSS support
doc.setFont("helvetica");
doc.setFontSize(16);
doc.text("Title", 10, 10); // Coordinates required
html2pdf.js respects CSS because it renders the DOM. What you see is what you get.
// html2pdf.js: CSS respected
// <div id="content" class="styled-box">Text</div>
// The .styled-box classes are preserved in the snapshot
html2pdf().from(document.getElementById("content")).save();
react-to-pdf also relies on DOM rendering, so CSS classes apply normally.
// react-to-pdf: CSS respected
// <div ref={ref} className="card">Content</div>
// The .card styles are captured in the output
const { toPdf } = useReactToPdf();
react-pdf does not apply app CSS to the PDF content. It renders the internal structure of the PDF file itself.
// react-pdf: Internal PDF styling
// Styles come from the PDF file, not your React CSS
<Document file="/report.pdf"><Page width={600} /></Document>
A common architectural error is confusing react-pdf with generation tools. The ecosystem has two similar names with different jobs.
jspdf, html2pdf.js, and react-to-pdf create new files. They take data or HTML and output a binary PDF.
// Generation packages output a file
// jspdf, html2pdf.js, react-to-pdf all call .save() or similar
doc.save("new-file.pdf");
react-pdf displays existing files. It does not have a .save() method for creation.
// react-pdf loads a file
// It does not generate content from React components
<Document file="/existing.pdf" />
π‘ Note: If you need to generate PDFs using React components (like
<View>and<Text>), the standard library is@react-pdf/renderer, notreact-pdf.react-pdfis strictly for viewing.
Wrapper libraries depend on underlying engines. If the engine changes, the wrapper might break.
jspdf is the foundation. It has the longest lifespan and fewest external dependencies.
// jspdf: Stable core
import { jsPDF } from "jspdf"; // Direct dependency
html2pdf.js depends on jspdf and html2canvas. Updates to either can affect behavior.
// html2pdf.js: Multiple dependencies
// Issues in html2canvas may affect image quality in PDF
html2pdf().set({ html2canvas: { scale: 2 } }).from(element).save();
react-to-pdf is a thin wrapper. It may lag behind React updates or underlying PDF engines.
// react-to-pdf: Wrapper risk
// Check npm for recent commits before adopting
const { toPdf } = useReactToPdf();
react-pdf depends on pdf.js by Mozilla. It is well-maintained for viewing purposes.
// react-pdf: Viewer stability
// Relies on Mozilla's pdf.js rendering engine
import { pdfjs } from "react-pdf";
| Feature | jspdf | html2pdf.js | react-to-pdf | react-pdf |
|---|---|---|---|---|
| Primary Goal | Generate (Vector) | Generate (Snapshot) | Generate (Snapshot) | View Existing |
| CSS Support | β No | β Yes | β Yes | β N/A |
| Text Selectable | β Yes | β Often No | β Often No | β Yes |
| React Style | Imperative | Imperative | Hook | Component |
| Best For | Custom Reports | Invoices/Receipts | Quick React Exports | PDF Viewer UI |
Select your tool based on the source of your content. If you have raw data and need crisp text, use jspdf. If you have an HTML layout you want to print exactly, use html2pdf.js. If you want a React hook to simplify that HTML capture, use react-to-pdf. If you need to let users read uploaded PDF files, use react-pdf. Avoid using react-pdf for generation tasks β that requires @react-pdf/renderer instead.
Choose html2pdf.js when you need a quick solution to convert existing HTML layouts into PDF files without rewriting styles. It is ideal for invoices or reports that already exist as DOM elements and require visual fidelity to the screen. Be aware that text in the resulting PDF may not be selectable since it is often rendered as images. This tool balances ease of use with reasonable output quality for standard web content.
Choose jspdf when you require precise, programmatic control over every element in the PDF document. It is best suited for generating documents from raw data where HTML CSS support is not needed or reliable. You will need to manually define coordinates for text and shapes, which offers flexibility but increases development time. This is the foundational library that many other wrappers rely on for core functionality.
Choose react-pdf when your goal is to display existing PDF files inside your React application interface. It provides components to render PDF pages with support for zooming, navigation, and text layer extraction. Do not select this package if you intend to generate new PDF files from React components, as that is not its primary function. For generation tasks in React, evaluate @react-pdf/renderer instead.
Choose react-to-pdf when you want a React-specific hook to simplify capturing components as PDF files. It reduces boilerplate code by managing references and conversion triggers internally. This package is suitable for projects that prefer hook-based patterns over manual DOM manipulation. Verify its maintenance status before adoption, as wrapper libraries can become outdated faster than core engines.
html2pdf.js converts any webpage or element into a printable PDF entirely client-side using html2canvas and jsPDF.
The simplest way to use html2pdf.js is to include it as a script in your HTML by using cdnjs:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Using a CDN URL will lock you to a specific version, which should ensure stability and give you control over when to change versions. cdnjs gives you access to all past versions of html2pdf.js.
Note: Read about dependencies for more information about using the unbundled version dist/html2canvas.min.js.
You may also download dist/html2pdf.bundle.min.js directly to your project folder and include it in your HTML with:
<script src="html2pdf.bundle.min.js"></script>
Install html2pdf.js and its dependencies using NPM with npm install --save html2pdf.js (make sure to include .js in the package name).
Note: You can use NPM to create your project, but html2pdf.js will not run in Node.js, it must be run in a browser.
Install html2pdf.js and its dependencies using Bower with bower install --save html2pdf.js (make sure to include .js in the package name).
If you're on a webpage that you can't modify directly and wish to use html2pdf.js to capture a screenshot, you can follow these steps:
function addScript(url) {
var script = document.createElement('script');
script.type = 'application/javascript';
script.src = url;
document.head.appendChild(script);
}
addScript('https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js');
html2pdf(document.body).Once installed, html2pdf.js is ready to use. The following command will generate a PDF of #element-to-print and prompt the user to save the result:
var element = document.getElementById('element-to-print');
html2pdf(element);
Every step of html2pdf.js is configurable, using its new Promise-based API. If html2pdf.js is called without arguments, it will return a Worker object:
var worker = html2pdf(); // Or: var worker = new html2pdf.Worker;
This worker has methods that can be chained sequentially, as each Promise resolves, and allows insertion of your own intermediate functions between steps. A prerequisite system allows you to skip over mandatory steps (like canvas creation) without any trouble:
// This will implicitly create the canvas and PDF objects before saving.
var worker = html2pdf().from(element).save();
The basic workflow of html2pdf.js tasks (enforced by the prereq system) is:
.from() -> .toContainer() -> .toCanvas() -> .toImg() -> .toPdf() -> .save()
| Method | Arguments | Description |
|---|---|---|
| from | src, type | Sets the source (HTML string or element) for the PDF. Optional type specifies other sources: 'string', 'element', 'canvas', or 'img'. |
| to | target | Converts the source to the specified target ('container', 'canvas', 'img', or 'pdf'). Each target also has its own toX method that can be called directly: toContainer(), toCanvas(), toImg(), and toPdf(). |
| output | type, options, src | Routes to the appropriate outputPdf or outputImg method based on specified src ('pdf' (default) or 'img'). |
| outputPdf | type, options | Sends type and options to the jsPDF object's output method, and returns the result as a Promise (use .then to access). See the jsPDF source code for more info. |
| outputImg | type, options | Returns the specified data type for the image as a Promise (use .then to access). Supported types: 'img', 'datauristring'/'dataurlstring', and 'datauri'/'dataurl'. |
| save | filename | Saves the PDF object with the optional filename (creates user download prompt). |
| set | opt | Sets the specified properties. See Options below for more details. |
| get | key, cbk | Returns the property specified in key, either as a Promise (use .then to access), or by calling cbk if provided. |
| then | onFulfilled, onRejected | Standard Promise method, with this re-bound to the Worker, and with added progress-tracking (see Progress below). Note that .then returns a Worker, which is a subclass of Promise. |
| thenCore | onFulFilled, onRejected | Standard Promise method, with this re-bound to the Worker (no progress-tracking). Note that .thenCore returns a Worker, which is a subclass of Promise. |
| thenExternal | onFulfilled, onRejected | True Promise method. Using this 'exits' the Worker chain - you will not be able to continue chaining Worker methods after .thenExternal. |
| catch, catchExternal | onRejected | Standard Promise method. catchExternal exits the Worker chain - you will not be able to continue chaining Worker methods after .catchExternal. |
| error | msg | Throws an error in the Worker's Promise chain. |
A few aliases are also provided for convenience:
| Method | Alias |
|---|---|
| save | saveAs |
| set | using |
| output | export |
| then | run |
html2pdf.js can be configured using an optional opt parameter:
var element = document.getElementById('element-to-print');
var opt = {
margin: 1,
filename: 'myfile.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
// New Promise-based usage:
html2pdf().set(opt).from(element).save();
// Old monolithic-style usage:
html2pdf(element, opt);
The opt parameter has the following optional fields:
| Name | Type | Default | Description |
|---|---|---|---|
| margin | number or array | 0 | PDF margin (in jsPDF units). Can be a single number, [vMargin, hMargin], or [top, left, bottom, right]. |
| filename | string | 'file.pdf' | The default filename of the exported PDF. |
| pagebreak | object | {mode: ['css', 'legacy']} | Controls the pagebreak behaviour on the page. See Page-breaks below. |
| image | object | {type: 'jpeg', quality: 0.95} | The image type and quality used to generate the PDF. See Image type and quality below. |
| enableLinks | boolean | true | If enabled, PDF hyperlinks are automatically added ontop of all anchor tags. |
| html2canvas | object | { } | Configuration options sent directly to html2canvas (see here for usage). |
| jsPDF | object | { } | Configuration options sent directly to jsPDF (see here for usage). |
html2pdf.js has the ability to automatically add page-breaks to clean up your document. Page-breaks can be added by CSS styles, set on individual elements using selectors, or avoided from breaking inside all elements (avoid-all mode).
By default, html2pdf.js will respect most CSS break-before, break-after, and break-inside rules, and also add page-breaks after any element with class html2pdf__page-break (for legacy purposes).
| Setting | Type | Default | Description |
|---|---|---|---|
| mode | string or array | ['css', 'legacy'] | The mode(s) on which to automatically add page-breaks. One or more of 'avoid-all', 'css', and 'legacy'. |
| before | string or array | [] | CSS selectors for which to add page-breaks before each element. Can be a specific element with an ID ('#myID'), all elements of a type (e.g. 'img'), all of a class ('.myClass'), or even '*' to match every element. |
| after | string or array | [] | Like 'before', but adds a page-break immediately after the element. |
| avoid | string or array | [] | Like 'before', but avoids page-breaks on these elements. You can enable this feature on every element using the 'avoid-all' mode. |
| Mode | Description |
|---|---|
| avoid-all | Automatically adds page-breaks to avoid splitting any elements across pages. |
| css | Adds page-breaks according to the CSS break-before, break-after, and break-inside properties. Only recognizes always/left/right for before/after, and avoid for inside. |
| legacy | Adds page-breaks after elements with class html2pdf__page-break. This feature may be removed in the future. |
// Avoid page-breaks on all elements, and add one before #page2el.
html2pdf().set({
pagebreak: { mode: 'avoid-all', before: '#page2el' }
});
// Enable all 'modes', with no explicit elements.
html2pdf().set({
pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
});
// No modes, only explicit elements.
html2pdf().set({
pagebreak: { before: '.beforeClass', after: ['#after1', '#after2'], avoid: 'img' }
});
You may customize the image type and quality exported from the canvas by setting the image option. This must be an object with the following fields:
| Name | Type | Default | Description |
|---|---|---|---|
| type | string | 'jpeg' | The image type. HTMLCanvasElement only supports 'png', 'jpeg', and 'webp' (on Chrome). |
| quality | number | 0.95 | The image quality, from 0 to 1. This setting is only used for jpeg/webp (not png). |
These options are limited to the available settings for HTMLCanvasElement.toDataURL(), which ignores quality settings for 'png' images. To enable png image compression, try using the canvas-png-compression shim, which should be an in-place solution to enable png compression via the quality option.
The Worker object returned by html2pdf() has a built-in progress-tracking mechanism. It will be updated to allow a progress callback that will be called with each update, however it is currently a work-in-progress.
html2pdf.js depends on the external packages html2canvas and jsPDF. These dependencies are automatically loaded when using NPM or the bundled package.
If using the unbundled dist/html2pdf.min.js (or its un-minified version), you must also include each dependency. Order is important, otherwise html2canvas will be overridden by jsPDF's own internal implementation:
<script src="jspdf.min.js"></script>
<script src="html2canvas.min.js"></script>
<script src="html2pdf.min.js"></script>
[!TIP] Working on html2pdf.js locally? Use
npm startto host local demos on http://localhost:8000.
When submitting an issue, please provide reproducible code that highlights the issue, preferably by creating a fork of this template jsFiddle (which has html2pdf.js already loaded). Remember that html2pdf.js uses html2canvas and jsPDF as dependencies, so it's a good idea to check each of those repositories' issue trackers to see if your problem has already been addressed.
Rendering: The rendering engine html2canvas isn't perfect (though it's pretty good!). If html2canvas isn't rendering your content correctly, I can't fix it.
Node cloning (CSS etc): The way html2pdf.js clones your content before sending to html2canvas is buggy. A fix is currently being developed - try out:
dist/html2pdf.bundle.js)npm install eKoopmans/html2pdf.js#bugfix/clone-nodes-BUILDResizing: Currently, html2pdf.js resizes the root element to fit onto a PDF page (causing internal content to "reflow").
Rendered as image: html2pdf.js renders all content into an image, then places that image into a PDF.
Promise clashes: html2pdf.js relies on specific Promise behaviour, and can fail when used with custom Promise libraries.
Maximum size: HTML5 canvases have a maximum height/width. Anything larger will fail to render.
html2pdf.js performs automatic vdiff (visual difference) comparisons on PDFs generated from a collection of sample HTML files. Contributions of additional test cases are more than welcome - see test/vdiff/html2pdf.vdiff.js and test/reference/*.html for examples. Some changes may require adding more options to the test harness, test/util/test-harness.js.
If you want to create a new feature or bugfix, please feel free to fork and submit a pull request! Create a fork, branch off of main, and make changes to the /src/ files (rather than directly to /dist/). You can test your changes by rebuilding with npm run build.
Copyright (c) 2017-2019 Erik Koopmans <http://www.erik-koopmans.com/>