vue3 如何将页面生成 pdf 导出

您所在的位置:网站首页 网页如何导出pdf格式文件内容 vue3 如何将页面生成 pdf 导出

vue3 如何将页面生成 pdf 导出

2024-03-04 21:55| 来源: 网络整理| 查看: 265

原文链接:vue3 如何将页面生成 pdf 导出

64b3b7cd1f0c8.png

前言

最近工作中有需要将一些前端页面(如报表页面等)导出为pdf的需求,博主采用的是html2Canvas + jspdf。

效果图

步骤

1.引入两个依赖

npm i html2canvas npm i jspdf

点击 jsPDF GitHub、jsPDF 文档 查看关于jsPDF更多信息。

2.在utils文件夹下新建html2pdf.ts文件

import html2canvas from 'html2canvas'; import jsPDF from 'jspdf' export const htmlToPDF = async (htmlId: string, title: string = "报表", bgColor = "#fff") => { let pdfDom: HTMLElement | null = document.getElementById(htmlId) as HTMLElement pdfDom.style.padding = '0 10px !important' const A4Width = 595.28; const A4Height = 841.89; let canvas = await html2canvas(pdfDom, { scale: 2, useCORS: true, backgroundColor: bgColor, }); let pageHeight = (canvas.width / A4Width) * A4Height; let leftHeight = canvas.height; let position = 0; let imgWidth = A4Width; let imgHeight = (A4Width / canvas.width) * canvas.height; /* 根据自身业务需求 是否在此处键入下方水印代码 */ let pageData = canvas.toDataURL("image/jpeg", 1.0); let PDF = new jsPDF("p", 'pt', 'a4'); if (leftHeight < pageHeight) { PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight); } else { while (leftHeight > 0) { PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight); leftHeight -= pageHeight; position -= A4Height; if (leftHeight > 0) PDF.addPage(); } } PDF.save(title + ".pdf"); }

如果你想给pdf加上水印,则添加下面这段代码:

const ctx: any = canvas.getContext('2d'); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.rotate((20 * Math.PI) / 180); ctx.font = '20px Microsoft Yahei'; ctx.fillStyle = 'rgba(184, 184, 184, 0.8)'; for (let i = canvas.width * -1; i < canvas.width; i += 240) { for (let j = canvas.height * -1; j < canvas.height; j += 200) { // 填充文字,x 间距, y 间距 ctx.fillText('水印名', i, j); } }

3.在目标页面引入方法即可

import { htmlToPDF } from '@/utils/html2pdf' test test test test test test test 导出

效果如下:

参考 jsPDF Vue3 导出 pdf 方案 如何用html2canvas +jsPDF更简单实现pdf防截断导出(含算法优化)? - 掘金 (juejin.cn) vue页面生成pdf且避免分页截断处理 实现前端页面局部转 pdf 及 打印 加分页防止内容截断 纯前端生成 PDF 之 jspdf 使用及注意事项 jsPDF + html2canvas A4 分页截断 完美解决方案(含代码 + 案例)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3