@pdfme/common, jspdf, pdf-lib, pdfjs-dist, pdfkit, pdfmake, and react-pdf are JavaScript libraries that address different aspects of PDF handling in web applications. jspdf, pdf-lib, pdfkit, and pdfmake focus on generating or modifying PDF documents programmatically in the browser or Node.js. pdfjs-dist (Mozilla’s PDF.js) specializes in rendering existing PDFs as images or HTML in the browser. react-pdf is a React-specific wrapper around PDF.js for declarative PDF viewing. @pdfme/common provides shared utilities for the PDFme ecosystem, primarily used alongside @pdfme/generator and @pdfme/ui for template-based PDF generation and form filling.
Working with PDFs in web apps falls into three distinct categories: generating new documents, modifying existing ones, and rendering/viewing PDF content. The libraries in this comparison each specialize in one or more of these areas — and choosing the wrong tool leads to frustration. Let’s break down how they differ in practice.
jspdf: Generate New PDFs Imperativelyjspdf creates PDFs from scratch using an imperative, canvas-like API. You call methods like .text() or .rect() to draw content at specific coordinates.
import jsPDF from 'jspdf';
const doc = new jsPDF();
doc.text('Hello world!', 10, 10);
doc.save('output.pdf');
pdf-lib: Modify Existing PDFspdf-lib reads, alters, and writes PDFs. It can fill form fields, add pages, or merge documents — but doesn’t render them visually.
import { PDFDocument } from 'pdf-lib';
const existingPdfBytes = await fetch('/form.pdf').then(res => res.arrayBuffer());
const pdfDoc = await PDFDocument.load(existingPdfBytes);
const form = pdfDoc.getForm();
form.getTextField('name').setText('John Doe');
const modifiedPdfBytes = await pdfDoc.save();
pdfjs-dist: Render Existing PDFspdfjs-dist converts PDF pages into canvases or SVGs for display. It doesn’t create or edit PDFs.
import * as pdfjsLib from 'pdfjs-dist';
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';
const loadingTask = pdfjsLib.getDocument('/document.pdf');
const pdf = await loadingTask.promise;
const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 1.5 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({ canvasContext: context, viewport }).promise;
document.body.appendChild(canvas);
pdfkit: Generate PDFs with Low-Level Controlpdfkit offers granular control over PDF generation, supporting paths, gradients, and custom fonts. It’s stream-friendly for server-side use.
import PDFDocument from 'pdfkit';
import blobStream from 'blob-stream'; // for browser output
const doc = new PDFDocument();
const stream = doc.pipe(blobStream());
doc.fontSize(25).text('Here is a PDF document.', 100, 100);
doc.end();
stream.on('finish', () => {
const url = stream.toBlobURL('application/pdf');
window.open(url);
});
pdfmake: Declarative Document Layoutpdfmake uses a JSON-like structure to define documents, handling pagination and styling automatically.
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
const docDefinition = {
content: [
{ text: 'My Report', style: 'header' },
'This is a sample report.'
],
styles: { header: { fontSize: 18, bold: true } }
};
pdfMake.createPdf(docDefinition).download('report.pdf');
react-pdf: React Component for Viewing PDFsreact-pdf wraps PDF.js into React components, simplifying integration into React apps.
import { Document, Page } from 'react-pdf';
function PdfViewer() {
return (
<Document file="/sample.pdf">
<Page pageNumber={1} />
</Document>
);
}
@pdfme/common: Shared Utilities for PDFme EcosystemThis package exports types and helper functions used by @pdfme/generator (for template-based PDF creation) and @pdfme/ui (for interactive form filling). It has no standalone functionality.
// Typically used internally by other PDFme packages
import { Template } from '@pdfme/common';
// Not used directly for PDF generation or rendering
If you need to fill form fields, add watermarks, or merge documents, pdf-lib is the only viable option among these libraries. None of the others support reading and altering existing PDF structures.
jspdf, pdfkit, and pdfmake generate new PDFs only.pdfjs-dist and react-pdf are viewers.@pdfme/common isn’t a PDF processor.// pdf-lib: Merge two PDFs
const [pdf1, pdf2] = await Promise.all([
PDFDocument.load(bytes1),
PDFDocument.load(bytes2)
]);
const mergedPdf = await PDFDocument.create();
const copiedPages = await mergedPdf.copyPages(pdf2, pdf2.getPageIndices());
copiedPages.forEach(page => mergedPdf.addPage(page));
For displaying existing PDFs, you have two practical choices:
pdfjs-dist: Full control over rendering logic. Use when you need custom UI (e.g., thumbnail navigation, text layer tweaks).react-pdf: Simplified React integration. Use when you’re in a React app and want minimal setup.Both rely on the same underlying engine (PDF.js), so rendering quality is identical. react-pdf just hides the canvas/SVG plumbing.
// react-pdf handles loading, scaling, and error states
<Document file="/doc.pdf" onLoadSuccess={({ numPages }) => console.log(numPages)}>
{[...Array(numPages)].map((_, i) => <Page key={i + 1} pageNumber={i + 1} />)}
</Document>
jspdf)Best for simple layouts where you control every coordinate. Becomes unwieldy for multi-page documents with dynamic content.
// jspdf: Manual line breaks and page management
const doc = new jsPDF();
let y = 10;
['Line 1', 'Line 2', 'Line 3'].forEach(line => {
if (y > 280) { doc.addPage(); y = 10; }
doc.text(line, 10, y);
y += 10;
});
pdfmake)Handles pagination, tables, and styling automatically. Ideal for reports, invoices, or any document with repeating structures.
// pdfmake: Automatic page breaks in tables
const docDefinition = {
content: [{
table: {
body: data.map(row => [row.id, row.name])
}
}]
};
pdfkit)Use when you need vector graphics, custom color spaces, or streaming output (e.g., sending PDFs directly from a Node.js server without buffering).
// pdfkit: Draw a custom path
const doc = new PDFDocument();
doc.moveTo(100, 100).lineTo(200, 200).stroke();
jspdf doesn’t support embedding existing PDF pages or form filling.pdfmake cannot modify existing PDFs — only generate new ones.pdfjs-dist and react-pdf cannot create PDFs; they’re viewers only.pdfkit in the browser requires bundler configuration for font support.@pdfme/common is not a standalone tool — it’s a dependency for other PDFme packages.Real-world apps often need both generation and viewing:
pdf-lib to fill a template PDF, then react-pdf to preview the result.pdfmake, save it as a Blob, and display it using pdfjs-dist.Example: Fill form → Preview
// Step 1: Modify with pdf-lib
const filledPdfBytes = await fillForm(templateBytes, data);
const blob = new Blob([filledPdfBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
// Step 2: Preview with react-pdf
<Document file={url}>
<Page pageNumber={1} />
</Document>
| Task | Best Library |
|---|---|
| Generate simple PDFs | jspdf |
| Generate complex reports | pdfmake |
| Low-level PDF creation | pdfkit |
| Modify existing PDFs | pdf-lib |
| View PDFs in vanilla JS | pdfjs-dist |
| View PDFs in React | react-pdf |
| Work with PDFme templates | @pdfme/common* |
* Only as part of the broader PDFme ecosystem.
Choose based on whether you’re creating, changing, or showing PDFs — and never try to force a viewer into a generator role (or vice versa).
Choose jspdf when you need a battle-tested, imperative API for generating simple to moderately complex PDFs directly in the browser with minimal setup. It’s well-suited for reports, invoices, or documents where precise layout control via code is acceptable. Avoid it for advanced typography, complex layouts, or when working with existing PDF templates.
Choose @pdfme/common only if you’re already using the PDFme ecosystem (@pdfme/generator or @pdfme/ui) for template-driven PDF generation with form fields. It’s not a standalone PDF creation or rendering library but rather a set of shared types and utilities. Avoid it for general-purpose PDF tasks outside the PDFme workflow.
Choose pdf-lib when your use case involves modifying existing PDFs — such as filling form fields, adding annotations, merging documents, or extracting pages — in both browser and Node.js environments. Its API is modern and promise-based, making it ideal for workflows that require reading and altering PDF content programmatically.
Choose pdfjs-dist when your primary goal is to display existing PDF files in the browser with high fidelity, including support for text selection, zooming, and accessibility. It’s the engine behind Firefox’s PDF viewer and is best paired with custom UI layers. Do not use it for generating new PDFs from scratch.
Choose pdfkit when you need fine-grained, low-level control over PDF generation with support for vector graphics, custom fonts, and streaming output — especially in Node.js. While it works in the browser via bundlers, its API is more verbose and requires deeper understanding of PDF internals. Avoid it for quick document generation or if you prefer high-level abstractions.
Choose pdfmake when you want to define document structure declaratively using JSON-like objects, supporting tables, lists, headers/footers, and page breaks out of the box. It’s excellent for data-heavy reports with consistent styling and works well in both browser and Node.js. Avoid it if you need pixel-perfect design control or must manipulate existing PDFs.
Choose react-pdf when building a React application that needs to render existing PDF documents with minimal boilerplate. It abstracts PDF.js into React components like <Document> and <Page>, handling loading states and rendering automatically. Do not use it for PDF creation or modification — it’s purely a viewer.
A library to generate PDFs in JavaScript.
You can catch me on twitter: @MrRio or head over to my company's website for consultancy.
jsPDF is now co-maintained by yWorks - the diagramming experts.
Recommended: get jsPDF from npm:
npm install jspdf --save
# or
yarn add jspdf
Or always get latest version via unpkg
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
The dist folder of this package contains different kinds of files:
core-js, the umd variant is self-contained.Usually it is not necessary to specify the exact file in the import statement. Build tools or Node automatically figure out the right file, so importing "jspdf" is enough.
Then you're ready to start making your document:
import { jsPDF } from "jspdf";
// Default export is a4 paper, portrait, using millimeters for units
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
If you want to change the paper size, orientation, or units, you can do:
// Landscape export, 2×4 inches
const doc = new jsPDF({
orientation: "landscape",
unit: "in",
format: [4, 2]
});
doc.text("Hello world!", 1, 1);
doc.save("two-by-four.pdf");
const { jsPDF } = require("jspdf"); // will automatically load the node version
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf"); // will save the file in the current working directory
require(["jspdf"], ({ jsPDF }) => {
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
});
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
We strongly advise you to sanitize user input before passing it to jsPDF!
For reporting security vulnerabilities, please see SECURITY.md.
When running under Node.js, jsPDF will restrict reading files from the local file system by default.
Strongly recommended: use Node's permission flags so the runtime enforces access:
node --permission --allow-fs-read=... ./scripts/generate.js
See Node's documentation for details. Note that you need to include
all imported JavaScript files (including all dependencies) in the --allow-fs-read flag.
Fallback (not recommended): you can allow jsPDF to read specific files by setting jsPDF.allowFsRead in your script.
import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.allowFsRead = ["./fonts/*", "./images/logo.png"]; // allow everything under ./fonts and a single file
Warning: We strongly recommend the Node flags over jsPDF.allowFsRead, as the flags are enforced by the runtime and offer stronger security.
Some functions of jsPDF require optional dependencies. E.g. the html method, which depends on html2canvas and,
when supplied with a string HTML document, dompurify. JsPDF loads them dynamically when required
(using the respective module format, e.g. dynamic imports). Build tools like Webpack will automatically create separate
chunks for each of the optional dependencies. If your application does not use any of the optional dependencies, you
can prevent Webpack from generating the chunks by defining them as external dependencies:
// webpack.config.js
module.exports = {
// ...
externals: {
// only define the dependencies you are NOT using as externals!
canvg: "canvg",
html2canvas: "html2canvas",
dompurify: "dompurify"
}
};
In Vue CLI projects, externals can be defined via the configureWebpack
or chainWebpack properties of the vue.config.js file
(needs to be created, first, in fresh projects).
In Angular projects, externals can be defined using custom webpack builders.
In React (create-react-app) projects, externals can be defined by either using
react-app-rewired or ejecting.
jsPDF can be imported just like any other 3rd party library. This works with all major toolkits and frameworks. jsPDF also offers a typings file for TypeScript projects.
import { jsPDF } from "jspdf";
You can add jsPDF to your meteor-project as follows:
meteor add jspdf:core
jsPDF requires modern browser APIs in order to function. To use jsPDF in older browsers like Internet Explorer, polyfills are required. You can load all required polyfills as follows:
import "jspdf/dist/polyfills.es.js";
Alternatively, you can load the prebundled polyfill file. This is not recommended, since you might end up loading polyfills multiple times. Might still be nifty for small applications or quick POCs.
The 14 standard fonts in PDF are limited to the ASCII-codepage. If you want to use UTF-8 you have to integrate a custom font, which provides the needed glyphs. jsPDF supports .ttf-files. So if you want to have for example Chinese text in your pdf, your font has to have the necessary Chinese glyphs. So, check if your font supports the wanted glyphs or else it will show garbled characters instead of the right text.
To add the font to jsPDF use our fontconverter in /fontconverter/fontconverter.html. The fontconverter will create a js-file with the content of the provided ttf-file as base64 encoded string and additional code for jsPDF. You just have to add this generated js-File to your project. You are then ready to go to use setFont-method in your code and write your UTF-8 encoded text.
Alternatively you can just load the content of the *.ttf file as a binary string using fetch or XMLHttpRequest and
add the font to the PDF file:
const doc = new jsPDF();
const myFont = ... // load the *.ttf font file as binary string
// add the font to jsPDF
doc.addFileToVFS("MyFont.ttf", myFont);
doc.addFont("MyFont.ttf", "MyFont", "normal");
doc.setFont("MyFont");
Since the merge with the yWorks fork there are a lot of new features. However, some of them are API breaking, which is why there is an API-switch between two API modes:
You can switch between the two modes by calling
doc.advancedAPI(doc => {
// your code
});
// or
doc.compatAPI(doc => {
// your code
});
JsPDF will automatically switch back to the original API mode after the callback has run.
Please check if your question is already handled at Stackoverflow https://stackoverflow.com/questions/tagged/jspdf.
Feel free to ask a question there with the tag jspdf.
Feature requests, bug reports, etc. are very welcome as issues. Note that bug reports should follow these guidelines:
jsPDF cannot live without help from the community! If you think a feature is missing or you found a bug, please consider if you can spare one or two hours and prepare a pull request. If you're simply interested in this project and want to help, have a look at the open issues, especially those labeled with "bug".
You can find information about building and testing jsPDF in the contribution guide
Copyright (c) 2010-2025 James Hall, https://github.com/MrRio/jsPDF (c) 2015-2025 yWorks GmbH, https://www.yworks.com/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.