js实现pdf报表
使用 jsPDF 生成 PDF 报表
jsPDF 是一个流行的 JavaScript 库,用于在客户端生成 PDF 文件。它支持文本、表格、图片等内容的添加。
安装 jsPDF:
npm install jspdf
基本用法示例:
import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("report.pdf");
添加表格:
const doc = new jsPDF();
doc.autoTable({
head: [['ID', 'Name', 'Email']],
body: [
[1, 'John', 'john@example.com'],
[2, 'Jane', 'jane@example.com']
]
});
doc.save('table.pdf');
使用 PDFKit 生成 PDF 报表
PDFKit 是另一个强大的 JavaScript 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('Report Title', 100, 80);
doc.fontSize(12).text('This is a sample PDF report.', 100, 100);
doc.end();
添加表格功能需要额外实现:
function addTable(doc, data) {
const startY = 150;
const rowHeight = 20;
const colWidth = 100;
data.forEach((row, rowIndex) => {
row.forEach((cell, colIndex) => {
doc.text(cell, 100 + colIndex * colWidth, startY + rowIndex * rowHeight);
});
});
}
使用 html2pdf 从 HTML 生成 PDF
如果需要基于现有 HTML 内容生成 PDF,可以使用 html2pdf.js。
安装 html2pdf.js:
npm install html2pdf.js
基本用法:

import html2pdf from 'html2pdf.js';
const element = document.getElementById('report-container');
const opt = {
margin: 10,
filename: 'report.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save();
使用 Puppeteer 生成 PDF
对于需要服务器端生成的场景,Puppeteer 是一个强大的选择。
安装 Puppeteer:
npm install puppeteer
基本用法:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent('<h1>Report</h1><p>This is a PDF report</p>');
await page.pdf({ path: 'report.pdf', format: 'A4' });
await browser.close();
})();
性能优化建议
对于大量数据的报表,考虑分页处理:
const doc = new jsPDF();
let y = 20;
data.forEach((item, index) => {
if (y > 280) { // 接近页面底部
doc.addPage();
y = 20;
}
doc.text(`${item.id}: ${item.name}`, 10, y);
y += 10;
});
使用 Web Worker 处理大型 PDF 生成任务,避免阻塞主线程:
// main.js
const worker = new Worker('pdf-worker.js');
worker.postMessage({ data: largeDataSet });
// pdf-worker.js
self.onmessage = function(e) {
const doc = new jsPDF();
// 生成PDF逻辑
const pdfOutput = doc.output('blob');
self.postMessage({ pdf: pdfOutput });
};
以上方法涵盖了从简单到复杂的 PDF 报表生成需求,可根据具体场景选择合适的技术方案。






