简体   繁体   English

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

[英]Javascript: Save html window as pdf using jsPDF

I am using this piece of javascript to print out some html content: 我正在使用这段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;
}

And this work absolutely fine. 而且这项工作绝对不错。

It opens the print dialog and then you can either 'print' it or 'save it as pdf'. 它会打开“打印”对话框,然后您可以“打印”或“另存为pdf”。

What I'd like to do is to skip the print dialog and save (download) it as pdf sraight away at the end of my function. 我想做的是跳过打印对话框,并在功能结束时将其另存为(pdf)。 I found a lot of suggestions to use jsPDF library for this, but couldn't find any easy examples on how to use it in my case... 我发现了很多使用jsPDF库的建议,但是找不到任何简单的示例来说明如何使用它。

Any advise is highly appreciated :) 任何建议,高度赞赏:)

I found a nice demo here showing what you need. 我在这里找到了一个不错的演示展示了您的需求。

There is also a codepen link for the same given at the bottom of that page where you can check out the complete code with html markup 该页面底部还提供了一个Codepen链接,您可以在其中使用html标记检出完整的代码

In short, if your HTML markup is like below 简而言之,如果您的HTML标记如下所示

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

Then on click over button, you can generate the pdf this way just by calling save function over the jsPDF object 然后在单击按钮上,您可以通过在jsPDF对象上调用save函数来以这种方式生成pdf

var doc = new jsPDF();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM