I want to convert HTML to PDF with the click of a button and download
HTML
<div id="pageprint">
<div id="reportbox">Hello World!!</div>
</div>
<button type="button" onclick="downloadCode();">Download HTML</button>
Javascript
<script>
function generatePDF() {
const element = document.getElementById("pageprint");
document.getElementById("reportbox").style.display = "block";
document.getElementById("reportbox").style.marginTop = "0px";
document.getElementById("pageprint").style.border = "1px solid black";
html2pdf().from(element).save('download.pdf');
}
function downloadCode(){
var x = document.getElementById("reportbox");
generatePDF();
setTimeout(function() { window.location=window.location;},3000);}
</script>
CodePudding user response:
You can print html just as follow.
<style type="text/css">
@media print{ button {display:none} };
</style>
<div id="pageprint">
<div id="reportbox">Hello World!!</div>
</div>
<button type="button" onclick=javascript:window.print()>Download HTML</button>
Please let me know if any issue found
CodePudding user response:
There isn't an easy way to do this. The best thing you could do is to open an empty page, fill it with your html data and print it to pdf. Or look for some external libary like jsPDF.
example for print to pdf:
var wnd = window.open('about:blank', '', '_blank');
wnd.document.write("<p> Some HTML-Content </p> ");
wnd.print();