首页 > 解决方案 > JS中的HTML到PDF使用变量

问题描述

这是我的第一篇文章,因为我被卡住了,我在这里或网络上都没有找到解决方案。

我想使用 JS 将 HTML 转换为 PDF。我正在搜索,最好的选择似乎是 HTML2canvas 和 JSpdf。但我的想法是我的 HTML 存储在一个变量中:

var test = '<html><head><script type="text/javscript">var number = 123;</script></head><body>
<h1>"the value for number is: " + number</h1></body></html>'

我的变量要复杂得多,它包含 CSS 和样式,但这只是为了理解。然后,当我尝试将其转换为画布时,它不会转换。

const filename  = 'ThisIsYourPDFFilename.pdf';

html2canvas(test).then(canvas => {
    let pdf = new jsPDF('p', 'mm', 'a4');
    pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
    pdf.save(filename);
}); 

有谁知道为什么会这样?也许这是一个非常愚蠢的问题,但我不知道如何避免错误。

先感谢您。

标签: javascripthtml2canvas

解决方案


您使用字符串作为 html2canvas 的参数,但它需要 HTML 元素:

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

查看他们的文档

我修改了你的代码:

const html2canvas = require("html2canvas");
const jsPDF = require("jspdf");

html2canvas(document.getElementById("screenshot"), { scale: 1 }).then(
  (canvas) => {
    document.body.appendChild(canvas);
    const filename = "ThisIsYourPDFFilename.pdf";
    let pdf = new jsPDF("p", "mm", "a4");
    pdf.addImage(canvas.toDataURL("image/png"), "PNG", 0, 0);
    pdf.save(filename);
    document.body.removeChild(canvas);
  }
);

正文应包含带有 id 屏幕截图的元素:

<div id="screenshot">
    Content
</div>

更新

根据这个资源jsPDF 有方法fromHTML,所以你可能不需要 html2canvas

var doc = new jsPDF();
var elementHTML = $('#contnet').html();
var specialElementHandlers = {
    '#elementH': function (element, renderer) {
        return true;
    }
};
// note here that it uses html
doc.fromHTML(elementHTML, 15, 15, {
    'width': 170,
    'elementHandlers': specialElementHandlers
});

// Save the PDF
doc.save('sample-document.pdf');

推荐阅读