Search code examples
javascriptjspdfhtml2canvas

jsPDF & html2canvas not writing image to pdf


Using jspdf and html2canvas to take a snapshot of a users chosen configuration on a table configurator (choose top/side/laminate colors). Its achieved by changing the source of each image using transparent png.

I'm having issues inserting the image into the pdf. I can append it to the document with no issues and write text and other images to the pdf without issue. I fear my image is way too large. The generated base64 output is massive.

I have it writing to the console:

var doc = new jsPDF('p', 'pt','a4',true);
doc.setFontSize(16);
doc.setTextColor(80, 77, 78);
doc.text(15, 2, 'should be an image under here'); 
html2canvas($("#prod"), {
    useCORS : true,
    onrendered: function(canvas) {
       var imgData = canvas.toDataURL('image/jpeg');

       doc.addImage(imgData, 'JPEG', 15, 0, 34, 37);
        console.log(imgData);
        $('#prod').append(canvas);
    }
});
doc.save('Spec_Sheet.pdf');

https://jsfiddle.net/x3x0e6ws/51/

All images are coming from local server. I have a min-height on each of the elements, I even tried throwing text in the div to force a height.

How can I remedy this?

Thank you,


Solution

  • First of all, greatly appreciate the jsfiddle. Secondly, you were very close... just move your doc.save inside your html2canvas callback.

    To explain why:

    When you call html2canvas, this is an "asynchronous" call. That's why the second argument of the function is a "callback". The code continues on with the next line (in your case, doc.save) before it actually finished rendering or adding the canvas element! At some point later, the code html2canvas code returns to the callback when the canvas rendering is finished, and adds the image to your (already saved) pdf...!

    var doc = new jsPDF('p', 'pt','a4',true);
    doc.setFontSize(16);
    doc.setTextColor(80, 77, 78);
    doc.text(15, 2, 'should be an image under here'); 
    html2canvas($("#prod"), {
        useCORS : true,
        onrendered: function(canvas) {
           var imgData = canvas.toDataURL('image/jpeg');
    
           doc.addImage(imgData, 'JPEG', 15, 0, 34, 37);
           console.log(imgData);
           $('#prod').append(canvas);
           doc.save('Spec_Sheet.pdf');
        }
    });