Introduction
pdf-lib is a pure JavaScript library that can both create new PDF documents and modify existing ones. Unlike many PDF tools that only support generation, pdf-lib can load a PDF, add pages, fill form fields, embed images, and merge documents. It runs everywhere JavaScript runs: Node.js, browsers, Deno, React Native, and edge runtimes, with zero native dependencies.
What pdf-lib Does
- Creates new multi-page PDF documents from scratch
- Loads and modifies existing PDF files (add text, images, pages)
- Fills and reads PDF form fields (AcroForms)
- Merges pages from multiple PDF documents into one
- Embeds fonts, PNG images, and JPEG images
Architecture Overview
pdf-lib parses PDF files into an in-memory object model representing the PDF's cross-reference table, object streams, and page tree. Modifications are applied to this model, and the library serializes it back into valid PDF bytes. Because it is written in pure TypeScript with no native bindings, it works identically across all JavaScript runtimes. Font embedding uses a built-in subset of standard fonts, with support for custom TrueType font embedding.
Self-Hosting & Configuration
- Install via npm:
npm install pdf-lib - For custom fonts, also install
@pdf-lib/fontkit:npm install @pdf-lib/fontkit - Load an existing PDF:
const pdfDoc = await PDFDocument.load(existingPdfBytes) - Embed custom fonts:
pdfDoc.registerFontkit(fontkit); const font = await pdfDoc.embedFont(fontBytes) - Works directly in browser
<script>tags via CDN with no build step required
Key Features
- Pure JavaScript with zero native dependencies
- Read, create, and modify PDFs in a single library
- AcroForm support for filling and reading interactive form fields
- Page copying and merging across multiple PDF documents
- Works in Node.js, browsers, Deno, React Native, and Cloudflare Workers
Comparison with Similar Tools
- PDFKit — focused on creating new PDFs; pdf-lib can also load and modify existing ones
- jsPDF — simpler API for basic PDF creation; pdf-lib offers richer modification capabilities
- Puppeteer — renders HTML to PDF; pdf-lib works programmatically without a browser engine
- pdf.js (Mozilla) — renders PDFs for viewing; pdf-lib modifies and generates PDF files
FAQ
Q: Can I fill PDF form fields with pdf-lib?
A: Yes. Load a PDF with form fields, then use form.getTextField('name').setText('value') to fill them programmatically.
Q: How do I merge two PDFs?
A: Load both documents, then use pdfDoc.copyPages(otherDoc, [0, 1]) to copy pages from one into the other.
Q: Does pdf-lib support encryption or password protection? A: It can read some encrypted PDFs if the password is provided. Writing encrypted PDFs is not currently supported.
Q: Can I use pdf-lib in a Cloudflare Worker? A: Yes. It is pure JavaScript with no native dependencies, so it runs in any edge runtime.