jsPDF:使用新的 .html() 方法时未加载 html2canvas

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

我想使用 jsPDF.html 将 html 页面转换为 pdf,我正在使用此代码:

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');
    }
  })
}

但我收到错误 html2canvas not loaded:是我忘记了什么吗?我有 html2canvas

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

我正在使用带有 webpack 的 vuejs。

在同一页面中,我目前正在使用以下代码替代 html2pdf

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()
}

正确找到 html2canvas。

html2canvas not loaded 到底是什么意思?我该怎么做才能加载它?

jsPDF 需要在全局范围内声明 html2canvas 才能工作,所以你必须写

window.html2canvas = html2canvas;

在你打电话之前的某个地方 html()

就是说,我也无法让它工作,所以我求助于 a wrapper 通过手动调用 html2canvas() 然后给出结果 canvas 来解决这个问题到 jsPDF。

根据 ptidus 之前的回答,这应该有效:

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

边距可能有问题,但我没有深入探讨。 您还会注意到生成的 PDF 实际上是文本而不是图像。

code example

对于所有使用 webpack 的人,我所做的是将 html2canvas 添加到 ProvidePluginYou can read about this here

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

以下两个已解决问题:

  1. //webpack配置 插件:[ 新 webpack.ProvidePlugin({ html2canvas: 'html2canvas' }); ]

  2. window["html2canvas"] = html2canvas;

即使没有第一步它的工作。