jsPDF: html2canvas not loaded while using new .html() method

Alessandro Dentella picture Alessandro Dentella · Jan 10, 2019 · Viewed 11.3k times · Source

I want to use jsPDF.html to convert html page to pdf, and I'm using this code:

savePdf () {
  var pdf = new jsPDF({unit: 'mm', format: 'a4', orientation: 'portrait' })
  pdf.html(document.getElementById('printable-cv'), {
    callback: function (pdf) {
      pdf.save('cv-a4.pdf');
    }
  })
}

but I get error html2canvas not loaded: is it something I forgot? I do have html2canvas

"html2canvas": "^1.0.0-alpha.12"

I'm using vuejs with webpack.

In the same page I'm currently using alternatively html2pdf with the following code:

savePdf0 () {
  let opt = {
    filename: 'cv.pdf',
    enableLinks: true,
    image: { type: 'jpeg', quality: 0.98 },
    html2canvas: {
      scale: 8,
      useCORS: true,
      width: 310,
      letterRendering: true,
    },
    jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
  }
  html2pdf().set(opt).from(document.getElementById('printable-cv')).save()
}

that correcly finds html2canvas.

What does html2canvas not loaded really mean? what can I do to load it?

Answer

ax_pernot picture ax_pernot · Jan 14, 2019

jsPDF needs html2canvas to be declared in the global scope to work, so you have to write

window.html2canvas = html2canvas;

somewhere before you call html().

That said, I wasn't able to make it work either, so I resorted to a wrapper that works around the issue by calling manually html2canvas() then giving the resulting canvas to jsPDF.