如何将 html2pdf PDF 转换为 base64?

How do I convert html2pdf PDF to base64?

我在让 html2pdf.js 正确地给我一个回调以便我可以将它转换为 base64 字符串时遇到一些问题。

我试过这个:

html2pdf().from(el).then(function(pdf) { 
   // pdf is null when I log this...
   console.log(pdf);
}).save();

以及使用从 output() 到此的所有内容的许多其他变体:

var pdf = new jsPDF();
html2pdf().from(element).set({ pdf: pdf }).toPdf().save();

一切都无济于事。

我目前在 v.0.9.0。我真正需要的只是 base64,这样我就可以将其发送回服务器并将其附加到电子邮件中——我如何实现它并不重要,但我在弄清楚如何使用它时遇到了问题正确回调

我已经在 github 上搜索了文档和 issues

缺少的是对 outputPdf() 方法的调用。您还应确保已升级到最新版本的 html2pdf 插件,因为旧版本不支持此功能。

您的新代码应如下所示:

html2pdf().from(el).outputPdf().then(function(pdf) {
    // This logs the right base64
    console.log(btoa(pdf));
});

来自documentation

[outputPdf] Sends type and options to the jsPDF object's output method, and returns the result as a Promise (use .then to access)

简单地使用 output() 不会 return 承诺,您必须使用 outputPdf()