简体   繁体   中英

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. After I click this "Download" button, I want the PDF to be automatically downloaded.

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.

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/

I'd use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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