Registry / serialization / pdf-lib

pdf-lib

JSON →
library1.17.1jsnpmunverified

`pdf-lib` is a robust and actively maintained JavaScript library designed for creating and modifying PDF documents in any modern JavaScript environment, including Node.js, browsers, Deno, and React Native. Currently at version 1.17.1, it receives frequent minor and patch releases, with major versions introducing significant architectural changes. A key differentiator of `pdf-lib` from many other open-source PDF libraries is its comprehensive support for *modifying* existing PDF documents, not just creating new ones. Its features include drawing text, images, and vector graphics, embedding fonts (with UTF-8 and UTF-16 support), managing pages (add, insert, remove, copy), creating and filling forms, and setting/reading document metadata and viewer preferences. The library is written in TypeScript, providing excellent type support for its users.

npm install pdf-lib
INSTALL
IMPORT
SIG · PDF-LIB
P
pdf-lib
serializationjavascriptv1.17.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PDFDocument
import { PDFDocument } from 'pdf-lib'
const PDFDocument = require('pdf-lib').PDFDocument
The primary class for creating and modifying PDFs. Asynchronous methods like `create()` and `load()` require `await` since v1.0.0.
rgb
import { rgb } from 'pdf-lib'
import rgb from 'pdf-lib/lib/api/colors/rgb'
A utility function for defining RGB colors, commonly used for drawing operations.
StandardFonts
import { StandardFonts } from 'pdf-lib'
import { HELVETICA } from 'pdf-lib/lib/api/fonts/StandardFonts'
An enum providing access to the 14 standard PDF fonts (e.g., `TimesRoman`, `Helvetica`).
PDFName
import { PDFName } from 'pdf-lib'
import { PDFName } from 'pdf-lib/es/core/objects/PDFName'
Needed for looking up dictionary entries with string keys, especially after v1.0.0's changes to `get()` methods.

This example demonstrates creating a new PDF document, embedding a standard font, adding a page, drawing text, and serializing the document to bytes.

import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'; async function createPdf() { // Create a new PDFDocument const pdfDoc = await PDFDocument.create(); // Embed the Times Roman font const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman); // Add a blank page to the document const page = pdfDoc.addPage(); // Get the width and height of the page const { width, height } = page.getSize(); // Draw a string of text toward the top of the page const fontSize = 30; page.drawText('Creating PDFs with pdf-lib is awesome!', { x: 50, y: height - 4 * fontSize, size: fontSize, font: timesRomanFont, color: rgb(0, 0.53, 0.71), }); // Serialize the PDFDocument to bytes (a Uint8Array) const pdfBytes = await pdfDoc.save(); // In a Node.js environment, you could write this to a file: // import { writeFileSync } from 'node:fs'; // writeFileSync('example.pdf', pdfBytes); // In a browser, you might open it in a new tab: // const blob = new Blob([pdfBytes], { type: 'application/pdf' }); // const url = URL.createObjectURL(blob); // window.open(url, '_blank'); console.log('PDF created successfully (or bytes generated).'); return pdfBytes; } createPdf().catch(console.error);
Debug
Known issues
breakingVersion 1.0.0 introduced significant breaking changes. Key API methods such as `PDFDocument.create()`, `PDFDocument.load()`, and `pdfDoc.save()` became asynchronous and now return Promises. Additionally, `PDFDocumentFactory` was renamed to `PDFDocument`, and the page drawing API was simplified from content streams to direct methods (e.g., `page.drawText`). The `getMaybe` method was removed, and string-based dictionary lookups with `get` now require wrapping strings in `PDFName.of()`.
fix
Ensure all calls to `create()`, `load()`, and `save()` are `await`ed. Update `PDFDocumentFactory` references to `PDFDocument`. Refactor drawing logic to use direct `page.draw...` methods. Replace `getMaybe` with `get` and use `PDFName.of()` for string keys.
affects: >=1.0.0
gotchaEmbedding custom fonts requires the separate `@pdf-lib/fontkit` package to be installed and registered with `pdfDoc.registerFontkit(fontkit)`.
fix
Install `@pdf-lib/fontkit` via npm (`npm install @pdf-lib/fontkit`) and register it before attempting to embed custom fonts: `import fontkit from '@pdf-lib/fontkit'; pdfDoc.registerFontkit(fontkit);`.
affects: >=0.x
gotchaThe `pdf-lib` bundle size, especially when including `@pdf-lib/fontkit` for custom font support, can be large. This is a consideration for browser-based applications where bundle size impacts load times.
fix
If custom fonts are not needed, avoid installing `@pdf-lib/fontkit`. For browser environments, consider using CDN builds that don't include `fontkit` if feasible, or optimize your build process. Recent versions (post v0.5.1) have seen bundle size reductions.
affects: >=0.x
gotcha`pdf-lib` does not officially support modifying encrypted PDF documents. Attempting to load and save encrypted PDFs may result in unexpected behavior, errors, or corrupted output.
fix
Avoid using `pdf-lib` with encrypted documents. If encryption is a requirement, preprocess the PDF to remove encryption before using `pdf-lib` or consider alternative solutions designed for encrypted PDF handling.
affects: >=0.x
breakingImage embedding methods `pdfDoc.embedJPG()` and `pdfDoc.embedPNG()` were renamed to `pdfDoc.embedJpg()` and `pdfDoc.embedPng()` respectively (lowercase 'g' and 'n') for consistency.
fix
Update method calls from `embedJPG` to `embedJpg` and `embedPNG` to `embedPng`.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'addPage')
Attempting to use methods on the `pdfDoc` object immediately after `PDFDocument.create()` or `PDFDocument.load()` without awaiting the Promise.
fix
Ensure `PDFDocument.create()` and `PDFDocument.load()` are awaited, as they return Promises since v1.0.0: `const pdfDoc = await PDFDocument.create();`
The font '...' contains a bad /BBox. (Adobe Reader error)
Issues when processing complex or malformed PDFs, or specific font embedding problems leading to an invalid PDF structure after saving.
fix
Validate the original PDF with external tools (e.g., qpdf) if possible. Try simplifying the operations performed on the PDF. If re-saving an existing PDF, try `pdfDoc.save({ useObjectStreams: false })` as a workaround for some legacy viewer issues. Ensure embedded fonts are correctly registered and compatible.
TypeError: pdfDoc.embedJPG is not a function
Using the old casing for image embedding methods after upgrading to `pdf-lib` v1.0.0 or later.
fix
Rename `pdfDoc.embedJPG()` to `pdfDoc.embedJpg()` and `pdfDoc.embedPNG()` to `pdfDoc.embedPng()`.
Standard fonts in pdf-lib cannot encode certain characters outside WinAnsi.
Attempting to draw text with characters not supported by the standard PDF fonts (e.g., `TimesRoman`, `Helvetica`), which primarily support the WinAnsi encoding.
fix
For text containing characters outside WinAnsi (e.g., Unicode characters, emojis), embed a custom font that supports the required character set (e.g., `fontBytes = await fetch('/path/to/my-font.ttf').then(res => res.arrayBuffer()); const customFont = await pdfDoc.embedFont(fontBytes);`). Remember to install and register `@pdf-lib/fontkit` for custom fonts.
TypeError: pdfDoc.catalog.getMaybe is not a function
The `getMaybe` method was removed in `pdf-lib` v1.0.0.
fix
Replace `getMaybe` calls with `get`. If looking up a string-based dictionary key, wrap the string in `PDFName.of()`: `pdfDoc.catalog.get(PDFName.of('AcroForm'))`.
Upgrade
Version history
1.17.1latest on npm
Audit
Dependencies
@pdf-lib/fontkitoptionalRequired for embedding custom fonts. It is an optional dependency to keep the main bundle size smaller.
Agent activity
5 hits · last 30 days
node
4
OpenAI (training)
1
Resources