Generating PDFs with JavaScript: browser and Node.js
JavaScript has mature libraries for all three ways of making a PDF: drawing it, laying it out from a description, or rendering HTML in a browser. The last of those is its own topic, covered on the HTML-to-PDF page; this page is about the libraries, where each runs, and the mistakes that cost the most time. Every Node example below was executed with the versions stated and the output checked with qpdf and pdf.js before publication.
The libraries#
| Library | Version | Licence | Runs in | Approach | Best for | Not for |
|---|---|---|---|---|---|---|
| pdf-lib | 1.17.1 | MIT | Browser and Node, no native code | Drawing API, plus reading and modifying existing files | Filling forms, stamping, merging, adding pages, small generated documents | Flowing text: there is no line wrapping or pagination |
| PDFKit | 0.17.2 | MIT | Node first; browser through a bundler with a Blob stream | Streaming drawing API with text wrapping, columns, lists, tables (0.16+), outlines, forms | Reports and invoices built from code, large documents streamed to disk or HTTP | Editing existing PDFs |
| pdfmake | 0.3.13 | MIT | Browser and Node | Declarative layout engine (a JSON document definition) on top of PDFKit | Table-heavy documents with repeated structure, defined as data | Pixel-precise placement; modifying files |
| jsPDF | 4.2.1 | MIT | Browser first; Node supported | Drawing API with a `html()` method that renders DOM through html2canvas into jsPDF's canvas context | Client-side exports where no server is available | Faithful HTML rendering, large documents |
| @react-pdf/renderer | 4.9.0 | MIT | Browser and Node | React components with a Flexbox-like layout (Yoga), rendered to PDF | Teams already in React who want layouts as components | Reusing web components: it has its own primitives, not the DOM |
| Headless Chromium | Puppeteer 25, Playwright 1.64 | Apache-2.0 | Node driving a browser process | HTML renderer | Existing HTML templates, rich CSS | Small files, untrusted input, hosts without a browser |
A practical split: pdf-lib for anything that starts from an existing PDF, PDFKit or pdfmake for documents generated on a server, jsPDF when the PDF must be assembled in the user's browser, and Chromium when the source is HTML.
Browser or server#
The same library can behave differently in the two environments. In Node, files come from disk, output is a Buffer written to a file or an HTTP response, and fonts can be read from the filesystem. In the browser, everything is a Uint8Array or a Blob, fonts must be fetched over HTTP, and the result is handed to the user with a download link or an <iframe>. The examples mark which they are. A browser-generated PDF never touches your server, which is a privacy feature and also the reason the browser cannot sign it, add it to an archive or guarantee the fonts used.
Creating a document with an embedded font (pdf-lib)#
pdf-lib's standard fonts are the fourteen that every PDF 1.7 reader must supply, and they only cover the WinAnsi character set. For anything else you embed a TrueType or OpenType font, which needs the companion @pdf-lib/fontkit package.
import { PDFDocument, rgb } from 'pdf-lib';
import fontkit from '@pdf-lib/fontkit';
import { readFileSync, writeFileSync } from 'node:fs';
const doc = await PDFDocument.create();
doc.registerFontkit(fontkit); // required before embedFont with a font file
const font = await doc.embedFont(readFileSync('fonts/NotoSans-Regular.ttf'), { subset: true });
const page = doc.addPage([595.28, 841.89]); // A4 in points; PageSizes.A4 is the same pair
const text = 'Hello, PDF. Grüße, señor, 10 €';
page.drawText(text, { x: 72, y: 770, size: 24, font, color: rgb(0.07, 0.08, 0.1) });
const width = font.widthOfTextAtSize(text, 24); // measure to place the next element
page.drawLine({ start: { x: 72, y: 762 }, end: { x: 72 + width, y: 762 }, thickness: 1, color: rgb(0.1, 0.36, 0.96) });
doc.setTitle('pdf-lib example');
const bytes = await doc.save(); // Uint8Array
writeFileSync('create.pdf', bytes);The output was a 3.3 KB single-page file. qpdf found no errors, pdf.js extracted the string including the accented characters and the euro sign, and the file contains one Type 0 font with a FontFile2 stream, which is an embedded TrueType subset. Without subset: true the whole font program would be embedded, which for a full Noto Sans is several hundred kilobytes. Coordinates are in points from the bottom-left corner; the units page has the conversions.
Modifying an existing document (pdf-lib)#
This is what pdf-lib is best at. It parses the file into objects, lets you draw on existing pages or add new ones, and writes everything back.
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
import { readFileSync, writeFileSync } from 'node:fs';
const doc = await PDFDocument.load(readFileSync('minimal.pdf')); // keeps pages, fonts, metadata
const helvetica = await doc.embedFont(StandardFonts.Helvetica); // standard font: referenced, not embedded
const [first] = doc.getPages();
first.drawText('Stamped by pdf-lib', { x: 72, y: 720, size: 14, font: helvetica, color: rgb(0.6, 0.1, 0.1) });
const page2 = doc.addPage([595.28, 841.89]);
page2.drawText('Page 2, added later.', { x: 72, y: 770, size: 18, font: helvetica });
const bytes = await doc.save({ useObjectStreams: false }); // default true packs objects into compressed streams
writeFileSync('modified.pdf', bytes);Run against the 592-byte minimal file from the anatomy page, this produced a two-page document in which the original "Hello, PDF." content stream is still present and the new text is appended as a second content stream on the same page. pdf-lib rewrites the whole file rather than appending an incremental update, so object numbers change and any existing digital signature is invalidated. The useObjectStreams option is worth knowing: the default output uses object streams and a cross-reference stream (PDF 1.5 features), which some older tools cannot read; setting it to false writes a classic cross-reference table, as explained on the xref page.
A laid-out document (PDFKit)#
PDFKit wraps text, paginates automatically and, since version 0.16, draws tables. It streams output, so a thousand-page report never has to fit in memory.
const PDFDocument = require('pdfkit');
const fs = require('node:fs');
const doc = new PDFDocument({
size: 'A4',
margins: { top: 72, right: 72, bottom: 72, left: 72 },
info: { Title: 'Invoice 1001', Author: 'Example Ltd' }, // document information dictionary
});
doc.pipe(fs.createWriteStream('invoice.pdf')); // or pipe to an HTTP response
doc.registerFont('Body', 'fonts/NotoSans-Regular.ttf'); // embedded as a subset on first use
doc.font('Body').fontSize(20).text('Invoice 1001');
doc.moveDown(0.5).fontSize(10).fillColor('#444')
.text('Payment is due within 30 days. This paragraph wraps automatically inside the page margins.', { width: 451 });
doc.moveDown(1.5).fillColor('#000');
doc.table({
columnStyles: [250, '*', '*', '*'], // fixed first column, the rest share the remaining width
data: [
['Item', 'Qty', 'Unit', 'Total'],
['Design work', '12', '80.00', '960.00'],
['Hosting (12 months)', '1', '120.00', '120.00'],
['Domain renewal', '1', '15.00', '15.00'],
],
});
doc.fontSize(11).text('Total: 1 095.00 EUR', 72, doc.y + 10, { align: 'right', width: 451 });
doc.end();The result was a single A4 page with the paragraph wrapped over two lines, the table ruled and aligned, and Noto Sans embedded as a Type 0 subset. The width of 451 pt is the A4 width minus the two 72 pt margins; PDFKit measures in points throughout. For a document with many rows, doc.table continues across pages on its own; for prose, doc.text does. Headers and footers are drawn by listening for the pageAdded event and drawing into the margin area.
pdfmake sits on top of PDFKit and replaces this imperative code with a document definition object ({ content: [...], styles: {...} }), which is easier to generate from data and to review in a pull request. Use it when the document is mostly tables and paragraphs with a consistent style; drop down to PDFKit when you need precise control of a single element.
In the browser (jsPDF)#
jsPDF runs entirely in the page. This snippet is browser-only and was not executed as part of this build.
import { jsPDF } from 'jspdf';
const doc = new jsPDF({ unit: 'pt', format: 'a4' }); // default unit is mm; pt matches PDF coordinates
doc.setFont('helvetica', 'normal'); // standard font: Latin text only
doc.setFontSize(18);
doc.text('Quarterly summary', 72, 72); // origin is top-left in jsPDF, unlike PDF itself
doc.setFontSize(11);
doc.text(doc.splitTextToSize('Long paragraphs are wrapped with splitTextToSize before drawing.', 451), 72, 100);
doc.save('summary.pdf'); // triggers a download; doc.output('blob') for an iframeTwo points about jsPDF that are often misunderstood. Its coordinate origin is the top-left corner, so y grows downwards; the library converts to PDF's bottom-left origin when it writes the file. And its html() method is not a browser print pipeline: it uses html2canvas to walk the DOM and draws the result into jsPDF's own canvas-like context, so text stays text only when jsPDF has the font (a standard font or one supplied through the fontFaces option), and layout fidelity is limited to what html2canvas understands. For a faithful rendering of real HTML you need a browser engine, which means a server running headless Chromium.
pdf-lib also runs in the browser with the same API as above: fetch the font with fetch() into an ArrayBuffer, and turn doc.save() into a download with new Blob([bytes], { type: 'application/pdf' }) and an object URL.
Traps#
Standard fonts and non-Latin text. StandardFonts.Helvetica in pdf-lib, 'Helvetica' in PDFKit and jsPDF's built-in fonts all use WinAnsiEncoding. They can draw accented Latin characters and the euro sign; they throw or print garbage for Greek, Cyrillic, CJK, emoji and even some Latin letters with diacritics such as "ā". The fix is always the same: embed a TrueType or OpenType font that has the glyphs, as in the first example. The fonts page explains what the file contains afterwards.
Font licences. Embedding a font in a PDF is distribution. Google Fonts and other OFL fonts allow it; many commercial fonts allow embedding only as a subset, and some forbid it through the fsType flag that pdf-lib and PDFKit do not check for you.
Buffers. doc.save() in pdf-lib returns a Uint8Array; Node's fs accepts it directly, and Express needs res.end(Buffer.from(bytes)) or res.send(Buffer.from(bytes)). In the browser, wrap it in a Blob. PDFKit is a readable stream and should be piped rather than collected, except for small files.
Large documents. pdf-lib and jsPDF build the entire file in memory, which is fine up to a few thousand pages of text and a problem with many images. PDFKit streams; pair it with fs.createWriteStream or an HTTP response and memory stays flat.
Page size. Every library takes points. A4 is 595.28 × 841.89 pt and Letter is 612 × 792 pt; PageSizes.A4 in pdf-lib and size: 'A4' in PDFKit expand to those. jsPDF's default unit is millimetres unless you pass unit: 'pt', which is the source of many off-by-a-factor-of-2.83 bugs. The units reference lists the conversions.
Metadata. pdf-lib exposes setTitle, setAuthor, setSubject, setKeywords, setProducer, setCreator, setCreationDate and setModificationDate; they write the information dictionary only, and there is no XMP API (the metadata page shows how to add an XMP packet through the low-level object API). PDFKit takes an info object in the constructor. jsPDF has setProperties. What each tool reads afterwards is covered on the metadata page.
Compression and structure. pdf-lib's default output uses object streams (PDF 1.5); PDFKit writes a classic cross-reference table unless its objectStreams option is set, which in turn requires pdfVersion: '1.5' or later. Neither matters for modern readers, but a downstream tool that chokes on one form is easier to diagnose if you know which form you produced. The compression page and the xref page cover both.
Verification. Open the output in more than one viewer, run qpdf --check, and look at the fonts with the PDF inspector. A file that opens in Chrome but not in Preview, or that prints with the wrong font, is almost always a font or encoding problem that an inspector shows in seconds.