pdfkit README

The project's README from github.com/foliojs/pdfkit. As one markdown file: README.md.

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

Use npm or yarn package manager. Just type the following command:

# with npm
npm install pdfkit

# with yarn
yarn add pdfkit

Features

Coming soon!

Example

Both const PDFDocument = require('pdfkit') and import PDFDocument from 'pdfkit' remain supported for backward compatibility. New code should prefer the named PDFDocument export, which will make a future migration to an ESM-only package more straightforward.

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 to collect its output. Browsers provide a Blob object for storing binary data and creating URLs that can be displayed in an iframe, downloaded or uploaded.

Experimental output helpers

PDFKit provides experimental toBlob and toBytes helpers from pdfkit/output. These functions may change before they are stabilized. Call the selected helper before ending the document so it receives the complete output.

Use toBlob when displaying, downloading or uploading the PDF in a browser:

import { PDFDocument, registerStdFonts } from 'pdfkit';
import Helvetica from 'pdfkit/standard-fonts/Helvetica';
import HelveticaBold from 'pdfkit/standard-fonts/HelveticaBold';
import { toBlob } from 'pdfkit/output';

registerStdFonts(Helvetica, HelveticaBold);
const doc = new PDFDocument();
const output = toBlob(doc);

// Add your content to the document here, as usual.

doc.end();
const blob = await output;
const url = URL.createObjectURL(blob);
iframe.src = url;

// Revoke the URL when the iframe no longer needs the PDF.
// URL.revokeObjectURL(url);

Use toBytes instead when a binary API, worker or parser needs one contiguous Uint8Array:

import { toBytes } from 'pdfkit/output';

const output = toBytes(doc);
doc.end();
const bytes = await output;

The stable, dependency-free alternative is to collect the document's Uint8Array chunks using its events and construct the Blob directly:

const chunks = [];

doc.on('data', chunk => chunks.push(chunk));
doc.on('end', () => {
  const blob = new Blob(chunks, { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);
  iframe.src = url;
});

// Add your content to the document here, as usual.
doc.end();

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

The browser build has no access to the file system. You can register a Uint8Array under a path before passing that exact path to registerFont, image or file:

import { PDFDocument, registerFile } from 'pdfkit';

const response = await fetch('/fonts/Roboto-Regular.ttf');
const fontData = new Uint8Array(await response.arrayBuffer());

registerFile('fonts/Roboto-Regular.ttf', fontData);

const doc = new PDFDocument();

// register an alias for the font path
doc.registerFont('Roboto', 'fonts/Roboto-Regular.ttf');
// or use the path directly
doc.font('fonts/Roboto-Regular.ttf');

// Optionally unregister the path when it is no longer needed.
registerFile('fonts/Roboto-Regular.ttf', undefined);

Registration is global to the loaded PDFKit module. Registering the same path again replaces its data. In Node, registered data takes precedence over a file at the same path; unregistering it restores normal file system lookup. Both APIs are available as named exports from the CommonJS entry point:

const { PDFDocument, registerFile } = require('pdfkit');

registerFile('files/example.txt', new Uint8Array([1, 2, 3]), {
  birthtime: new Date('2020-01-02T03:04:05Z'),
  ctime: new Date('2021-02-03T04:05:06Z'),
});
registerFile('files/example.txt', undefined);

registerFile accepts only a Uint8Array or undefined. You can still pass a Uint8Array or ArrayBuffer directly to registerFont, image and file, and you can pass a data URL directly to image and file. An unregistered file path throws in the browser. The optional birthtime and ctime values must be valid Date objects; either omitted value defaults to the time of registration.

Documentation

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

License

PDFKit is available under the MIT license.

pdfkit (foliojs/pdfkit)

Searching Database…

10.7K ·GitHub
这是什么?PDFKit 是一个 JavaScript 库,可以在 Node.js 和浏览器中生成结构复杂、多页、可打印的 PDF 文档。
它是框架还是库?它是一个库,你可以在自己的代码中通过 require 或 import 引入。它提供可链式调用的 API,既有底层绘图函数,也有用于文本、图片、表格和表单的高级辅助功能。
怎么把它加到项目里?用 npm 或 yarn 安装,然后 require PDFDocument(或使用新的具名导入),再把输出通过 pipe 写入文件或流。
PDFKit 底层依赖什么?它内置了处理字体、图片和加密的辅助包:fontkit 负责字体处理,png-js 负责 PNG,此外还有 fflate、linebreak,以及用于加密的 @noble 系列加密库。
浏览器版和 Node 版的功能完全一样吗?不一样。浏览器版无法访问文件系统,因此字体和图片必须以 Uint8Array 数据的形式注册(或以 ArrayBuffer、data URL 的形式传入),不能通过文件路径引用;如果引用了未注册的路径,就会抛出错误。
为什么不用无头浏览器来生成 PDF?PDFKit 通过类似画布(canvas)的矢量和文本 API 以编程方式生成 PDF,而不是渲染 HTML。因此它更轻量,并且能精确控制版面、字体,以及表单、加密等 PDF 专有功能。
在浏览器中具体怎么使用 PDFKit?你可以用 Browserify 或 webpack 打包,也可以使用发布版本中预构建好的 pdfkit.standalone.js 文件。输出内容可以通过 Blob 收集,或使用实验性的 toBlob、toBytes 辅助方法。
可以嵌入哪些图片和字体格式?图片支持 JPEG 和 PNG(包括索引色 PNG 和透明 PNG)。字体支持 TrueType、OpenType、WOFF、WOFF2、TrueType Collection 和 Datafork TrueType,并会自动进行字体子集化处理。
能给生成的 PDF 加密或做访问限制吗?可以。PDFKit 支持 PDF 加密,并可设置访问权限,例如打印、复制、修改、添加注释、填写表单以及内容组装等权限。
PDFKit 支持无障碍或带标签的 PDF 吗?支持。它通过标记内容、逻辑结构、Tagged PDF 以及 PDF/UA 合规性提供无障碍功能。
Creator
foliojs
Size
58.9 MB
Stars
10.7K
Age
15y
Commits · 90 Days