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/
CodePudding user response:
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)