js实现pdf
使用 jsPDF 生成 PDF
安装 jsPDF 库:
npm install jspdf
基本示例代码:
import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("example.pdf");
使用 PDFKit 生成 PDF
安装 PDFKit:
npm install pdfkit
基本示例代码:
const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
doc.fontSize(25).text('Some text here', 100, 100);
doc.end();
使用 html2pdf.js 转换 HTML 为 PDF
安装 html2pdf.js:
npm install html2pdf.js
基本示例代码:
import html2pdf from 'html2pdf.js';
const element = document.getElementById('content-to-export');
html2pdf().from(element).save();
使用 Puppeteer 生成 PDF
安装 Puppeteer:
npm install puppeteer
基本示例代码:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com', {waitUntil: 'networkidle2'});
await page.pdf({path: 'example.pdf', format: 'A4'});
await browser.close();
})();
添加样式和格式
jsPDF 添加字体和样式:
doc.setFont("helvetica", "bold");
doc.setFontSize(16);
doc.setTextColor(255, 0, 0);
PDFKit 添加图像:
doc.image('path/to/image.png', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
处理中文显示问题
jsPDF 使用自定义字体:
import { jsPDF } from "jspdf";
import simhei from './simhei-normal';
const doc = new jsPDF();
doc.addFileToVFS("simhei-normal.ttf", simhei);
doc.addFont("simhei-normal.ttf", "simhei", "normal");
doc.setFont("simhei");
doc.text("中文内容", 10, 10);
生成表格
jsPDF 自动表格插件:
import 'jspdf-autotable';
doc.autoTable({
head: [['Name', 'Email', 'Country']],
body: [
['John', 'john@example.com', 'USA'],
['李华', 'lihua@example.com', 'China']
]
});
分页控制
PDFKit 分页示例:
doc.addPage();
doc.text('This is page 2', 100, 100);
jsPDF 分页示例:
doc.addPage();
doc.text('This is page 2', 10, 10);
保存选项
设置 PDF 元数据:
doc.setProperties({
title: 'Sample PDF',
subject: 'Demo PDF generation',
author: 'Your Name',
keywords: 'javascript, pdf',
creator: 'Your App'
});
浏览器兼容性提示
现代浏览器支持这些库生成 PDF,但需要注意:
- 某些功能可能需要 polyfill
- 移动端浏览器可能有不同表现
- 大型文档可能需要性能优化
这些方法各有优缺点,选择取决于具体需求:

- 简单文本:jsPDF
- 复杂布局:PDFKit
- HTML转换:html2pdf.js
- 网页截图:Puppeteer






