html2canvas/jsPDF - images not showing when converting html to a pdf

Viewed 5106

I'm looking to convert some simple HTML into a PDF. It seems the easiest way to do this and keep the css styling is to use the 'html2canvas' js library to convert the html to canvas first, and then create the PDF using jsPDF.

The issue I'm getting is that I have both a background image and inline image in my HTML but neither are showing in the PDF once converted. I've created a Codepen here: https://codepen.io/adamboother/pen/NWGeqom

Here's my js that does the conversion:

function convertToPdf()
{
    html2canvas(document.querySelector('#certificate')).then(canvas => {
        let pdf = new jsPDF('landscape', 'mm', 'a4');

        pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);

        pdf.save('certificate.pdf');
    });
}

Has anyone found a fix for this?

1 Answers

I am using useCORS: true to your code and it works, assuming your image is in the server. Besides you can follow below code:

function convertToPdf()
{ 
    html2canvas(document.querySelector('#certificate'), {useCORS: true}).then(function(canvas) {
      let img = new Image();
      img.src = canvas.toDataURL('image/png');
      img.onload = function () {
        let pdf = new jsPDF('landscape', 'mm', 'a4');
        pdf.addImage(img, 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
        pdf.save('certificate.pdf');
      };
    });
}
Related