Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

pdfkit

foliojs2mMIT0.16.0TypeScript support: definitely-typed

A PDF generation library for Node.js

pdf, pdf writer, pdf generator, graphics, document, vector

readme

PDFKit

A JavaScript PDF generation library for Node and the browser.

Description

PDFKit is a PDF document generation library for Node and the browser that makes creating complex, multi-page, printable documents easy. The API embraces chainability, and includes both low level functions as well as abstractions for higher level functionality. The PDFKit API is designed to be simple, so generating complex documents is often as simple as a few function calls.

Check out some of the documentation and examples to see for yourself! You can also read the guide as a self-generated PDF with example output displayed inline. If you'd like to see how it was generated, check out the README in the docs folder.

You can also try out an interactive in-browser demo of PDFKit here.

Installation

Installation uses the npm package manager. Just type the following command after installing npm.

npm install pdfkit

Features

  • Vector graphics
    • HTML5 canvas-like API
    • Path operations
    • SVG path parser for easy path creation
    • Transformations
    • Linear and radial gradients
  • Text
    • Line wrapping (with soft hyphen recognition)
    • Text alignments
    • Bulleted lists
  • Font embedding
    • Supports TrueType (.ttf), OpenType (.otf), WOFF, WOFF2, TrueType Collections (.ttc), and Datafork TrueType (.dfont) fonts
    • Font subsetting
    • See fontkit for more details on advanced glyph layout support.
  • Image embedding
    • Supports JPEG and PNG files (including indexed PNGs, and PNGs with transparency)
  • Annotations
    • Links
    • Notes
    • Highlights
    • Underlines
    • etc.
  • AcroForms
  • Outlines
  • PDF security
    • Encryption
    • Access privileges (printing, copying, modifying, annotating, form filling, content accessibility, document assembly)
  • Accessibility support (marked content, logical structure, Tagged PDF, PDF/UA)

Coming soon!

  • Patterns fills
  • Higher level APIs for creating tables and laying out content
  • More performance optimizations
  • Even more awesomeness, perhaps written by you! Please fork this repository and send me pull requests.

Example

const PDFDocument = require('pdfkit');
const fs = require('fs');

// Create a document
const doc = new PDFDocument();

// Pipe its output somewhere, like to a file or HTTP response
// See below for browser usage
doc.pipe(fs.createWriteStream('output.pdf'));

// Embed a font, set the font size, and render some text
doc
  .font('fonts/PalatinoBold.ttf')
  .fontSize(25)
  .text('Some text with an embedded font!', 100, 100);

// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('path/to/image.png', {
  fit: [250, 300],
  align: 'center',
  valign: 'center'
});

// Add another page
doc
  .addPage()
  .fontSize(25)
  .text('Here is some vector graphics...', 100, 100);

// Draw a triangle
doc
  .save()
  .moveTo(100, 150)
  .lineTo(100, 250)
  .lineTo(200, 250)
  .fill('#FF3300');

// Apply some transforms and render an SVG path with the 'even-odd' fill rule
doc
  .scale(0.6)
  .translate(470, -380)
  .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
  .fill('red', 'even-odd')
  .restore();

// Add some text with annotations
doc
  .addPage()
  .fillColor('blue')
  .text('Here is a link!', 100, 100)
  .underline(100, 100, 160, 27, { color: '#0000FF' })
  .link(100, 100, 160, 27, 'http://google.com/');

// Finalize PDF file
doc.end();

The PDF output from this example (with a few additions) shows the power of PDFKit — producing complex documents with a very small amount of code. For more, see the demo folder and the PDFKit programming guide.

Browser Usage

There are three ways to use PDFKit in the browser:

In addition to PDFKit, you'll need somewhere to stream the output to. HTML5 has a Blob object which can be used to store binary data, and get URLs to this data in order to display PDF output inside an iframe, or upload to a server, etc. In order to get a Blob from the output of PDFKit, you can use the blob-stream module.

The following example uses Browserify or webpack to load PDFKit and blob-stream. See here and here for examples of prebuilt version usage.

// require dependencies
const PDFDocument = require('pdfkit');
const blobStream = require('blob-stream');

// create a document the same way as above
const doc = new PDFDocument();

// pipe the document to a blob
const stream = doc.pipe(blobStream());

// add your content to the document here, as usual

// get a blob when you are done
doc.end();
stream.on('finish', function() {
  // get a blob you can do whatever you like with
  const blob = stream.toBlob('application/pdf');

  // or get a blob URL for display in the browser
  const url = stream.toBlobURL('application/pdf');
  iframe.src = url;
});

You can see an interactive in-browser demo of PDFKit here.

Note that in order to Browserify a project using PDFKit, you need to install the brfs module with npm, which is used to load built-in font data into the package. It is listed as a devDependency in PDFKit's package.json, so it isn't installed by default for Node users. If you forget to install it, Browserify will print an error message.

Documentation

For complete API documentation and more examples, see the PDFKit website.

License

PDFKit is available under the MIT license.

changelog

pdfkit changelog

[v0.16.0] - 2024-12-29

  • Update fontkit to 2.0
  • Update linebreak to 1.1
  • Add support for spot colors
  • Add support to scale text horizontally
  • Add an option to keep the indentation after a new line starts and allow to indent a whole paragraph/text element
  • Add Name property for set custom icon for note()
  • Fix sets tab order to "Structure" when a document is tagged
  • Fix font cache collision for fonts with missing postscript name or bad TTF metadata or identical metadata for different fonts
  • Fix for embedding fonts into PDF (font name must not contain spaces)
  • Fix measuring text when OpenType features are passed in to .text()

[v0.15.2] - 2024-12-15

  • Fix index not counting when rendering ordered lists (#1517)
  • Fix PDF/A3 compliance of attachments
  • Fix CIDSet generation only for PDF/A1 subset
  • Fix missing acroform font dictionary
  • Fix modify time comparison check equality embedded files

[v0.15.1] - 2024-10-30

  • Fix browserify transform sRGB_IEC61966_2_1.icc file
  • Fix time comparison check equality embedded files

[v0.15.0] - 2024-03-23

  • Add subset for PDF/UA
  • Fix for line breaks in list items (#1486)
  • Fix for soft hyphen not being replaced by visible hyphen if necessary (#457)
  • Optimize output files by ignoring identity transforms
  • Fix for Acroforms - setting an option to false will still apply the flag (#1495)
  • Fix for text extraction in PDFium-based viewers due to invalid ToUnicodeMap (#1498)
  • Remove deprecated write method
  • Drop support for Node.js < 18 and for browsers released before 2020

[v0.14.0] - 2023-11-09

  • Add support for PDF/A-1b, PDF/A-1a, PDF/A-2b, PDF/A-2a, PDF/A-3b, PDF/A-3a
  • Update crypto-js to v4.2.0 (properly fix security issue)

  • Add support for EXIF orientation on JPEG images (#626 and #1353)

[v0.13.0] - 2021-10-24

  • Add tiling pattern support

[v0.12.3] - 2021-08-01

  • Remove examples from published package

[v0.12.2] - 2021-08-01

  • Fix for PDF accessibility check. (#1265)
  • Allow applying 'underline' and 'strike' text styling together on a text
  • Allow to specify the AcroForm text fontSize
  • Update crypto-js to v4.0 (properly fix security issue)

[v0.12.1] - 2021-04-10

  • Update crypto-js to v3.3 (fix security issue)
  • Update fontkit to 1.8.1

[v0.12.0] - 2021-04-04

  • Add support for Embedded Files and File Attachment Annotations
  • Accessibility support
  • Replace integration tests by visual regression tests
  • Fix access permissions in PDF version 1.7ext3
  • Fix Buffer() is deprecation warning
  • Add forms.md to generate documentation files
  • Fix "@" in FontName

[v0.11.0] - 2019-12-03

  • Fix infinite loop when an individual character is bigger than the width of the text.
  • Fix infinite loop when text is positioned after page right margin
  • Allow links in continued text to be stopped by setting link to null
  • Add support to interlaced PNG files
  • Do not emit _interopDefault helper in commonjs build
  • Fix gradient with multiple stops (#1045)
  • Set link annotation flag to print by default
  • Add support for AcroForms
  • Drop support for (uncommon) cid less fonts on standalone build (reduces bundle size)

[v0.10.0] - 2019-06-06

  • Fix links to pages within the document
  • Add support for named destinations
  • Throw errors when dash(...) is passed invalid lengths
  • Remove PDFDocument#output method
  • Add standalone build (js/pdfkit.standalone.js)

[v0.9.1] - 2019-04-30

  • Fix setting printing permission
  • Fix corruption of string objects in browser
  • Add option to set default font
  • Remove call to fontkit.openSync
  • Add standalone virtual file system implementation
  • Add option (fontLayoutCache) to disable font layout cache

[v0.9.0] - 2019-01-28

  • Convert to code base from coffescript to ES6+
  • Fix loading grayscale / transparent PNG files
  • Reduce number of calls to async functions
  • Implement encryption / access control