jspdf vs pdfmake vs html2pdf.js vs html-pdf
Web 应用中从 HTML 和程序化内容生成 PDF 的客户端方案对比
jspdfpdfmakehtml2pdf.jshtml-pdf类似的npm包:
Web 应用中从 HTML 和程序化内容生成 PDF 的客户端方案对比

html-pdfhtml2pdf.jsjsPDFpdfmake 是用于在 Web 应用中生成 PDF 文档的 JavaScript 库,但它们在架构、能力和运行环境上差异显著。html-pdf 是一个仅限 Node.js 的包,使用 PhantomJS 将 HTML 转换为 PDF,目前已官方弃用html2pdf.js 在浏览器中运行,利用 html2canvas 和 jsPDF 将 DOM 元素捕获为 PDF。jsPDF 是一个底层 PDF 创建库,支持浏览器和 Node.js 环境,允许通过代码绘制文本、图像和图形,但不直接渲染 HTML。pdfmake 则采用声明式的文档定义方式生成 PDF,对布局、表格和样式有强大支持,同样兼容浏览器和 Node.js。

npm下载趋势
3 年
GitHub Stars 排名
统计详情
npm包名称
下载量
Stars
大小
Issues
发布时间
License
jspdf4,509,69430,88930.1 MB1081 个月前MIT
pdfmake1,132,70512,18013.6 MB3087 个月前MIT
html2pdf.js566,1784,7207.17 MB4873 个月前MIT
html-pdf123,0843,633-4695 年前MIT

PDF 生成库对比:html-pdf、html2pdf.js、jsPDF 与 pdfmake

在 Web 应用中生成 PDF 是常见需求 —— 无论是生成发票、报表还是可打印摘要。但选择哪个库,取决于你的输入源(HTML 还是结构化数据)、运行环境(浏览器还是 Node.js)以及对输出质量的要求。下面我们从工程实践角度深入分析。

⚠️ html-pdf:已弃用,仅限 Node.js

html-pdf 曾是一个流行的 Node.js 包,通过 PhantomJS 渲染 HTML 生成 PDF。但该包现已在 npm 和 GitHub 上被官方标记为弃用,作者明确建议迁移到 Puppeteer 等现代库 。PhantomJS 本身早已停止维护,这意味着无法支持现代 CSS(如 Flexbox、Grid),且存在未修复的安全漏洞 。

只能在 Node.js 中运行,无法用于浏览器环境。因此,新项目绝不应使用 html-pdf

// html-pdf:已弃用的用法(仅 Node.js)
const pdf = require('html-pdf');
const html = '<h1>Hello World</h1>';
pdf.create(html).toFile('./output.pdf', (err, res) => {
  if (err) return console.log(err);
  console.log(res.filename);
});

💡 迁移建议:Node.js 环境下使用 Puppeteer 或 Playwright 进行现代、可靠的 HTML 到 PDF 转换。

🖼️ html2pdf.js:浏览器端的 HTML 快照

html2pdf.js 完全在浏览器中运行,旨在将任意 DOM 元素转换为 PDF。其内部结合了两个库 :

  • html2canvas:将 HTML 元素渲染为 <canvas>(将文本和布局光栅化为图像)
  • jsPDF:将 canvas 转换为 PDF

这意味着输出是基于像素的图像,而非矢量文本。放大后可能模糊,文件体积也较大。但它的优势是使用极其简单,能快速捕获 UI 的视觉状态。

// html2pdf.js:将 DOM 元素转为 PDF
import html2pdf from 'html2pdf.js';

const element = document.getElementById('invoice');
html2pdf().from(element).save();

你可以通过配置设置边距、文件名或页面尺寸:

html2pdf()
  .set({ margin: 10, filename: 'report.pdf', image: { type: 'jpeg', quality: 0.95 } })
  .from(element)
  .save();

✅ 适用场景:需要“导出为 PDF”按钮,且希望结果与浏览器中显示一致。
❌ 不适用场景:需要可搜索文本、小文件体积或精确排版。

✍️ jsPDF:底层 PDF 构建器

jsPDF 提供通过代码绘制 PDF 的底层 API。它不理解 HTML 或 CSS —— 你需要使用坐标手动定位文本、图像和图形。这赋予你完全控制权,但也意味着布局逻辑需自行实现。

它支持浏览器和 Node.js(在 Node 中需配合 canvas 或图像插件),并生成矢量文本、可搜索的 PDF

// jsPDF:通过代码创建 PDF
import { jsPDF } from 'jspdf';

const doc = new jsPDF();
doc.setFontSize(22);
doc.text('Hello world!', 20, 20);
doc.save('output.pdf');

插入图片需要预先加载:

const img = new Image();
img.src = '/logo.png';
img.onload = () => {
  doc.addImage(img, 'PNG', 15, 40, 180, 160);
  doc.save('with-image.pdf');
};

对于表格或分页,需借助 jspdf-autotable 等插件。否则,所有布局都需手动计算。

✅ 适用场景:生成简单、数据驱动的文档(如快递单、证书),且能通过代码定义布局。
❌ 不适用场景:需要复现复杂 HTML 布局或自动分页。

📐 pdfmake:声明式文档定义

pdfmake 使用类似 JSON 的文档定义来描述 PDF 结构。你将内容定义为对象数组(文本、表格、图像、列),pdfmake 会自动处理布局、分页、页眉页脚和样式 。

它支持矢量文本带行合并的表格分页页眉页脚自定义字体。输出文件干净、可搜索且体积小 。

// pdfmake:声明式 PDF
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

const docDefinition = {
  content: [
    { text: '发票', style: 'header' },
    { text: '客户:张三' },
    {
      table: {
        body: [
          ['商品', '价格'],
          ['小部件', '¥10'],
          ['小配件', '¥20']
        ]
      }
    }
  ],
  styles: {
    header: { fontSize: 18, bold: true }
  }
};

pdfMake.createPdf(docDefinition).download('invoice.pdf');

它还支持动态页眉页脚:

const docDefinition = {
  header: () => '我的公司',
  footer: (currentPage, pageCount) => `第 ${currentPage} 页,共 ${pageCount} 页`,
  content: [/* ... */]
};

✅ 适用场景:需要生成专业、可打印的文档,包含表格、一致样式和自动分页。
❌ 不适用场景:输入源是无法转换为结构化数据的原始 HTML。

🔁 输入源:HTML vs. 结构化数据

这是核心架构差异:

输入类型渲染方式
html-pdfHTML (Node.js)PhantomJS (已弃用)
html2pdf.jsDOM 元素光栅化为图像
jsPDF代码(图元)矢量绘制
pdfmakeJSON 定义矢量布局引擎

如果你的内容是浏览器中的 HTML,且需要视觉快照 → 选 html2pdf.js
如果你有结构化数据(如 API 返回),需要生成高质量 PDF → 选 pdfmake
如果你需要像素级控制坐标 → 选 jsPDF

🌐 运行环境

  • 仅浏览器html2pdf.js(设计如此)
  • 浏览器 + Node.jsjsPDFpdfmake(Node.js 中需少量配置)
  • 仅 Node.js(已弃用)html-pdf

注意:jsPDFpdfmake 虽支持 Node.js,但它们不渲染 HTML —— 它们从代码或定义生成 PDF。

📄 质量与文件体积

  • html2pdf.js 生成较大文件,因为内容以图像形式嵌入。
  • jsPDFpdfmake 生成小体积、文本可搜索的 PDF
  • html-pdf 的输出质量依赖 PhantomJS,缺乏现代渲染能力。

🧩 总结:如何选择

场景推荐库
将屏幕上的 DOM 转为 PDF(如“导出为 PDF”按钮)html2pdf.js
从 JSON 数据生成发票、合同或报表pdfmake
创建简单、代码定义的 PDF(如标签、证书)jsPDF
Node.js 中 HTML 转 PDF(新项目)不要用这些 —— 用 Puppeteer
Node.js 中 HTML 转 PDF(旧项目)html-pdf 迁移

🚫 关于 html-pdf 的最后提醒

html-pdf 不应在任何新项目中使用。它对 PhantomJS 的依赖使其过时、不安全且与现代 Web 标准不兼容。如需服务端 HTML 转 PDF,请使用基于 Chromium 的方案如 Puppeteer。对于客户端需求,根据输入源在 html2pdf.js(视觉快照)和 pdfmake/jsPDF(结构化高质量文档)之间选择。

如何选择: jspdf vs pdfmake vs html2pdf.js vs html-pdf
  • jspdf:

    当需要对 PDF 内容进行精细控制,并通过代码而非 HTML 生成文档时,选择 jsPDF 。它适用于生成标签、证书或简单表单等场景,但缺乏原生 HTML/CSS 支持,复杂布局(如表格)需依赖插件或手动实现。

  • pdfmake:

    当需要基于结构化数据生成包含复杂布局(如表格、页眉页脚、多栏)的专业级 PDF 时,选择 pdfmake 。它使用声明式 API,自动处理分页和样式,输出为矢量文本,文件小且可搜索,适合发票、合同等业务文档。

  • html2pdf.js:

    当需要将现有 HTML 内容(如报表、发票或仪表盘)直接在浏览器中转为 PDF 且希望保留视觉样式时,选择 html2pdf.js 。它适合“一键导出”场景,但需注意其内部使用 html2canvas 进行光栅化,可能导致文本不可搜索、文件体积大或复杂 CSS 渲染不准确。

  • html-pdf:

    不要在新项目中使用 html-pdf —— 该包已在 npm 和 GitHub 上被官方标记为弃用,且依赖已停止维护的 PhantomJS 。它仅适用于 Node.js,无法用于客户端 PDF 生成。现有项目应迁移到 Puppeteer 等现代替代方案。

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

Alternatively, load it from a CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/3.0.4/jspdf.umd.min.js"></script>

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");

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.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/3.0.4/polyfills.umd.js"></script>

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.