使用html2canvas截图不全问题的解决办法

2023-12-01 0 400
目录
  • 实现方法
  • 遇见问题
  • 具体封装代码
  • 总结

实现方法

利用 html2canvas 工具将html转为图片流 npm install html2canvas利用 jspdf 工具 将图片流转为 pdf 并保存 npm install jspdf

遇见问题

1、截图不全

之前没用过这个,网上找了代码之后发现有滚动条的情况下会截图不全,仅能展示出当前页面展示出来的内容,类似于这种情况,这是带滚动条的html,第一张和第二张分别为滚动条在顶部以及在底部的展现

使用html2canvas截图不全问题的解决办法

使用html2canvas截图不全问题的解决办法

下载成pdf之后分别为这样,只有窗口展示的部分,滚动条以外的内容没有

使用html2canvas截图不全问题的解决办法

使用html2canvas截图不全问题的解决办法

百度之后有让改参数的,也有让滚动条滚至顶部的,感觉都不是我的问题,直觉说是元素高度哪里有问题,原来的页面元素是这么写的,对比下载后的文件,内容高度大概和最外面的div高度是一样的,外面盒子的高度又是固定的,本人就试了下在里面再加一个div,且不设置高度,让其高度完全由内容撑开,问题就解决了

<div class=\”red-div\” id=\”pdfDom_children\”> // 这里是滚动的div
<div class=\”first-div\”></div>
<div class=\”second-div\”></div>
<div>111</div>
</div>

修改后的页面元素

<div class=\”red-div\”>
<div id=\”pdfDom_children\”>
<div class=\”first-div\”></div>
<div class=\”second-div\”></div>
<div>111</div>
</div>
</div>

具体封装代码

// 导出页面为PDF格式
import html2canvas from \”html2canvas\”;
import JsPDF from \”jspdf\”;
const htmlToPdf = {
getPdf(title: string) {
const targetDom = document.getElementById(\”pdfDom_children\”);
html2canvas(document.querySelector(\”#pdfDom_children\”), {
allowTaint: true,
backgroundColor: \”white\”,
useCORS: true, //支持图片跨域
scale: 1, //设置放大的倍数
// height: targetDom.clientHeight, // 网上原来的设置,没用,注释掉了
// width: targetDom.clientWidth, // 网上原来的设置,没用,注释掉了
// windowHeight: targetDom.clientHeight, // 网上原来的设置,没用,注释掉了
}).then((canvas) => {
//内容的宽度
const contentWidth = canvas.width;
//内容的高度
const contentHeight = canvas.height;
//一页pdf显示htm1页面生成的canvas高度,a4纸的尺寸[595.28,841.89];
const pageHeight = (contentWidth / 592.28) * 841.89;
//未生成pdf的htm1页面高度
let leftHeight = contentHeight;
//页面偏移
let position = 0;
//a4纸的尺寸[595.28,841.89],htm1页面生成的canvas在pdf中图片的宽高
const imgwidth = 595.28;
const imgHeight = (592.28 / contentWidth) * contentHeight;
//canvas转图片数据
const pageData = canvas.toDataURL(\”img/jpeg\”, 1.0);
//新建JSPDF对象
const PDF = new JsPDF(\”\”, \”pt\”, \”a4\”);
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;
if (leftHeight > 0) {
PDF.addPage();
}
}
}
console.log(pageData); //保存文件
PDF.save(title + \”.pdf\”);
});
},
};
export default htmlToPdf;

总结

到此这篇关于使用html2canvas截图不全问题的解决办法的文章就介绍到这了,更多相关html2canvas截图不全问题内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

您可能感兴趣的文章:

  • vue项目中如何实现网页的截图功能 (html2canvas)

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 JavaScript 使用html2canvas截图不全问题的解决办法 https://www.u-9.cn/biancheng/javascript/5195.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务