Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 354
Alessandro Dentella Avatar asked Jan 10 '19 10:01

Alessandro Dentella


3 Answers

For all of you who are using webpack what I did is I added html2canvas to a ProvidePlugin. You can read about this here

// webpack configuration
plugins: [
    new webpack.ProvidePlugin({
        html2canvas: 'html2canvas'
    });
]
like image 198
Martiuh Avatar answered Sep 20 '22 03:09

Martiuh


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.

like image 35
ax_pernot Avatar answered Sep 24 '22 03:09

ax_pernot


Following the previous anser by ptidus, this should work:

saveAsPdf() {
  window.html2canvas = html2canvas;
  var doc = new jsPDF(
    'p', 'pt', 'a4'
  );
  doc.html(document.querySelector("body"), {
    callback: function(pdf) {
      pdf.save("cv-a4.pdf");
    }
  });
}

There is something off with the margins probably, but I didn't explore that too much. You will also notice that the generated PDF is actually text and not an image.

code example

like image 27
Amit Merin Avatar answered Sep 23 '22 03:09

Amit Merin