pdf-lib

repository·master·Indexed 27 days ago

https://github.com/hopding/pdf-lib

A JavaScript library for creating and modifying PDF documents that runs in Node, Browser, Deno, and React Native. Key features include document manipulation (adding, inserting, or removing pages), creating and filling PDF forms, drawing text, images, and vector graphics, embedding fonts with UTF-8/UTF-16 support, and managing document metadata.

Tokens
10.1K
Snippets
23
Records
65
Agent score
94%

What's inside pdf-lib

  1. Overview of pdf-lib features

    master

    pdf-lib is a library for creating and modifying PDF documents in any modern JavaScript runtime, including Node, Browser, Deno, and React Native.

    Key capabilities include:

    • Document Manipulation: Create new PDFs, modify existing ones, add, insert, or remove pages, and copy pages between documents.
    • Form Handling: Create, fill, and flatten PDF forms.
    • Drawing & Content: Draw text, images (PNG/JPEG), PDF pages, vector graphics, and SVG paths. It also supports measuring text width and height.
    • Fonts: Embed fonts with support for UTF-8 and UTF-16 character sets.
    • Metadata & Preferences: Set and read document metadata and viewer preferences.
    • Attachments: Add attachments to PDF documents.
  2. Explore PDF 2.0 example files

    master
    The pdf20examples collection provides a set of simple PDF 2.0 files intended for educational purposes. These files demonstrate specific features introduced in the PDF 2.0 specification, such as UTF-8 encoding, black point compensation, and page-level output intents. Use these files to test how your PDF parser or viewer handles new PDF 2.0 standards.
  3. Understand pdf-lib limitations

    master

    Before using pdf-lib, be aware of the following functional limitations:

    • Text Extraction/Editing: You can extract or edit text within form fields (using PDFTextField.getText or PDFTextField.setText), but you cannot extract or edit plain text that exists on a page outside of a form field.
    • HTML/CSS Support: pdf-lib does not support HTML or CSS. You cannot use HTML/CSS to add content to or embed content into a PDF. If you require HTML-to-PDF capabilities, consider using Puppeteer.
    • Encryption: As noted in the encryption handling section, pdf-lib does not support encrypted documents for modification.
  4. Install and register @pdf-lib/fontkit

    master

    To support embedding custom fonts, you must install the @pdf-lib/fontkit module and register it with your PDFDocument instance using pdfDoc.registerFontkit(fontkit) before attempting to embed custom fonts.

    # With npm
    npm install --save @pdf-lib/fontkit
    
    # With yarn
    yarn add @pdf-lib/fontkit
    import { PDFDocument } from 'pdf-lib'
    import fontkit from '@pdf-lib/fontkit'
    
    const pdfDoc = await PDFDocument.create()
    pdfDoc.registerFontkit(fontkit)
  5. Run integration tests for different environments

    master

    Integration tests are located in the apps/ directory and ensure the project works across different JavaScript environments. Note: You must run yarn build to compile the code before running these tests.

    • Node.js: yarn apps:node (follow terminal prompts)
    • Deno: yarn apps:deno (follow terminal prompts)
    • Browser: yarn apps:web (open http://localhost:8080/apps/web/test1.html in your browser)
    • React Native (iOS): yarn apps:rn:ios (use the simulator)
    • React Native (Android):
      adb reverse tcp:8080 tcp:8080
      yarn apps:rn:android
    yarn apps:node
    yarn apps:deno
    yarn apps:web
    yarn apps:rn:ios
    abd reverse tcp:8080 tcp:8080
    yarn apps:rn:android
  6. Draw content on a page using PDFPage methods

    master

    In v1.0.0, drawing content is simplified. Instead of manually creating and registering content streams, you can call drawing methods directly on a PDFPage instance.

    Supported methods include:

    • PDFPage.drawText
    • PDFPage.drawImage
    • PDFPage.drawRectangle
    • PDFPage.drawSvgPath
    page.drawText('Creating PDFs in JavaScript is awesome!', {
      x: 50,
      y: 450,
      size: 15,
      font: timesRomanFont,
      color: rgb(0, 0.53, 0.71),
    });
  7. Use pdf-lib in Deno

    master

    pdf-lib supports the Deno runtime. To use it, import pdf-lib and @pdf-lib/fontkit via a CDN like Skypack, as Deno requires module references via URLs.

    To create a document in Deno:

    import {
      PDFDocument,
      StandardFonts,
      rgb,
    } from 'https://cdn.skypack.dev/pdf-lib@^1.11.1?dts';
    
    const pdfDoc = await PDFDocument.create();
    const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
    
    const page = pdfDoc.addPage();
    const { width, height } = page.getSize();
    const fontSize = 30;
    page.drawText('Creating PDFs in JavaScript is awesome!', {
      x: 50,
      y: height - 4 * fontSize,
      size: fontSize,
      font: timesRomanFont,
      color: rgb(0, 0.53, 0.71),
    });
    
    const pdfBytes = await pdfDoc.save();
    
    await Deno.writeFile('out.pdf', pdfBytes);

    Execute the script using: deno run --allow-write <filename>.ts

  8. Embed custom fonts for Unicode support

    master

    To use characters outside the Latin alphabet (Unicode), you must embed a custom font. This requires loading the font data (e.g., from a file or network request) and passing it to embedFont. You must also register fontkit using pdfDoc.registerFontkit(fontkit) to support advanced font features.

    import { PDFDocument } from 'pdf-lib'
    import fontkit from '@pdf-lib/fontkit'
    
    const url = 'https://pdf-lib.js.org/assets/ubuntu/Ubuntu-R.ttf'
    const fontBytes = await fetch(url).then((res) => res.arrayBuffer())
    
    const pdfDoc = await PDFDocument.create()
    
    pdfDoc.registerFontkit(fontkit)
    const ubuntuFont = await pdfDoc.embedFont(fontBytes)
    
    const page = pdfDoc.addPage()
    page.drawText('Some fancy Unicode text in the ŪЬȕǹƚü font', {
      font: ubuntuFont,
    })