Vue如何将页面导出成PDF文件
本文实例为大家分享了Vue将页面导出成PDF文件的具体代码,供大家参考,具体内容如下
我在前端岗位上要实现个可视化图表页的PDF文件导出,在这里给大家分享下使用jsPDF和html2canvas包将Vue页面导出成PDF的方法。
1.下载npm包
npminstallhtml2canvas npminstalljspdf
2.创建插件.js文件
Vue-cli项目的话是在./utils文件夹下,我在这里使用的nuxt框架,所以是在./plugins文件夹下。
importhtml2Canvasfrom'html2canvas';
importJsPDFfrom'jspdf';
exportdefault{
install(Vue,options){
Vue.prototype.getPdf=function(){
vartitle=this.pdfTitle;//导出的pdf文件名
html2Canvas(document.querySelector(this.pdfSelector),{//导出的html元素
allowTaint:true
}).then(function(canvas){
letcontentWidth=canvas.width;
letcontentHeight=canvas.height;
letpageHeight=contentWidth/592.28*841.89;
letleftHeight=contentHeight;
letposition=0;
letimgWidth=595.28;
letimgHeight=592.28/contentWidth*contentHeight;
letpageData=canvas.toDataURL('image/jpeg',1.0);
letPDF=newJsPDF('','pt','a4');
if(leftHeight0){
PDF.addImage(pageData,'JPEG',0,position,imgWidth,imgHeight);
leftHeight-=pageHeight;
position-=841.89;
if(leftHeight>0){
PDF.addPage();
}
}
}
PDF.save(title+'.pdf');
})
}
}
}
上面的插件代码可以直接复制,然后在引用的Vue文件中填入自己的参数就可以了。
3.修改引用页面
导出按钮调用getPdf方法,data填入参数。
保存为PDF