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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| PDF() { let title = this.titleName; let dom = document.querySelector('#printPage') let width = dom.offsetWidth let height = dom.offsetHeight let canvas = document.createElement("canvas") let scale = 2 canvas.width = width * scale; //定义canvas 宽度 * 缩放 canvas.height = height * scale ; //定义canvas高度 *缩放 canvas.style.width = width * scale + "px"; canvas.style.height = height * scale + "px"; canvas.getContext("2d").scale(scale, scale); //获取context,设置scale var opts = { //allowTaint: true, //允许污染 taintTest: false, //在渲染前测试图片 background: "#fff", scale: 1, canvas: canvas, width: width, //dom 原始宽度 height: height, useCORS: true, // 【重要】开启跨域配置 //logging: true, //日志开关,便于查看html2canvas的内部执行流程 } html2Canvas(dom, opts).then((canvas)=> { var context = canvas.getContext('2d'); // 【重要】关闭抗锯齿 context.mozImageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; context.msImageSmoothingEnabled = false; context.imageSmoothingEnabled = false; let contentWidth = canvas.width let contentHeight = canvas.height //未生成pdf的html页面高度 let leftHeight = contentHeight //页面偏移 let position = 0 //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 if(this.direction == '纵'){ //一页pdf显示html页面生成的canvas高度; var pageHeight = contentWidth / 592.28 * 841.89 var imgWidth = 595.28 var imgHeight = 592.28 / contentWidth * contentHeight var pathAway = 'p' }else{ var pageHeight = contentWidth / 841.89 * 592.28; // 横向 var imgWidth = 841.89; // 横向 var imgHeight = 841.89/contentWidth * contentHeight; // 横向 var pathAway = 'l' } let pageData = canvas.toDataURL('image/jpeg', 1.0) //p:纵向,l为横向 a4:纸张大小,默认是a4; let PDF = new JsPDF(pathAway, 'pt', 'a4') //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) //当内容未超过pdf一页显示的范围,无需分页 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 position -= 592.28 // 横向 //避免添加空白页 if (leftHeight > 0) { PDF.addPage() } } } PDF.save(title + '.pdf') }) }
|