js实现将网页转换成pdf
使用html2canvas和jsPDF库实现网页转PDF
html2canvas可以将网页内容渲染为canvas,jsPDF再将canvas转为PDF文件。这种方法适合需要精确控制页面样式的场景。
// 安装依赖
npm install html2canvas jspdf
// 代码示例
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
const exportToPDF = async (elementId, filename) => {
const element = document.getElementById(elementId);
const canvas = await html2canvas(element);
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgProps = pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save(filename);
};
使用浏览器原生打印功能
通过CSS媒体查询优化打印样式,利用浏览器自带的"另存为PDF"功能。

@media print {
@page {
size: A4;
margin: 0;
}
body * {
visibility: hidden;
}
.print-area, .print-area * {
visibility: visible;
}
.print-area {
position: absolute;
left: 0;
top: 0;
}
}
window.print();
使用PDFKit生成结构化PDF
适合需要生成复杂PDF文档的场景,支持文本、图像、矢量图形等。
const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
doc.fontSize(25).text('网页标题', 100, 80);
doc.fontSize(14).text('网页内容...', 100, 100);
// 添加图像
doc.image('screenshot.png', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
doc.end();
使用Puppeteer进行服务器端转换
通过Headless Chrome实现高质量PDF转换,适合复杂网页或需要批量处理的场景。

const puppeteer = require('puppeteer');
async function generatePDF(url, outputPath) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url, {waitUntil: 'networkidle0'});
await page.pdf({
path: outputPath,
format: 'A4',
printBackground: true,
margin: {
top: '20mm',
bottom: '20mm',
left: '20mm',
right: '20mm'
}
});
await browser.close();
}
使用wkhtmltopdf工具
基于WebKit引擎的命令行工具,支持从HTML直接生成PDF。
wkhtmltopdf input.html output.pdf
在Node.js中调用:
const { exec } = require('child_process');
exec('wkhtmltopdf http://example.com output.pdf', (error) => {
if (error) console.error(error);
});
每种方法各有优缺点,html2canvas+jsPDF适合客户端简单转换,Puppeteer适合高质量服务端转换,PDFKit适合编程生成PDF,原生打印适合用户手动操作。选择方案时应考虑浏览器兼容性、性能需求和功能复杂度等因素。





