What is pdf-lib and why is it needed?
pdf-lib is a powerful and lightweight library for creating and editing PDF documents in JavaScript (Node.js and browser). Unlike heavyweight solutions like Puppeteer or jsPDF, pdf-lib does not require a browser environment (Chromium) to be installed and works exclusively with native PDF structures. It is ideal for server-side generation of reports, invoices, certificates, and any other documents where full control over content is needed: text, fonts (including embedding), images, forms, annotations, and pages.
Installation
Installation via npm is simple:
npm install pdf-libThen import it into your project:
const { PDFDocument, rgb, StandardFonts } = require('pdf-lib');Main Features
- Creating PDF from scratch — adding pages, text, images.
- Editing existing PDFs — copying pages, inserting text over them, merging documents.
- Working with fonts — support for standard fonts (Helvetica, TimesRoman) and embedding custom TTF fonts.
- Drawing shapes — lines, rectangles, ellipses with color and transparency settings.
- Forms and annotations — creating text fields, buttons, links.
- Export to Uint8Array — the result can be saved to a file or sent to the client.
Code Example on Node.js
Let's create a simple PDF with a title and an image:
const { PDFDocument, rgb } = require('pdf-lib');const fs = require('fs');
async function createPDF() { const doc = await PDFDocument.create(); const page = doc.addPage([600, 400]); // Text page.drawText('Hello, World!', { x: 50, y: 350, size: 30, color: rgb(0, 0.53, 0.71), }); // Rectangle page.drawRectangle({ x: 50, y: 200, width: 200, height: 100, color: rgb(0.9, 0.1, 0.1), borderColor: rgb(0, 0, 0), borderWidth: 2, }); // Embedding an image (PNG) const imageBytes = fs.readFileSync('logo.png'); const image = await doc.embedPng(imageBytes); page.drawImage(image, { x: 300, y: 250, width: 100, height: 100, }); const pdfBytes = await doc.save(); fs.writeFileSync('output.pdf', pdfBytes);}
createPDF().catch(console.error);When to use pdf-lib?
pdf-lib is the best choice if you are working in a Node.js (or browser) environment and need to:
- Quickly generate PDFs without launching a browser (saving memory and time).
- Embed custom fonts (e.g., for Cyrillic).
- Edit existing PDFs (add watermarks, merge documents).
- Create interactive forms.
Avoid pdf-lib if you need to render complex HTML/CSS into PDF (Puppeteer is better suited here) or work with large volumes of data (heavy PDFs can slow down performance).