简体   繁体   English

单击按钮将 HTML 页面转换为可下载的 PDF

[英]Converting the HTML page to a downloadable PDF with a button click

I wanted to convert my HTML page to a PDF file with a button click.我想通过单击按钮将我的 HTML 页面转换为 PDF 文件。 After I click this "Download" button, I want the PDF to be automatically downloaded.单击此“下载”按钮后,我希望自动下载 PDF。

I tried this:我试过这个:

<button onclick="printFunction()">Download</button>
<script>
      function printFunction() { 
        window.print(); 
      }
</script>

But this can only generate a print page, which I need to save the PDF file manually.但是这样只能生成打印页面,需要我手动保存到PDF文件中。

I searched online and find a lot of answers that suggest we add a third-party plug-in.我在网上搜索了很多答案,建议我们添加第三方插件。 Is there an easier way to do that?有更简单的方法吗?

I found a similar example here: https://phpcoder.tech/download-html-page-as-pdf-using-javascript/我在这里找到了一个类似的例子: https://phpcoder.tech/download-html-page-as-pdf-using-javascript/

I'd use html2pdf我会使用 html2pdf

<body id="body">
<button id="button">Click me!</button>

<script src="html2pdf.bundle.min.js"></script>
<script>
const btn = document.getElementById("button");

btn.addEventListener("click", function(){
var element = document.getElementById('body');
html2pdf().from(element).save('filename.pdf');
});
</script>
</body>

here are the docs https://www.npmjs.com/package/html2pdf.js/v/0.9.0 You can change filename.pdf to whatever you want (aside from the extension)这是文档https://www.npmjs.com/package/html2pdf.js/v/0.9.0您可以将 filename.pdf 更改为您想要的任何内容(除了扩展名)

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

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