Search code examples
javascripthtmlpdfdom-to-image

export pdf for two divs inside pdf pages using domtoimage.toPng


I have two divs (div1,div2) i want to export div1 inside pdf page 1 and export div2 inside pdf page 2 my problem i can capture only one div from them using domtoimage.toPng how can i capture both of divs my code : `

                               <script>
              $('#downloadPDF').click(function () {
              domtoimage.toPng(document.getElementById('div1'))
          //  domtoimage.toJpeg(document.getElementById('div2'))

    .then(function (blob) {
        var pdf = new jsPDF('p', 'pt', [$('#div1').width(), $('#div1').height()]);
        pdf.addImage(blob, 'PNG', 0, 0, $('#div2').width(), $('#div2').height());

  pdf.addPage();

        pdf.addImage(blob, 'PNG', 0, 0, $('#div1').width(), $('#div1').height());
        pdf.save("report.pdf");

        that.options.api.optionsChanged();
    });
    });
    </script>`

Solution

  • You need to prepare 2 blobs to save them into PDF.

    $('#downloadPDF').click(function() {
      Promise.all([
          domtoimage.toPng(document.getElementById('div1')),
          domtoimage.toPng(document.getElementById('div2'))
        ])
        .then(function([blob1,  blob2]) {
          var pdf = new jsPDF('p', 'pt', [$('#div1').width(), $('#div1').height()]);
          pdf.addImage(blob1, 'PNG', 0, 0, $('#div1').width(), $('#div1').height());
    
          pdf.addPage();
    
          pdf.addImage(blob2, 'PNG', 0, 0, $('#div2').width(), $('#div2').height());
          pdf.save("report.pdf");
    
          that.options.api.optionsChanged();
        });
    });