jsPDF README

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

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:

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:

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:

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

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.

jsPDF (parallax/jsPDF)

Searching Database…

31.3K ·GitHub
这是什么?jsPDF 是一个 JavaScript 库,可以直接在客户端(浏览器中)生成 PDF 文档,因此无需服务器即可生成 PDF。
这是我要导入的库,还是独立应用?它是一个通过 npm 分发的 JavaScript 库,你可以将其导入自己的项目中。它提供 ES 模块、UMD 以及 Node 专用等多种构建版本。
我该如何把 jsPDF 添加到项目中?可以通过 npm 安装(或直接从 unpkg 加载),然后使用 import 'jspdf' 导入。大多数打包工具和 Node 会自动解析正确的构建文件。
要使用全部功能,我还需要安装其他包吗?核心的 PDF 生成功能没有额外要求,但 html() 方法需要可选的 html2canvas 包;如果你传入原始 HTML 字符串,还需要 dompurify。这些依赖会动态加载,因此 Webpack 可以对它们进行代码拆分。
它是否开箱即支持中文或西里尔字母等非 ASCII 文本?不支持。内置的 14 种 PDF 字体只覆盖 ASCII 字符,因此要处理中文等 UTF-8 文本,你必须使用随附的 fontconverter 工具转换并嵌入自定义的 .ttf 字体。
它只能在浏览器中使用,还是也能在 Node 中使用?两者都支持。它提供专用的 Node 构建版本,使用文件操作而非浏览器 API;同时还有面向浏览器的 ES 和 UMD 构建版本。
直接把用户生成的内容输入 jsPDF 安全吗?不安全。项目明确提醒你应先对任何用户输入进行清理(sanitize);在 Node 环境下,出于安全考虑,它默认限制读取本地文件。
compat 模式和 advanced API 模式有什么区别?compat 模式(默认)与原始 MrRio API 保持一致,以确保完整的插件兼容性;advanced 模式则启用了 yWorks 分支的功能,如变换矩阵、FormObjects 和 patterns,而 compat 模式不具备这些功能。
为什么 jsPDF 现在由 yWorks 共同维护?yWorks 是一家专注于图表绘制的公司,它将自己的高级分支合并回了原始的 jsPDF 项目,在经典 API 之外还带来了 patterns 和变换矩阵等功能。
我能在 TypeScript 或 Angular/React 等框架中使用 jsPDF 吗?可以。jsPDF 附带 TypeScript 类型定义文件,并可与 Webpack、Angular、Vue CLI、Meteor 以及 React 配合使用(create-react-app 需通过 react-app-rewired 或 eject 进行配置),文档中还提供了关于将可选依赖外部化的说明。
jsPDF 能在 Internet Explorer 等旧版浏览器中运行吗?只能借助 polyfill。ES 构建版本会通过 core-js 自动导入它们,但对于旧版浏览器,你需要自行加载所需的 polyfill,或使用预打包的 polyfill 文件。
Creator
parallax
Size
141 MB
Stars
31.3K
Age
16y
Commits · 90 Days