前端页面生成pdf方案
前端pdf导出方案
·
前端页面生成pdf方案
使用jsPDF的html方法生成
直接将html节点传入jsPDF生成pdf,效果一般
const pdf = new jsPDF('p', 'pt', 'a4');
const target: HTMLElement | null = document.querySelector("#content");
if (target) {
pdf.html(target, {
callback: () => {
pdf.save('报表.pdf')
}
});
}
使用jsPDF api手动生成
清晰度高,适合一些简单pdf生成,pdf内容类似canvas一样绘制,复杂页面的pdf生成需要花费大量时间
pdf.ellipse(40, 20, 10, 5);
pdf.setFillColor(0,0,255);
pdf.ellipse(80, 20, 10, 5, 'F');
pdf.setLineWidth(1);
pdf.setDrawColor(0);
pdf.setFillColor(255,0,0);
pdf.circle(120, 20, 5, 'FD');
pdf.save('报表.pdf');
html2canvas + jsPDF
清晰度中等,利用html2canvas 将dom页面转化为canvas,然后加入到jsPDF 中进行pdf的生成,适合一些常规的报表页面,可视化页面的pdf生成
const pdf = new jsPDF('p', 'pt', 'a4');
const target: HTMLElement | null = document.querySelector("#content");
if (target) {
html2canvas(target).then(canvas => {
document.body.appendChild(canvas);
const contentWidth = canvas.width
const contentHeight = canvas.height
const pageData = canvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight);
pdf.save('报表.pdf');
});
}
利用Puppeteer生成pdf
清晰度高,可配置性强,该方案利用Puppeteer运行一个Chrome无头浏览器进行pdf的生成,需要运行node服务,如果导出要求高或者产品经常需要进行pdf导出时可以使用该方案,具体的实现流程为:
- 服务器运行一个nodejs服务启动一个Puppeteer服务
- 前端提供需要导出的页面的url,该页面可以使用用户看到的页面或者针对导出页面单独实现一个pdf版本的页面(最优)
- 前端访问pdf生成的服务,将页面url传给node服务
- node服务利用Puppeteer访问前端传入的页面url,然后使用无头浏览器在页面加载后将页面保存为pdf,并向前端提供该文件的下载路径
更多推荐
已为社区贡献1条内容
所有评论(0)