Center image doc.addImage jspdf

问题描述 投票:2回答:1

我正在使用html2canvas截取我的页面的屏幕快照,并使用jspdf创建图像的pdf。现在,我的图像在pdf文档中保持对齐,我希望它居中,如何实现?

function pdfmaker() {

    var element = $("#timesheet");

    document.getElementById("message").style.display = "block";
    document.getElementById("logo").style.display = "block";
    var firstName = "<?php echo $fname?>";
    var lastName = "<?php echo $lname ?>";
    var startDate = "<?php echo $startDate?>";
    var endDate = "<?php echo $endDate ?>";

    html2canvas(element, {
        useCORS: true,
        onrendered: function(canvas) {
            var imgData = canvas.toDataURL("image/png");


            var imgWidth = 297; //297
            var pageHeight = 297; //297  
            var imgHeight = canvas.height * imgWidth / canvas.width;
            var heightLeft = imgHeight;

            // var doc = new jsPDF('l', 'mm',[1350, 1350]);
            var doc = new jsPDF('l', 'mm', [420, 297]); //420,297
            var position = 5; //0

            margins = {

                top: 20,
                bottom: 10,
                left: 45,
                width: 522
            };


            doc.addImage(imgData, 'PNG', 5, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;

            while (heightLeft >= 5) {
                position = heightLeft - imgHeight;
                doc.addPage();
                doc.addImage(imgData, 'PNG', 5, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;
            }

            doc.save(firstName + '_' + lastName + '_Summary_report_' + startDate + '_' + endDate + ".pdf");
        }
    });

    document.getElementById("message").style.display = "none";
    document.getElementById("logo").style.display = "none";

}
jspdf html2canvas
1个回答
1
投票

您需要使用坐标参数在addImage()方法内定义,请参见:http://raw.githack.com/MrRio/jsPDF/master/docs/module-addImage.html

这是唯一的方法。为此,我建议您使用以下方法doc.internal.pageSize.getWidth();计算关于图像宽度的多余值,该值将居中。

© www.soinside.com 2019 - 2024. All rights reserved.