vue3页面导出为PDF文件
尝试了很多方法,都没有找到完美的解决方法
目前网上有个思路,就是将页面先转存为图片,然后将图片另存为PDF文件
记录一下完整过程
一、安装必备包
安装两个第三方插件
npm i html2canvas
npm i jspdf
html2canvas,作用显而易见,将html转为canvas画布
jspdf是js程序中操作pdf的包
二、封装导出PDF的方法
在vue3项目中,我一般放在src/utils目录下
新建htmlToPDF.js文件,代码如下:
// 页面导出为pdf格式
import html2Canvas from "html2canvas";
import jsPDF from "jspdf";const htmlToPdf = {getPdf(title, id) {html2Canvas(document.querySelector(id), {allowTaint: false,taintTest: false,logging: false,useCORS: true,dpi: window.devicePixelRatio * 4, //将分辨率提高到特定的DPI 提高四倍scale: 4, //按比例增加分辨率}).then((canvas) => {var pdf = new jsPDF("p", "mm", "a4"); //A4纸,纵向var ctx = canvas.getContext("2d"),a4w = 190,a4h = 272, //A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277imgHeight = Math.floor((a4h * canvas.width) / a4w), //按A4显示比例换算一页图像的像素高度renderedHeight = 0;while (renderedHeight < canvas.height) {var page = document.createElement("canvas");page.width = canvas.width;page.height = Math.min(imgHeight, canvas.height - renderedHeight); //可能内容不足一页//用getImageData剪裁指定区域,并画到前面创建的canvas对象中page.getContext("2d").putImageData(ctx.getImageData(0,renderedHeight,canvas.width,Math.min(imgHeight, canvas.height - renderedHeight)),0,0);pdf.addImage(page.toDataURL("image/jpeg", 1.0),"JPEG",10,10,a4w,Math.min(a4h, (a4w * page.height) / page.width)); //添加图像到页面,保留10mm边距renderedHeight += imgHeight;if (renderedHeight < canvas.height) {pdf.addPage(); //如果后面还有内容,添加一个空页}// delete page;}pdf.save(title + ".pdf");});},
};export default htmlToPdf;
三、页面调用
直接上代码
<template><div style="position: relative;"><div class="report" id="report">需要存为PDF的内容</div> <div class="output" @click="printReport">导出此报告</div></div>
</template><script>
import htmlToPdf from "@/utils/htmlToPDF";
const printReport = () => {htmlToPdf.getPdf('周期报告',"#report");
}
</script><style lang="scss" scoped>
.report {position: relative;padding: 20px 500px;display: flex;justify-content: space-between;flex-direction: column;height: 100%;width: 100%;background-color: #eee;
}.output {top: 20px;left: 500px;width: 100px;height: 40px;background-color: #2177b8;position: absolute;border-radius: 10px;color: #fff;display: flex;align-items: center;justify-content: center;cursor: pointer;
}
</style>
调用函数时,需要传入导出PDF文件的文件名和要导出内容的dom的id
亲测,可以成功导出,但适配的是A4纸,在分页的地方比较难看,如下: