我的目标是将包含图像的长 div 导出为 PDF 格式。我正在使用 Html2Canvas 和 JSPDF 库。 我已经成功地拍摄了快照并将其导出到不同页面中的JS。 然而,我面临的问题是,当 Canvas 元素将其导出为一张大图像时,原始图像会被剪切。 我相信有帮助的解决方案是如果下一个元素不适合 A4 尺寸,则提供填充/空间。
以下是我的代码
function Export2PDF(element){
var div = document.getElementById("ExportDiv");
var rect = div.getBoundingClientRect();
var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;
var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);
document.body.appendChild(canvas)
html2canvas(div, {
canvas:canvas,
height:rect.height,
width:rect.width,
onrendered: function(canvas) {
var image = canvas.toDataURL("image/png");
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(image, 'PNG', 20, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(image, 'PNG', 20, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save( 'file.pdf');
}
});
}
任何人都可以帮助我实现同样的目标吗?预先感谢您。
编辑
div结构如下:-
<div>
<table >Table 1
<tr>
<tr>
<tr>
</table>
<table >Table 2</table>
<table >Table 3</table>
</div>
最佳答案
当我遇到类似的问题时,我跟踪高度“指针”的位置,当 currentHeight + imageHeight > somevalue
时,我只是添加了新页面,示例代码:
var height = 0;
var image = loadImage();
...
...
doc.text(0, height, 'asd');
height += 30;
if (height + image.height > 230) //you need to experiment with value, I found that 230 was fine for me
{
doc.addPage();
height = 0;
}
doc.image(0, height, image);
关于javascript - 如果元素不适合 A4 尺寸,请为其留出空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51653978/