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

久未见 提交于 2019-12-06 07:38:33

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/54126963/jspdf-html2canvas-not-loaded-while-using-new-html-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!