0

I am iterating through list of divs,converting them to canvas and then adding them to jspdf.

After doing all these I am saving them to disk.

   function exportDataTablesAsPDF() {
        var dataTablesToBeExported = $('.js-exportdiv');


        $.each(dataTablesToBeExported, function (index, element) {

            html2canvas(element).then(function (canvas) {
                var img = canvas.toDataURL("image/png");
                masterPdf.addImage(img, 'PNG', 0, 0,canvas.width,canvas.height);
            });
        });
       masterPdf.save("Test.pdf");
    }

But the problem here is , masterPdf.save() executes before all canvas call backs are complete.

The pdf gets downloaded befoe all the images are added to the document. Is there a way, I can wait for all then(canvas) to finish and download the pdf.

Simsons
  • 12,295
  • 42
  • 153
  • 269

1 Answers1

3

You could try calling masterPdf.save after all the images have been added.

Something like

 function exportDataTablesAsPDF() {
        var dataTablesToBeExported = $('.js-exportdiv');
        var numberOfImages = dataTablesToBeExported.length;


        $.each(dataTablesToBeExported, function (index, element) {

            html2canvas(element).then(function (canvas) {
                var img = canvas.toDataURL("image/png");
                masterPdf.addImage(img, 'PNG', 0, 0,canvas.width,canvas.height);
                if (index + 1 == numberOfImages) { masterPdf.save("Test.pdf"); }
            });
        });
    }
Umang Raghuvanshi
  • 1,228
  • 15
  • 34
  • Don't you think you are doing the same thing as written in the question because the JS function is synchronous and save method is calling only after whole $.each finished. – Ullas Hunka Jul 27 '18 at 05:20
  • I believe that `html2canvas` is the async code here and `masterPdf.addImage` is sync. Obviously, it is hard to be sure about that without knowing what class `masterPdf` belongs to @UllasHunka. – Umang Raghuvanshi Jul 27 '18 at 05:23