jspdf、pdf-lib 和 pdfmake 都是 JavaScript 中处理 PDF 文件的主流库,但它们的侧重点完全不同。jspdf 擅长从头绘制 PDF 内容,采用命令式 API;pdf-lib 专注于修改现有 PDF 文件(如填写表单、合并),同时也支持创建;pdfmake 则使用声明式的 JSON 结构来定义文档,特别适合生成报表和发票。
在 JavaScript 生态中处理 PDF 文件时,jspdf、pdf-lib 和 pdfmake 是最常见的三个选择。它们都能生成 PDF,但设计哲学和适用场景差异巨大。本文将从架构角度对比它们的核心机制,帮助你在实际工程中做出正确选择。
jspdf 采用命令式绘制模型。
// jspdf: 命令式绘制
import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.text("Hello World", 10, 10);
doc.save("document.pdf");
pdf-lib 采用对象修改模型。
// 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 采用声明式文档定义。
// pdfmake: 声明式定义
import pdfMake from "pdfmake/build/pdfmake";
const dd = { content: ["Hello World"] };
pdfMake.createPdf(dd).download("document.pdf");
处理复杂布局时,三个库的表现截然不同。
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-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();
中文支持是前端 PDF 生成的常见痛点。
jspdf 需要手动加载字体文件。
// 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)。
// pdfmake: 使用 vfs 字体
// 需预先引入 vfs_fonts.js 包含常用字体
pdfMake.fonts = { Roboto: { /*...*/ } };
const dd = { content: ["文本"], defaultStyle: { font: "Roboto" } };
如果你需要编辑已有的 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) 生成新文档
尽管差异明显,它们也有一些共同点。
// 浏览器:触发下载
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
// 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 }] };
// 三者均可直接在浏览器运行,无需服务器
// 数据不出客户端,安全性较高
| 特性 | jspdf | pdf-lib | pdfmake |
|---|---|---|---|
| 核心用途 | 从头创建简单 PDF | 修改现有 PDF / 创建 | 生成复杂报表 |
| 布局方式 | 命令式坐标 | 命令式坐标 | 声明式 JSON |
| 表格支持 | 需插件 (autoTable) | 手动绘制 | 内置支持 |
| 修改现有文件 | ❌ 不支持 | ✅ 支持 | ❌ 不支持 |
| 字体配置 | Base64 嵌入 | 手动嵌入 | VFS 预加载 |
| 学习曲线 | 低 | 中 | 低 |
jspdf 像是一把通用螺丝刀 🔧——适合快速解决简单问题,社区资源多,但处理复杂任务时效率低。适合内部工具、简单凭证生成。
pdf-lib 像是一把手术刀 🪓——精准控制 PDF 结构,适合需要编辑、合并或填写表单的场景。适合合同系统、文档处理流水线。
pdfmake 像是一个排版引擎 📄——专注于文档内容结构,适合生成发票、报表等固定格式文档。适合数据报告、导出功能。
最终建议:不要试图用一个库解决所有问题。如果需要修改现有文件,必须选 pdf-lib。如果需要生成复杂表格报表,pdfmake 效率最高。如果只是简单导出文本或图片,jspdf 足够轻量。根据具体业务场景组合使用,往往能获得最佳效果。
选择 jspdf 如果你需要快速从头生成简单的 PDF 文件,且不需要复杂的表格布局。它适合简单的文本和图片拼接场景,社区插件丰富,但处理复杂排版时代码会变得繁琐。
选择 pdf-lib 如果你的核心需求是修改现有的 PDF 模板,例如填写表单、合并文件或添加水印。它在处理现有文档结构方面表现最好,也支持从头创建,但布局需要手动计算坐标。
选择 pdfmake 如果你需要生成结构复杂的报表、发票或包含表格的文档。它的声明式配置让布局管理更简单,内置了对表格和列的良好支持,但自定义绘图能力较弱。
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.
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:
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.
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");
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
require(["jspdf"], ({ jsPDF }) => {
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
});
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
We strongly advise you to sanitize user input before passing it to jsPDF!
For reporting security vulnerabilities, please see SECURITY.md.
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.
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.
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
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.
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");
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:
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.
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:
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
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.