diff --git a/src/utils/htmlToPdf.js b/src/utils/htmlToPdf.js new file mode 100644 index 00000000..2e997a3c --- /dev/null +++ b/src/utils/htmlToPdf.js @@ -0,0 +1,99 @@ +/** + path: src/utils/htmlToPdf.js + name: 导出页面为PDF格式 +**/ +import html2Canvas from 'html2canvas' +import JsPDF from 'jspdf' + + function convertImageToCanvas(image) { + // 创建canvas DOM元素,并设置其宽高和图片一样 + let canvas = document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + canvas.getContext("2d").drawImage(image, 0, 0); + // 我们在实际的开发中,需要将抓换后的base64图片编码传输到后台图片服务器,由server直接存储或者生成一张图片; + // 所以会用到 toDataURL + //console.log(canvas.toDataURL('image/jpeg')) + return canvas; + } + +const htmlToPdf = { +// pdfExport() { +// var mainRight = document.getElementById('mainRight'); +// html2canvas(mainRight, { +// allowTaint: true, +// scale: 2, // 提升画面质量,但是会增加文件大小 +// }).then(function(canvas) { + +// var contentWidth = canvas.width; +// var contentHeight = canvas.height; + +// var pageData = canvas.toDataURL('image/jpeg', 0.4); + +// var pdfWidth = (contentWidth + 10) / 2 * 0.75; +// var pdfHeight = (contentHeight + 200) / 2 * 0.75; // 500为底部留白 + +// var imgWidth = pdfWidth; +// var imgHeight = (contentHeight / 2 * 0.75); //内容图片这里不需要留白的距离 + +// var pdf = new jsPDF('', 'pt', [pdfWidth, pdfHeight]); +// pdf.addImage(pageData, 'jpeg', 0, 0, imgWidth, imgHeight); +// pdf.save('report_pdf_' + new Date().getTime() + '.pdf'); +// }); } + getPdf(title) { + let domId='idPdfDom'; + let dom=document.getElementById(domId); + //所有的图片都加上 + let imgList=dom.querySelectorAll('img'); + //console.log('imgList',imgList) + + imgList.forEach(function(item){ + item.crossOrigin= 'anonymous'; + item.src =item.src+'?v='+Math.random() + document.body.appendChild(convertImageToCanvas(item)) + }) + //let dom=document.querySelector('#'+domId); + + //console.log(dom.length,'dom.length'); + setTimeout(() => { + html2Canvas(dom, {allowTaint: true,}).then(canvas=>{ + //内容的宽度 + 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 = 841.89 / contentWidth * contentHeight; + // let imgHeight = 592.28 / contentWidth * contentHeight; + //canvas转图片数据 + let pageData = canvas.toDataURL('image/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() + } + } + } + //保存文件 + PDF.save('我的笔记.pdf') + + }) + },500); + } +}; + +export default htmlToPdf;