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

前端 未结 4 2513
刺人心
刺人心 2021-02-20 03:10

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

savePdf () {
  var pdf = new jsPDF({u         


        
相关标签:
4条回答
  • 2021-02-20 03:52

    The following two had fixed the issue:

    1. // webpack configuration plugins: [ new webpack.ProvidePlugin({ html2canvas: 'html2canvas' }); ]

    2. window["html2canvas"] = html2canvas;

    even with out the first step its working.

    0 讨论(0)
  • 2021-02-20 04:01

    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.

    0 讨论(0)
  • 2021-02-20 04:15

    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

    0 讨论(0)
  • 2021-02-20 04:16

    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'
        });
    ]
    
    0 讨论(0)
提交回复
热议问题