Search code examples
javascriptjqueryjspdfhtml2canvas

How to Save do an callback/action when all divs are rendered using html2canvas


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.


Solution

  • 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"); }
                });
            });
        }