PDFKit Documentation

repository·master·Indexed 27 days ago

https://github.com/foliojs/pdfkit

A JavaScript library for generating complex, multi-page, printable PDF documents in Node.js and browser environments. Version 0.19.1 provides capabilities for document creation using chainable methods for text, images, and vector graphics, as well as comprehensive support for creating PDF/UA (Universal Accessibility) conformant documents through logical structure trees, tagged PDF elements, and marked content sequences.

Tokens
18.7K
Snippets
51
Records
91
Agent score
94%

What's inside pdfkit

  1. Create a PDF document in Node.js

    master

    To create a PDF, require the pdfkit module and instantiate the PDFDocument class. PDFDocument instances are readable Node streams. You must use the pipe method to direct the output to a writable stream (like a file or an HTTP response) and call end() to finalize the document.

    Note: The write and output methods are deprecated and should not be used.

    const PDFDocument = require('pdfkit');
    const fs = require('fs');
    
    const doc = new PDFDocument();
    
    doc.pipe(fs.createWriteStream('/path/to/file.pdf'));
    
    // add stuff to PDF here...
    
    doc.end();
  2. Implement rich text with the continued option

    master

    To change text styles (like color or font) in the middle of a paragraph without breaking the line wrapping, use the continued: true option in the text method. This tells PDFKit to retain the current wrapping state for the next call.

    To remove a link in a rich text sequence, set the link option to null.

    doc.fillColor('green')
       .text(lorem.slice(0, 500), {
         width: 465,
         continued: true
       }).fillColor('red')
       .text(lorem.slice(500));
  3. Create PDF/A documents for long-term archiving

    master

    To create PDF/A compliant documents (ISO 19005-1:2005), set the subset option in the PDFDocument constructor.

    Supported Subsets

    • Level B (Basic): PDF/A-1b, PDF/A-2b, PDF/A-3b
    • Level A (Accessible): PDF/A-1a, PDF/A-2a, PDF/A-3a

    Requirements

    • Fonts: You cannot use standard PDFKit fonts (AFM format) because they do not contain font data. You must use registerFont() with embeddable formats like .ttf.
    • PDF/A-1: Requires pdfVersion to be at least 1.4. For level A (PDF/A-1a), set tagged: true.
    • PDF/A-2 & PDF/A-3: Requires pdfVersion to be at least 1.7. For level A conformance, set tagged: true.
    • Restrictions: PDF/A documents cannot be encrypted and cannot contain JavaScript, audio, or video content.
  4. Add annotations in PDFKit

    master

    Annotations allow you to add interactive features like links, notes, highlights, and underlines to a PDF. Each annotation is defined by a rectangle (x, y, width, height) and optional properties.

    Important: Stacking Order Annotations follow a stacking order. If you are placing multiple annotations on the same area, ensure the link annotation is added last so it is not covered by other visual annotations (like underlines or highlights) and remains clickable.

  5. Initialize forms in PDFKit

    master

    Before adding any form annotations (text fields, buttons, etc.) to a document, you must call the doc.initForm() method. It is recommended to set the default form font using doc.font() before calling initForm().

    doc.font('Helvetica');
    doc.initForm();
    doc.font('Helvetica'); // establishes the default form field font
    doc.initForm();
  6. Style PDFKit tables

    master

    Tables can be styled using defaultStyle, columnStyles, rowStyles, and individual cell styles. Styles follow a specific precedence order:

    1. defaultStyle (lowest precedence)
    2. columnStyles
    3. rowStyles
    4. cellStyle (highest precedence)

    When multiple styles define the same property (like border), they are merged. For example, if defaultStyle defines a top border and a cell defines a left border, the resulting cell will have both.

    Common Styling Tasks

    Zebra Striping: Use rowStyles with a function to apply background colors to alternating rows.

    Custom Borders: Use rowStyles or columnStyles functions to return border objects like { border: [top, right, bottom, left] } or specific side borders like { border: { left: 2 } }.

    Removing Borders: Set border: false in rowStyles to remove all borders from a row.

  7. Build Complex or Nested Structure Trees

    master

    You can create nested structure elements by passing children to doc.struct(). Elements can be added directly to the document or to other structure elements.

    Warning: If you provide children during the creation of a structure element (the atomic style), structElem.end() is called automatically and you cannot use structElem.add() to add more children later. You must choose between the atomic style (passing children in constructor) or the incremental style (using .add()).

    // Create nested structure elements
    const section1 = doc.struct('Sect', [
        doc.struct('P', [
            someTextStructureContent,
            doc.struct('Link', someLinkStructureContent),
            moreTextStructureContent
        ])
    ]);
    const section2 = doc.struct('Sect', secondSectionStructureContent);
    
    // Add them to the document's structure
    doc.addStructure(section1).addStructure(section2);
  8. Incrementally Construct Structure Elements

    master

    For better memory management, you can build structure elements incrementally. This involves creating an element, adding it to a parent, adding content, and then calling .end() to flush it.

    Critical: To prevent your application from hanging when calling doc.end(), ensure every element you create is eventually attached to the document's structure (by adding it to a parent).

    // Begin a new section and add it to the document's structure
    const mySection = doc.struct('Sect');
    doc.addStructure(mySection);
    
    // Create a new paragraph and add it to the section
    const myParagraph = doc.struct('P');
    mySection.add(myParagraph);
    
    // Add content, both to the page, and to the paragraph
    const myParagraphContent = doc.markStructureContent('P');
    myParagraph.add(myParagraphContent);
    doc.text('Hello, world! ');
    
    // End the paragraph, allowing it to be flushed out, freeing memory
    myParagraph.end();
  9. Create a conformant PDF/UA document

    master

    To create a PDF/UA (Universal Accessibility) conformant document, you must configure your PDFDocument with specific options and follow certain content practices:

    1. Document Configuration:
      • Set pdfVersion to '1.5' or higher.
      • Set subset to 'PDF/UA' (to identify as PDF/UA-1).
      • Set tagged to true.
      • Provide a Title in the info option and set displayTitle: true.
      • Specify the natural language in document options.
    2. Content Practices:
      • Add logical structure for all significant content.
      • Include accessibility information (alternative text, actual text, etc.) in the logical structure or marked Span content.
      • Include all spaces that separate words/sentences (e.g., use doc.text('Hello ') instead of doc.text('Hello')).
      • Mark all non-structure content as artifacts.
      • Write objects in the natural reading order.
      • Avoid conveying information solely through visuals (color, contrast, position).
      • Avoid flickering or flashing content.
  10. Set predefined page sizes in PDFKit

    master

    You can use standard paper sizes by passing the size name as a string to the size property within the options object. This can be done during the initialization of a PDFDocument or when adding a new page via addPage().

    Supported predefined sizes include:

    • A-series: A0 through A10
    • B-series: B0 through B10
    • C-series: C0 through C10
    • RA-series: RA0 through RA4
    • SRA-series: SRA0 through SRA4
    • US/Canada Standards: EXECUTIVE, LEGAL, LETTER, TABLOID
    • Other: 4A0, 2A0, FOLIO
    // Passing size to the constructor
    const doc = new PDFDocument({size: 'A7'});
    
    // Passing size to the addPage function
    doc.addPage({size: 'A7'});