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

本文介绍了如何结合html2canvas和jspdf库来将网页内容转化为PDF文件。关键步骤包括设置页面滚动位置为顶部,利用html2canvas获取页面截图,然后用jspdf创建PDF并保存。注意解决当页面内容超出一页时滚动部分生成空白的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先引入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");
       }
   )
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值