PDF Generation in JavaScript: pdf-lib Library

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is pdf-lib and why is it needed?

pdf-lib is a powerful and pure JavaScript library for creating and modifying PDF documents on the server side (Node.js) and in the browser. Unlike heavyweight solutions like Puppeteer, pdf-lib does not require installing a browser or external dependencies. It works directly with the PDF specification, making it an ideal choice for generating simple to moderately complex documents: reports, invoices, certificates, forms, and contracts.

Installation

To install it in a Node.js project, run the command:

npm install pdf-lib

The library has no native dependencies and is compatible with Node.js 10+.

Main Features

  • Creating PDFs from scratch (blank pages, text, images, font embedding).
  • Editing existing PDFs (extracting pages, inserting, deleting, rotating).
  • Working with forms (filling fields, creating checkboxes and radio buttons).
  • Support for Unicode and custom fonts (TTF, OTF).
  • Adding metadata (author, title, date).
  • Export to ArrayBuffer, Uint8Array, or Blob.

JavaScript Code Example (Node.js)

Below is a simple example of creating a PDF with text 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]); // Adding text page.drawText('Hello, World!', { x: 50, y: 350, size: 30, color: rgb(0, 0.53, 0.71), }); // Embedding a font (optional) const fontBytes = fs.readFileSync('./fonts/roboto.ttf'); const font = await doc.embedFont(fontBytes); page.drawText('Custom Font', { x: 50, y: 300, size: 20, font: font, }); // Saving const pdfBytes = await doc.save(); fs.writeFileSync('output.pdf', pdfBytes); console.log('PDF created!');}

createPDF().catch(console.error);

This code creates a document with two lines, one of which uses an embedded font. To work with images, use doc.embedPng() or doc.embedJpg().

When to use pdf-lib

  • You need to quickly generate a PDF without launching a browser.
  • The document does not contain complex layouts (tables, columns) — for that, templating engines like Puppeteer are better suited.
  • A lightweight library with a minimal size (~500 KB) is required.
  • You are working with forms or editing existing PDFs.

Conclusion

pdf-lib is an excellent choice for projects that require PDF generation on Node.js without unnecessary dependencies. It is easy to learn, well-documented, and supports all basic operations. For complex layouts, consider Puppeteer or jsPDF, but for 80% of tasks, pdf-lib will be more than sufficient.

Recommendations