如何使用 HTML2Canvas 和 jspdf 添加图像后拆分页面

Man*_*ana 3 javascript html2canvas jspdf angular

使用 html2canvas 和 JsPDF 将 HTML 转换为 pdf,并使用下面的代码生成代码,此代码会将 div 的完整 HTML 转换为单个图像,并将在 pdf 中显示为单个页面。

import * as jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

    htmltoPDF()
    {
        // parentdiv is the html element which has to be converted to PDF
        html2canvas(document.querySelector("#parentdiv")).then(canvas => {
    
          var pdf = new jsPDF('p', 'pt', [canvas.width, canvas.height]);
    
          var imgData  = canvas.toDataURL("image/jpeg", 1.0);
          pdf.addImage(imgData,0,0,canvas.width, canvas.height);
          pdf.save('converteddoc.pdf');
    
      });

}
Run Code Online (Sandbox Code Playgroud)

为了分割代码,我使用下面的代码将页面分割成多个页面,但没有正确分割空间,因为我的 pdf 附加了小图像。

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

enter code here

var doc = new jsPDF('p', 'mm');
var position = 0;

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

while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save( 'file.pdf');
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以根据从特定位置分割图像的静态高度来分割页面?

小智 5

  1. 首先我们必须限制画布图像的高度和宽度
html2canvas(divToPrint, {
        width: 2480,
        height: 3508
      }).then((canvas) => {

})
Run Code Online (Sandbox Code Playgroud)
  1. 然后我们就可以轻松地分割这个画布图像。
html2canvas(divToPrint, {
        width: 2480,
        height: 3508
      }).then((canvas) => {
        let imgWidth = 400;
        let pageHeight = 480;
        let imgHeight =
          ((canvas.height * imgWidth) / 2454)*1.24;
        var heightLeft = imgHeight;

        const imgData = canvas.toDataURL("image/png");

        const pdf = new jsPDF({
          orientation: "p",
          unit: "mm",
          format: [400, 480],
        });

        let position = 0;
        pdf.setFillColor(248);
        pdf.rect(0, 0, 400, 480, "F");
        pdf.addImage(Header, "JPEG", 0, 0, 400, 400);
        pdf.setFontSize(35);
        pdf.text('SMRF 360', 10, 420);
        pdf.setFontSize(15);
        pdf.text(`Feedback report`, 10, 433)
        pdf.text('March 2021', 10, 440)
        pdf.addPage();
        pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;

        while (heightLeft >= 0) {
          position = heightLeft - imgHeight;
          pdf.addPage();
          pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
          heightLeft -= pageHeight;
        }
        pdf.save("Result.pdf");
      });
Run Code Online (Sandbox Code Playgroud)

  • pdf.addImage(Header, "JPEG", 0, 0, 400, 400) 中的标题是什么;@N·迪亚斯 (2认同)