// 页面导出为pdf格式以及分页隔断处理 //title表示为下载的标题,html表示document.querySelector('#myPrintHtml') import html2Canvas from 'html2canvas'; import JsPDF from 'jspdf'; let noTableHeight = 0; //table外的元素高度 export function pageToPDF(title, html, lableList, type) { return new Promise(function (resolve, reject) { let width = html.clientWidth, //获取dom 宽度 height = html.clientHeight, //获取dom 高度 canvas = document.createElement('canvas'), //创建一个canvas节点 scale = 1; //定义任意放大倍数 支持小数 canvas.width = width * scale; //定义canvas 宽度 * 缩放 canvas.height = height * scale; //定义canvas高度 *缩放 canvas.style.width = html.clientWidth * scale + 'px'; canvas.style.height = html.clientHeight * scale + 'px'; canvas.getContext('2d').scale(scale, scale); //获取context,设置scale let opts = { scale: scale, // 添加的scale 参数 canvas: canvas, //自定义 canvas logging: false, //日志开关,便于查看html2canvas的内部执行流程 width: width, //dom 原始宽度 height: height, useCORS: true, // 【重要】开启跨域配置 }; html2Canvas(html, opts).then(() => { var contentWidth = canvas.width; var contentHeight = canvas.height; //一页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 = (592.28 / contentWidth) * contentHeight; var pageData = canvas.toDataURL('image/jpeg', 1.0); var 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(); } } } // 保存文件 if (canvas) { PDF.save(title + '.pdf'); resolve(1); } else { reject('下载失败'); } }); }); } // pdf截断需要一个空白位置来补充 function getFooterElement(remainingHeight, fillingHeight = 0) { const newNode = document.createElement('div'); newNode.style.background = '#ffffff'; newNode.style.width = 'calc(100% + 8px)'; newNode.style.marginLeft = '-4px'; newNode.style.marginBottom = '0px'; newNode.classList.add('divRemove'); newNode.style.height = remainingHeight + fillingHeight + 'px'; return newNode; } function isSplit(nodes, index, pageHeight) { // 判断是不是tr 如果不是高度存起来 // 表格里的内容要特殊处理 // tr.offsetTop 是tr到table表格的高度 // 所以计算高速时候要把表格外的高度加起来 // 生成的pdf没有表格了这里可以不做处理 直接计算就行 if (nodes[index].localName !== 'tr') { //判断元素是不是tr noTableHeight += nodes[index].clientHeight; } if (nodes[index].localName !== 'tr') { return ( nodes[index].offsetTop + nodes[index].offsetHeight < pageHeight && nodes[index + 1] && nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight ); } else { return ( nodes[index].offsetTop + nodes[index].offsetHeight + noTableHeight < pageHeight && nodes[index + 1] && nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight + noTableHeight > pageHeight ); } }