如果元素不适合A4大小,则为其留出空间

时间:2018-08-02 12:43:05

标签: javascript jquery html jspdf html2canvas

我的目标是将包含图片的long 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>

每个TR都以 THis is a TR

1 个答案:

答案 0 :(得分:0)

当我遇到类似的问题时,我会跟踪“指针”的高度以及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);
相关问题