How to split page after adding the image using HTML2Canvas and jspdf

Viewed 3325

Using html2canvas and JsPDF for converting HTML to pdf and using below code for generating the code this code will give convert the complete html of div to single image and wil show in the pdf as single page.

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');
    
      });

}

For split the code i used below code which split the pages into the multiple pages but not spliting the space correctly because my pdf has small images attached 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');`

Is their any approach to split the page according to the static height which split the image from particular position?

1 Answers
  1. First we have to restrict canvas image height and width
html2canvas(divToPrint, {
        width: 2480,
        height: 3508
      }).then((canvas) => {

})
  1. Then we can split this canvas image easily.
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");
      });
Related