VUE HTML转PDF下载
npm install --save html2canvas@1.0.0-rc.4
npm install jspdf
封装htmlToPdf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | //导出页面为PDF格式 import html2canvas from 'html2canvas' ; import JsPDF from 'jspdf' ; const htmlToPdf = { getPdf(title,content){ html2canvas(content,{ allowTaint: true , scale: 3 , // 清晰度 }).then(canvas=>{ var context = canvas.getContext( '2d' ); // 设置字体样式 context.font = '24px SimSun, Songti SC' ; context.fillText( '24px的宋体呈现' , 20 , 50 ); //内容的宽度 let contentwidth =canvas.width; //内容的高度 let contentHeight = canvas.height; //一页pdf显示html页面生成的canvas高度,a4纸的尺寸[595.28,841.89]; let pageHeight =contentwidth/ 592.28 * 841.89 ; //未生成pdf的html页面高度 let leftHeight = contentHeight //页面偏移 let position = 0 ; //a4纸的尺寸[595.28,841.89], html页面生成的canvas在pdf中图片的宽高 let imgwidth= 595.28 ; let imgHeight = 592.28 / contentwidth * contentHeight; //canvas转图片数据 let pageData = canvas.toDataURL( 'img/jpeg' , 1.0 ); //新建JsPDF对象 let PDF = new JsPDF( '' , '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 -= 841.89 ; if (leftHeight > 0 ){ PDF.addPage() } } } console.log(pageData) //(获取压缩的PDF文件图片数据) //保存文件 PDF.save(title + '.pdf' ) }) } }; export default htmlToPdf; |
前端调用:
1 2 3 4 5 6 7 8 9 10 11 | <div id = "pdfDom" > <JxtRcyjJobTemplate :JxtRcyjJobData= "JxtRcyjJobData" ></JxtRcyjJobTemplate> </div> <script type= "es6" > import htmlToPdf from '@/utils/htmlToPdf.js' ; methods: { downloadPdf(){ htmlToPdf.getPdf( "呈报表" ,document.getElementById( "pdfDom" )); } } </script> |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库