jspdf vs pdf-lib vs pdfmake
JavaScript 环境下的 PDF 生成与修改方案
jspdfpdf-libpdfmake类似的npm包:

JavaScript 环境下的 PDF 生成与修改方案

jspdf、pdf-lib 和 pdfmake 都是 JavaScript 中处理 PDF 文件的主流库,但它们的侧重点完全不同。jspdf 擅长从头绘制 PDF 内容,采用命令式 API;pdf-lib 专注于修改现有 PDF 文件(如填写表单、合并),同时也支持创建;pdfmake 则使用声明式的 JSON 结构来定义文档,特别适合生成报表和发票。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
jspdf031,31130.2 MB1167 个月前MIT
pdf-lib08,662-3185 年前MIT
pdfmake012,35012 MB23910 小时前MIT

jsPDF vs pdf-lib vs pdfmake:架构选型与实战对比

在 JavaScript 生态中处理 PDF 文件时,jspdf、pdf-lib 和 pdfmake 是最常见的三个选择。它们都能生成 PDF,但设计哲学和适用场景差异巨大。本文将从架构角度对比它们的核心机制,帮助你在实际工程中做出正确选择。

🎨 核心设计理念:绘制 vs 修改 vs 声明

jspdf 采用命令式绘制模型。

  • 你像操作画布一样,指定坐标放置文本或线条。
  • 适合从头创建文档,但布局逻辑分散在代码中。
// jspdf: 命令式绘制
import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.text("Hello World", 10, 10);
doc.save("document.pdf");

pdf-lib 采用对象修改模型。

  • 你操作的是 PDF 文档对象结构,可以创建也可以修改现有文件。
  • 适合处理模板、合并文件或填写表单。
// pdf-lib: 对象操作
import { PDFDocument } from "pdf-lib";
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
page.drawText("Hello World", { x: 50, y: 50 });
const pdfBytes = await pdfDoc.save();

pdfmake 采用声明式文档定义。

  • 你描述文档长什么样(JSON 结构),库负责渲染。
  • 适合报表、发票等结构固定的文档。
// pdfmake: 声明式定义
import pdfMake from "pdfmake/build/pdfmake";
const dd = { content: ["Hello World"] };
pdfMake.createPdf(dd).download("document.pdf");

📐 布局与表格:手动坐标 vs 自动流式

处理复杂布局时,三个库的表现截然不同。

jspdf 需要手动计算坐标。

  • 没有内置表格组件,通常需要配合插件(如 autoTable)。
  • 分页逻辑需要自己管理,容易出错。
// jspdf: 手动定位
const doc = new jsPDF();
doc.text("Item", 10, 10);
doc.text("Price", 50, 10);
doc.text("Apple", 10, 20); // 需手动计算 Y 轴

pdf-lib 同样需要手动计算坐标。

  • 它更关注底层 PDF 对象,不提供高级布局工具。
  • 适合精确控制元素位置,不适合长文档流。
// pdf-lib: 手动定位
const page = pdfDoc.addPage();
page.drawText("Item", { x: 10, y: 500 });
page.drawText("Price", { x: 50, y: 500 });
page.drawText("Apple", { x: 10, y: 480 }); // 需手动计算 Y 轴

pdfmake 内置流式布局引擎。

  • 天然支持表格、列布局和多级嵌套。
  • 自动处理分页,无需关心坐标。
// pdfmake: 自动布局
const dd = {
  content: [
    { table: { body: [["Item", "Price"], ["Apple", "10"]] }
  ]
};
pdfMake.createPdf(dd).download();

🔤 字体处理:嵌入 vs 虚拟文件系统

中文支持是前端 PDF 生成的常见痛点。

jspdf 需要手动加载字体文件。

  • 默认不支持中文,需将字体转为 Base64 嵌入。
  • 增加包体积,配置过程繁琐。
// jspdf: 加载自定义字体
doc.addFileToVFS("MyFont.ttf", base64FontString);
doc.addFont("MyFont.ttf", "MyFont", "normal");
doc.setFont("MyFont");

pdf-lib 支持嵌入标准字体或自定义字体。

  • 需要手动读取字体文件并嵌入。
  • 灵活性高,但代码量较大。
// pdf-lib: 嵌入字体
const fontBytes = await fetch("./font.ttf").then(res => res.arrayBuffer());
const customFont = await pdfDoc.embedFont(fontBytes);
page.drawText("你好", { x: 50, y: 50, font: customFont });

pdfmake 使用虚拟文件系统(vfs)。

  • 通常预打包常用字体,或动态加载 vfs_fonts.js。
  • 配置简单,但自定义字体需构建步骤。
// pdfmake: 使用 vfs 字体
// 需预先引入 vfs_fonts.js 包含常用字体
pdfMake.fonts = { Roboto: { /*...*/ } };
const dd = { content: ["文本"], defaultStyle: { font: "Roboto" } };

📝 修改现有 PDF:唯一的选择

如果你需要编辑已有的 PDF 文件,选项非常有限。

jspdf 不支持修改现有 PDF。

  • 只能创建新文件。
  • 无法填写表单或合并页面。
// jspdf: 无法加载现有文件进行修改
// 仅支持 new jsPDF() 创建新文档

pdf-lib 专为修改设计。

  • 可以加载现有字节,修改表单、添加页面或水印。
  • 是此类场景的首选方案。
// pdf-lib: 修改现有文件
const existingPdfBytes = await fetch("./template.pdf").then(res => res.arrayBuffer());
const pdfDoc = await PDFDocument.load(existingPdfBytes);
const form = pdfDoc.getForm();
form.getTextField("name").setText("Alice");

pdfmake 不支持修改现有 PDF。

  • 仅支持从头生成。
  • 适合生成新报告,不适合编辑模板。
// pdfmake: 无法加载现有文件进行修改
// 仅支持 createPdf(dd) 生成新文档

🌱 相似之处:共同的基础能力

尽管差异明显,它们也有一些共同点。

1. 🌐 浏览器与 Node.js 支持

  • 三者均支持在浏览器和 Node.js 环境中运行。
  • 注意文件保存方式不同(下载 vs 文件系统写入)。
// 浏览器:触发下载
doc.save("file.pdf"); // jspdf
pdfBytes => download(pdfBytes); // pdf-lib
pdfMake.createPdf(dd).download(); // pdfmake

// Node.js: 写入文件
fs.writeFileSync("file.pdf", doc.output()); // jspdf
fs.writeFileSync("file.pdf", pdfBytes); // pdf-lib
fs.writeFileSync("file.pdf", result); // pdfmake

2. 🖼️ 图片支持

  • 都支持嵌入图片,但 API 略有不同。
  • 都需要处理图片数据(Base64 或 ArrayBuffer)。
// jspdf
doc.addImgData(imgData, "JPEG", 10, 10, 100, 100);

// pdf-lib
const jpgBytes = await fetch("./img.jpg").then(res => res.arrayBuffer());
const jpgImage = await pdfDoc.embedJpg(jpgBytes);
page.drawImage(jpgImage, { x: 50, y: 50, width: 100, height: 100 });

// pdfmake
const dd = { content: [{ image: "data:image/jpeg;base64,...", width: 100 }] };

3. 🔒 纯前端处理

  • 都不需要后端服务参与生成过程。
  • 适合隐私敏感数据或离线场景。
// 三者均可直接在浏览器运行,无需服务器
// 数据不出客户端,安全性较高

📊 总结对比表

特性jspdfpdf-libpdfmake
核心用途从头创建简单 PDF修改现有 PDF / 创建生成复杂报表
布局方式命令式坐标命令式坐标声明式 JSON
表格支持需插件 (autoTable)手动绘制内置支持
修改现有文件❌ 不支持✅ 支持❌ 不支持
字体配置Base64 嵌入手动嵌入VFS 预加载
学习曲线低中低

💡 架构师建议

jspdf 像是一把通用螺丝刀 🔧——适合快速解决简单问题,社区资源多,但处理复杂任务时效率低。适合内部工具、简单凭证生成。

pdf-lib 像是一把手术刀 🪓——精准控制 PDF 结构,适合需要编辑、合并或填写表单的场景。适合合同系统、文档处理流水线。

pdfmake 像是一个排版引擎 📄——专注于文档内容结构,适合生成发票、报表等固定格式文档。适合数据报告、导出功能。

最终建议:不要试图用一个库解决所有问题。如果需要修改现有文件,必须选 pdf-lib。如果需要生成复杂表格报表,pdfmake 效率最高。如果只是简单导出文本或图片,jspdf 足够轻量。根据具体业务场景组合使用,往往能获得最佳效果。

如何选择: jspdf vs pdf-lib vs pdfmake

  • jspdf:

    选择 jspdf 如果你需要快速从头生成简单的 PDF 文件,且不需要复杂的表格布局。它适合简单的文本和图片拼接场景,社区插件丰富,但处理复杂排版时代码会变得繁琐。

  • pdf-lib:

    选择 pdf-lib 如果你的核心需求是修改现有的 PDF 模板,例如填写表单、合并文件或添加水印。它在处理现有文档结构方面表现最好,也支持从头创建,但布局需要手动计算坐标。

  • pdfmake:

    选择 pdfmake 如果你需要生成结构复杂的报表、发票或包含表格的文档。它的声明式配置让布局管理更简单,内置了对表格和列的良好支持,但自定义绘图能力较弱。

jspdf的README

jsPDF

Continous Integration Code Climate Test Coverage GitHub license Total alerts Language grade: JavaScript Gitpod ready-to-code

A library to generate PDFs in JavaScript.

You can catch me on twitter: @MrRio or head over to my company's website for consultancy.

jsPDF is now co-maintained by yWorks - the diagramming experts.

Live Demo | Documentation

Install

Recommended: get jsPDF from npm:

npm install jspdf --save
# or
yarn add jspdf

Or always get latest version via unpkg

<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>

The dist folder of this package contains different kinds of files:

  • jspdf.es.*.js: Modern ES2015 module format.
  • jspdf.node.*.js: For running in Node. Uses file operations for loading/saving files instead of browser APIs.
  • jspdf.umd.*.js: UMD module format. For AMD or script-tag loading.
  • polyfills*.js: Required polyfills for older browsers like Internet Explorer. The es variant simply imports all required polyfills from core-js, the umd variant is self-contained.

Usually it is not necessary to specify the exact file in the import statement. Build tools or Node automatically figure out the right file, so importing "jspdf" is enough.

Usage

Then you're ready to start making your document:

import { jsPDF } from "jspdf";

// Default export is a4 paper, portrait, using millimeters for units
const doc = new jsPDF();

doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");

If you want to change the paper size, orientation, or units, you can do:

// Landscape export, 2×4 inches
const doc = new jsPDF({
  orientation: "landscape",
  unit: "in",
  format: [4, 2]
});

doc.text("Hello world!", 1, 1);
doc.save("two-by-four.pdf");

Running in Node.js

const { jsPDF } = require("jspdf"); // will automatically load the node version

const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf"); // will save the file in the current working directory

Other Module Formats

AMD
require(["jspdf"], ({ jsPDF }) => {
  const doc = new jsPDF();
  doc.text("Hello world!", 10, 10);
  doc.save("a4.pdf");
});
Globals
const { jsPDF } = window.jspdf;

const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");

Security

We strongly advise you to sanitize user input before passing it to jsPDF!

For reporting security vulnerabilities, please see SECURITY.md.

Reading files from the local file system on node

When running under Node.js, jsPDF will restrict reading files from the local file system by default.

Strongly recommended: use Node's permission flags so the runtime enforces access:

node --permission --allow-fs-read=... ./scripts/generate.js

See Node's documentation for details. Note that you need to include all imported JavaScript files (including all dependencies) in the --allow-fs-read flag.

Fallback (not recommended): you can allow jsPDF to read specific files by setting jsPDF.allowFsRead in your script.

import { jsPDF } from "jspdf";

const doc = new jsPDF();
doc.allowFsRead = ["./fonts/*", "./images/logo.png"]; // allow everything under ./fonts and a single file

Warning: We strongly recommend the Node flags over jsPDF.allowFsRead, as the flags are enforced by the runtime and offer stronger security.

Optional dependencies

Some functions of jsPDF require optional dependencies. E.g. the html method, which depends on html2canvas and, when supplied with a string HTML document, dompurify. JsPDF loads them dynamically when required (using the respective module format, e.g. dynamic imports). Build tools like Webpack will automatically create separate chunks for each of the optional dependencies. If your application does not use any of the optional dependencies, you can prevent Webpack from generating the chunks by defining them as external dependencies:

// webpack.config.js
module.exports = {
  // ...
  externals: {
    // only define the dependencies you are NOT using as externals!
    canvg: "canvg",
    html2canvas: "html2canvas",
    dompurify: "dompurify"
  }
};

In Vue CLI projects, externals can be defined via the configureWebpack or chainWebpack properties of the vue.config.js file (needs to be created, first, in fresh projects).

In Angular projects, externals can be defined using custom webpack builders.

In React (create-react-app) projects, externals can be defined by either using react-app-rewired or ejecting.

TypeScript/Angular/Webpack/React/etc. Configuration:

jsPDF can be imported just like any other 3rd party library. This works with all major toolkits and frameworks. jsPDF also offers a typings file for TypeScript projects.

import { jsPDF } from "jspdf";

You can add jsPDF to your meteor-project as follows:

meteor add jspdf:core

Polyfills

jsPDF requires modern browser APIs in order to function. To use jsPDF in older browsers like Internet Explorer, polyfills are required. You can load all required polyfills as follows:

import "jspdf/dist/polyfills.es.js";

Alternatively, you can load the prebundled polyfill file. This is not recommended, since you might end up loading polyfills multiple times. Might still be nifty for small applications or quick POCs.

Use of Unicode Characters / UTF-8:

The 14 standard fonts in PDF are limited to the ASCII-codepage. If you want to use UTF-8 you have to integrate a custom font, which provides the needed glyphs. jsPDF supports .ttf-files. So if you want to have for example Chinese text in your pdf, your font has to have the necessary Chinese glyphs. So, check if your font supports the wanted glyphs or else it will show garbled characters instead of the right text.

To add the font to jsPDF use our fontconverter in /fontconverter/fontconverter.html. The fontconverter will create a js-file with the content of the provided ttf-file as base64 encoded string and additional code for jsPDF. You just have to add this generated js-File to your project. You are then ready to go to use setFont-method in your code and write your UTF-8 encoded text.

Alternatively you can just load the content of the *.ttf file as a binary string using fetch or XMLHttpRequest and add the font to the PDF file:

const doc = new jsPDF();

const myFont = ... // load the *.ttf font file as binary string

// add the font to jsPDF
doc.addFileToVFS("MyFont.ttf", myFont);
doc.addFont("MyFont.ttf", "MyFont", "normal");
doc.setFont("MyFont");

Advanced Functionality

Since the merge with the yWorks fork there are a lot of new features. However, some of them are API breaking, which is why there is an API-switch between two API modes:

  • In "compat" API mode, jsPDF has the same API as MrRio's original version, which means full compatibility with plugins. However, some advanced features like transformation matrices and patterns won't work. This is the default mode.
  • In "advanced" API mode, jsPDF has the API you're used from the yWorks-fork version. This means the availability of all advanced features like patterns, FormObjects, and transformation matrices.

You can switch between the two modes by calling

doc.advancedAPI(doc => {
  // your code
});
// or
doc.compatAPI(doc => {
  // your code
});

JsPDF will automatically switch back to the original API mode after the callback has run.

Support

Please check if your question is already handled at Stackoverflow https://stackoverflow.com/questions/tagged/jspdf. Feel free to ask a question there with the tag jspdf.

Feature requests, bug reports, etc. are very welcome as issues. Note that bug reports should follow these guidelines:

  • A bug should be reported as an mcve
  • Make sure code is properly indented and formatted (Use ``` around code blocks)
  • Provide a runnable example.
  • Try to make sure and show in your issue that the issue is actually related to jspdf and not your framework of choice.

Contributing

jsPDF cannot live without help from the community! If you think a feature is missing or you found a bug, please consider if you can spare one or two hours and prepare a pull request. If you're simply interested in this project and want to help, have a look at the open issues, especially those labeled with "bug".

You can find information about building and testing jsPDF in the contribution guide

Credits

  • Big thanks to Daniel Dotsenko from Willow Systems Corporation for making huge contributions to the codebase.
  • Thanks to Ajaxian.com for featuring us back in 2009. (Internet Archive Wayback Machine reference)
  • Our special thanks to GH Lee (sphilee) for programming the ttf-file-support and providing a large and long sought after feature
  • Everyone else that's contributed patches or bug reports. You rock.

License (MIT)

Copyright (c) 2010-2025 James Hall, https://github.com/MrRio/jsPDF (c) 2015-2025 yWorks GmbH, https://www.yworks.com/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.