编程语言
首页 > 编程语言> > javascript – 如何使用jsPDF在PDF中以两页显示图像?

javascript – 如何使用jsPDF在PDF中以两页显示图像?

作者:互联网

我有一个HTML页面.我有一个按钮,当我单击此按钮时,它将使用html2canvas将整个html页面转换为数据图像,并使用jsPDF库将其放入PDF.
我正在使用的javascript

$("#printButton").click(function(){
html2canvas([document.getElementById('form1')], {
        onrendered: function (canvas) {
            var imageData = canvas.toDataURL('image/jpeg',1.0); 
           var doc = new jsPDF('landscape');
           doc.addImage(imageData,'JPEG',5,20,200,150);
           doc.save('Test.pdf');
     }
    });
});

它仅在第一页显示图像.但是每当html页面大小更多时,我想剪切图像数据并将其放在PDF格式的两页中.
请帮我解决这个问题.

解决方法:

这可能不是完美的答案,但仍然有效

                $("#btnSaveAsPDF").click(function () {
                html2canvas($("#tblSaveAsPdf_canvas"), {
                onrendered: function (canvas) {
                var imageData = canvas.toDataURL("image/jpeg");
                var image = new Image();
                image = Canvas2Image.convertToJPEG(canvas);
                var doc = new jsPDF();
                doc.addImage(imageData, 'JPEG', 12, 10);
                var croppingYPosition = 1095;
                count = (image.height) / 1095;

                for (var i =1; i < count; i++) {
                        doc.addPage();
                        var sourceX = 0;
                        var sourceY = croppingYPosition;
                        var sourceWidth = image.width;
                        var sourceHeight = 1095;
                        var destWidth = sourceWidth;
                        var destHeight = sourceHeight;
                        var destX = 0;
                        var destY = 0;
                        var canvas1 = document.createElement('canvas');
                        canvas1.setAttribute('height', destHeight);
                        canvas1.setAttribute('width', destWidth);                         
                        var ctx = canvas1.getContext("2d");
                        ctx.drawImage(image, sourceX, 
                                             sourceY,
                                             sourceWidth,
                                             sourceHeight, 
                                             destX, 
                                             destY, 
                                             destWidth, 
                                             destHeight);
                        var image2 = new Image();
                        image2 = Canvas2Image.convertToJPEG(canvas1);
                        image2Data = image2.src;
                        doc.addImage(image2Data, 'JPEG', 12, 10);
                        croppingYPosition += destHeight;              
                    }                  
                var d = new Date().toISOString().slice(0, 19).replace(/-/g, "");
                filename = 'report_' + d + '.pdf';
                doc.save(filename);
            }

        });
    });

标签:jspdf,html2canvas,javascript,jquery,pdf
来源: https://codeday.me/bug/20191004/1852898.html