【发布时间】:2018-08-02 21:04:01
【问题描述】:
我的目标是将包含图像的长 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>
【问题讨论】:
标签: javascript jquery html jspdf html2canvas