官网:GitHub - parallax/jsPDF: Client-side JavaScript PDF generation for everyone.
主要用途: 在js中生成pdf文件
安装
- 使用npm(推荐):
npm i jspdf
- 使用yarn:
yarn add jspdf
- 从cdn加载使用版本2.5.2的包:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.2/jspdf.umd.min.js"></script>
- 从cdn加载使用最新版本的包
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
使用
基础示例
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");
- 如果想更换纸张大小、水平方向或者单位,可以:
// 横向导出, 尺寸为2*4英寸
const doc = new jsPDF({
orientation: "landscape",
unit: "in",
format: [4, 2]
});
doc.text("Hello world!", 1, 1);
doc.save("two-by-four.pdf");
在node中使用
const { jsPDF } = require("jspdf");
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
其它模块使用
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");
参数说明
属性 | 类型 | 说明 | 默认值 |
---|---|---|---|
orientation | string | 首页的方向:可选值为:“portrait” 纵向、"landscape“横向。或简写为"p"或"l” | portrait |
unit | string | 指定坐标时要使用的测量单位(基本单位)。可选值为:pt(点),mm(毫米),cm(厘米),in(英寸),px(像素),pc,em或ex。 注意:为了获得“px”正确缩放比例,需要通过设置options.hotfixes=[“px_scaling”]来启用“px_scaling”修补程序 | mm |
format | string/Array | 首页的格式,可选值为: + a0-a10 + b0-b10 + c0-c10 + d1 + letter + government-letter + legal + junior-legal + ledger + tabloid + credit-card 如果想使用自定义格式,写成数组就好,e.g. [595.8, 841.9] | a4 |
putOnlyUsedFonts | boolean | 仅将已使用字体放入PDF中 | false |
compress | boolean | 压缩生成的pdf文件 | false |
precision | number | 元素位置的精确度 | 16 |
hotfixes | Array | 用于启用修补程序 |