【js】实现html整个页面生成单张pdf

首先引入html2canvas和jspdf
html2canvas: http://html2canvas.hertzen.com/
jspdf: https://parall.ax/products/jspdf

创建方法downloadAsPdf

downloadAsPdf(){
   // 特别重要:当页面超过一页,出现滚动条,滚动的部分生成的图片为空白
   window.pageYoffset = 0
   document.documentElement.scrollTop = 0
   document.body.scrollTop = 0
   let url = html2canvas(document.querySelector('#app'),{dpi: '600',scale: '2',}).then(function (canvas) {
       let pageWidth = canvas.width;
       let pageHeight = canvas.height;
       var pageData = canvas.toDataURL('image/jpeg', 1.0);
       // Create a new PDF with the same dimensions as the image.
       const pdf = new jsPDF({
           orientation: pageHeight > pageWidth ? "portrait": "landscape",
           unit: "px",
           format: [pageHeight, pageWidth]
       });
       // Add the image to the PDF with dimensions equal to the internal dimensions of the page.
       pdf.addImage(pageData, 0, 0, pageWidth,pageHeight);
       // Save the PDF with the filename specified here:
       pdf.save("report.pdf");
       }
   )
},

你可能感兴趣的:(前端实用工具集,javascript,html,前端)