Javascript:使用jsPDF将html窗口保存为pdf

时间:2017-12-08 11:17:45

标签: javascript html pdf printing jspdf

我正在使用这段javascript打印出一些html内容:

function printHTML(htmlToPrint) {
    var mywindow = window.open('', 'PRINT', 'height=400, width=600');

    mywindow.document.write("<html><head><title>My Doc Title</title>");
    mywindow.document.write("</head><body>");
    mywindow.document.write(htmlToPrint);
    mywindow.document.write("</body></html>");

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

这项工作绝对没问题。

打开打印对话框,然后您就可以打印&#39;它或者将其保存为pdf&#39;。

我想要做的是跳过打印对话框并在我的功能结束时将其保存(下载)为pdf sraight。我发现了很多使用jsPDF库的建议,但是在我的案例中找不到任何关于如何使用它的简单示例...

任何建议都非常感谢:)

1 个答案:

答案 0 :(得分:0)

我找到了一个很好的演示here来展示你需要的东西。

在该页面底部还有一个codepen链接,您可以在其中查看带有html标记的完整代码

简而言之,如果您的HTML标记如下所示

<div id="content">
    <h3>Sample h3 tag</h3>
    <p>Sample pararaph</p>
</div>
<button id="cmd">Generate PDF</button>

然后在点击按钮上,只需在jsPDF对象上调用保存功能,就可以通过这种方式生成pdf

var doc = new jsPDF();

$('#cmd').click(function () {   
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
        'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});