pdf-lib

1.17.1 · active · verified Sun Apr 19

`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.

Common errors

Warnings

Install

Imports

Quickstart

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);

view raw JSON →