结合 html2canvas 和 jspdf 插件处理
/* eslint-disable */ //不使用JQuery版的 import html2canvas from 'html2canvas' import JsPDF from 'jspdf' /** * @param ele 要生成 pdf 的DOM元素(容器) * @param padfName PDF文件生成后的文件名字 * */ export function toPdf(ele) { return new Promise((resolve,reject)=>{ html2canvas(ele, { dpi: 300, // allowTaint: true, //允许 canvas 污染, allowTaint参数要去掉,否则是无法通过toDataURL导出canvas数据的 useCORS: true, scale: 2, logging: false, async: true, }).then((canvas) => { var contentWidth = canvas.width var contentHeight = canvas.height console.log(contentWidth, contentHeight) //一页pdf显示html页面生成的canvas高度; var pageHeight = (contentWidth / 592.28) * 841.89 //未生成pdf的html页面高度 var leftHeight = contentHeight //页面偏移 var position = 0 //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 var imgWidth = 595.28 var imgHeight = (595.28 / contentWidth) * contentHeight var pageData = canvas.toDataURL('image/jpeg', 1.0) var pdf = new JsPDF('', 'pt', 'a4') //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) //当内容未超过pdf一页显示的范围,无需分页 if (leftHeight < pageHeight) { //在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示; pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight) // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight); } else { // 分页 while (leftHeight > 0) { pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight) leftHeight -= pageHeight position -= 841.89 //避免添加空白页 if (leftHeight > 0) { pdf.addPage() } } } resolve(pdf) }).catch(()=>{ reject() }) }) } export async function downloadPDF(ele, pdfName){ const pdf = await toPdf(ele) pdf.save(pdfName) }
标签:canvas,vue,ele,html,pageData,var,pdf From: https://www.cnblogs.com/wjs0509/p/17798711.html