I want to export HTML to PDF with JavaScript, I saw libraries like jsPDF and pdfMake, but they are very limited. For example, with none of them I can export HTML elements, like <hr>
, with jsPDF the styling is very limited, I saw this question but the answer is not working for me, with pdfMake I cannot download the pdf, just with chrome.
If you can retrieve the HTML from an URL you may want to check this answer that I wrote that explains how to do it.
Example:
https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=show
It's so easy to put an anchor in your HTML that shows the PDF or downloads it in your HTML.
This anchor will show the PDF converted from the https://www.github.com
page:
<a href="https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=show" target="_blank">Show PDF</a>
And this one will download it:
<a href="https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=download&file_name=my_pdf">Download PDF</a>
If you want to try it with JavaScript, you could create an HTML button and on click event download the PDF. Example:
HTML:
<button type="button" id="download-pdf-button">Download the PDF</button>
JavaScript:
document.getElementById("download-pdf-button").addEventListener("click", function() {
var link = document.createElement('a');
link.href = 'https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=download';
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
});
See the project in Github.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With