Search code examples
jspdfhtml2canvas

jsPDF - multiple pages - rendering HTML always going to page1


We use jsPDF 2.5.1 to render a multi page PDF.

We use the html function to render various DOM elements to each page, and this was working in version 1.x of jsPDF

However now every time we call .html() - it puts it on the first page, rather than the newly added page, here is the code

if (pdfPageIndex < numPdfPages) {
    if (pdfPageIndex > 0) {
        pdf.addPage();
    }

    pdf.html(
        document.getElementById('pdfPage_' + pdfPageIndex),             
        {
         html2canvas: {
             logging: true
             },
         callback: function(){ return pdfCallback($scope)}});

Solution

  • Please try with below addImage method based on canvas height and width it will render in multiple pages

    const data = document.getElementById('pdfPage_');
    html2canvas(data).then((canvas:any) => {
      const imgWidth = 208;
      const pageHeight = 295;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      let heightLeft = imgHeight;
      let position = 0;
      heightLeft -= pageHeight;
      const doc = new jspdf('p', 'mm');
      doc.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');
        heightLeft -= pageHeight;
      }
      doc.save('Downld.pdf');
    });