🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
路径:ireport365.wa/js/enduser/designer/vs-common.js 技术栈: html2canvas jspdf.js ``` function prictPage(){ var shareContent = document.getElementById('gridster'); var width = shareContent.offsetWidth; var height = shareContent.offsetHeight; var canvas = document.createElement("canvas"); var content = canvas.getContext("2d"); var scale = 2; var rect = shareContent.getBoundingClientRect();//获取元素相对于视察的偏移量 canvas.width = width * scale; canvas.height = height * scale; content.scale(scale, scale); content.translate(-rect.left,-rect.top);//设置context位置,值为相对于视窗的偏移量负值,让图片复位 var opts = { dpi: window.devicePixelRatio*scale, scale: scale, canvas: canvas, logging: true, width: width, height: height, // Whether to allow cross-origin images to taint the canvas allowTaint:true, // Whether to test each image if it taints the canvas before drawing them taintTest:false, // 如果没有开启html2canvas的useCORS配置项,html2canvas会正常执行且不会报错,但是不会输出对应的CDN图片 // (已测试同时包含CDN的图片和本地图片的资源的页面,但是只有本地图片能够被正常渲染出来) useCORS: true, onrendered: function(canvas) { var context = canvas.getContext('2d'); // 【重要】关闭抗锯齿 context.mozImageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; context.msImageSmoothingEnabled = false; context.imageSmoothingEnabled = false; //document.body.appendChild(canvas); 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 = ''; var img = new Image(); img.setAttribute('crossOrigin', 'anonymous'); img.onload = function () { pageData = canvas.toDataURL('image/PNG', 1.0); document.getElementById('canvasImg').src = pageData; context.drawImage(document.getElementById('canvasImg'), 0, 0); mkPdf(pageData); }; img.src = '/images/empty-page.png'; function mkPdf(pageData){ var pdf = new jsPDF('p', 'pt', 'a4'); //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) //当内容未超过pdf一页显示的范围,无需分页 if (leftHeight < pageHeight) { pdf.addImage(pageData, 'PNG', 0, 0, imgWidth, imgHeight ); } else { while(leftHeight > 0) { pdf.addImage(pageData, 'PNG', 0, position, imgWidth, imgHeight); leftHeight -= pageHeight; position -= 841.89; //避免添加空白页 if(leftHeight > 0) { pdf.addPage(); } } } var timestamp =Date.parse(new Date()); var dowfile = timestamp+'.pdf'; // pdf.save('content.pdf'); pdf.save(dowfile); } } }; html2canvas(shareContent, opts); } ```