Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML2Canvas creating multiple divs

I'm trying to create a PDF using jsPDF and HTML2Canvas. I have multiple DIVs to insert into the PDF. If I try to put all DIVs into a container and render once then it only puts the first page height into the PDF. Can't figure out how to render multiple divs and stick them in the same PDF so that it keeps going page by page.

JAVASCRIPT

function genPDF() {         
    html2canvas(document.getElementById("container"), {

        onrendered: function (canvas) {

            var img = canvas.toDataURL();

            var doc = new jsPDF(); 
            doc.addImage(img, 'PNG');
            doc.addPage(); 

            doc.save('test.pdf');
        }
    });
}

HTML

<div id="container">
    <div class="divEl" id="div1">Hi <img  src="img1.JPG"> </div>
    <div class="divEl" id="div2">Why <img  src="img2.PNG"> </div>
</div>

<button onClick="genPDF()"> Click Me </button>
like image 238
Timo Avatar asked Sep 08 '26 08:09

Timo


1 Answers

Add each of your images separately.
You need to wait for all the html2canvas renderings are done and added to pdf and then save your final pdf.

One way to achieve this by using JQuery and array of promises, actual code would look like this:

function genPDF() { 
    var deferreds = [];
    var doc = new jsPDF();
    for (let i = 0; i < numberOfInnerDivs; i++) {
        var deferred = $.Deferred();
        deferreds.push(deferred.promise());
        generateCanvas(i, doc, deferred);
    }

    $.when.apply($, deferreds).then(function () { // executes after adding all images
      doc.save('test.pdf');
    });
}

function generateCanvas(i, doc, deferred){

    html2canvas(document.getElementById("div" + i), {

        onrendered: function (canvas) {

            var img = canvas.toDataURL();
            doc.addImage(img, 'PNG');
            doc.addPage(); 

            deferred.resolve();
         }
    });
}
like image 70
Basel Issmail Avatar answered Sep 12 '26 08:09

Basel Issmail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!