js实现pdf打印
使用 window.print() 方法打印 PDF
通过浏览器原生打印功能实现 PDF 打印,适用于简单内容打印。
function printPDF() {
window.print();
}
调用 printPDF() 会触发浏览器打印对话框,用户可选择打印为 PDF。
使用 jsPDF 库生成 PDF
jsPDF 是一个流行的 JavaScript 库,用于生成 PDF 文件。
// 安装 jsPDF
// npm install jspdf
import { jsPDF } from "jspdf";
function generatePDF() {
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("document.pdf");
}
使用 html2pdf.js 转换 HTML 为 PDF
html2pdf.js 可将 HTML 元素转换为 PDF 文件。

// 安装 html2pdf.js
// npm install html2pdf.js
import html2pdf from "html2pdf.js";
function convertToPDF() {
const element = document.getElementById("content-to-print");
html2pdf().from(element).save();
}
使用 PDFKit 生成复杂 PDF
PDFKit 适用于需要复杂布局的 PDF 生成。
// 安装 PDFKit
// npm install pdfkit
const PDFDocument = require("pdfkit");
const fs = require("fs");
function createPDF() {
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream("output.pdf"));
doc.fontSize(25).text("Some text", 100, 100);
doc.end();
}
使用浏览器打印样式优化
通过 CSS 媒体查询优化打印输出效果。

@media print {
body * {
visibility: hidden;
}
.print-content, .print-content * {
visibility: visible;
}
.print-content {
position: absolute;
left: 0;
top: 0;
}
}
处理打印分页问题
使用 CSS 控制分页行为,避免内容被截断。
.page-break {
page-break-after: always;
}
.no-break {
page-break-inside: avoid;
}
使用 PDF.js 显示和打印 PDF
Mozilla 的 PDF.js 可用于在网页中显示和打印 PDF 文件。
// 引入 PDF.js 库
pdfjsLib.getDocument("document.pdf").promise.then(function(pdf) {
pdf.getPage(1).then(function(page) {
const viewport = page.getViewport({ scale: 1.0 });
const canvas = document.getElementById("pdf-canvas");
const context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({
canvasContext: context,
viewport: viewport
});
});
});
使用服务器端生成 PDF
对于复杂需求,可考虑使用服务器端解决方案如:
- Node.js 的 Puppeteer
- PHP 的 TCPDF
- Python 的 ReportLab
这些方法通常能提供更稳定的打印质量和更丰富的功能。






