引用JS <script src="js/jquery-2.1.4.js"></script> <script src="js/html2canvas.js"></script> <script src="js/jspdf.js"></script> Html <button type="button" id="down_btn">下载PDF</button> <div style="width: 824px;height:1192px;text-align: center;margin: 0 auto;background:red;" id="box"></div>
JS $('#sbt').click(function(){ downpdf('box'); }) function dowpdf(id){ const cntElem=document.getElementById(id); var shareContent=cntElem; var width=shareContent.offsetWidth; var height=shareContent.offsetHeight; var canvas=document.createElement('canvas'); var scale=3; canvas.width=width*scale; canvas.height=height*scale; canvas.getContext('2d').scale(scale,scale); var opts={ scale:scale, canvas, width:width, height:height, useCORS:true, }; html2canvas(shareContent,opts).then(canvas=>{ var context=canvas.getContext('2d'); context.mozImageSmoothingEnabled=false; context.webkitImageSmoothingEnabled=false; context.msImageSmoothingEnabled=false; context.imageSmoothingEnabled=false; var dataUrl=canvas.toDataURL("image/jpeg"); var newImg=document.createElement('img'); newImg.src=dataUrl; newImg.setAttribute('id','newImg'); newImg.style.width=canvas.width/scale+'px'; newImg.style.height=canvas.height/scale+'px'; // document.getElementById('box2').appendChild(newImg); 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 url= canvas.toDataURL("image/jpeg"); var image = new Image(); image.src = canvas.toDataURL("image/jpeg"); var doc = new jsPDF('','pt','a4'); // PDF分页 image.onload = function() { if (leftHeight < pageHeight) { doc.addImage(image.src,'jpeg',0,0,imgWidth,imgHeight ); } else { while(leftHeight > 0) { doc.addImage(image.src, 'jpeg', 0, position, imgWidth, imgHeight) leftHeight -= pageHeight; position -= 841.89; if(leftHeight > 0) { doc.addPage(); } } } doc.save("名称.pdf"); } ; }); }