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.
Asked
Active
Viewed 5,610 times
5
-
2The best thing I've seen for this is to use a server-side process to fire up PhantomJS, print to PDF and respond with the generated file – Phil Jul 08 '15 at 06:18
-
1In my project I cannot user a server, I have to do it on the client side... – István Jul 08 '15 at 06:28
-
This is a problem I'm struggling with currently, I have a vested interest in getting this solved. The way I see it is that any server-side solution should use a recognized rendering engine, with something like PhantomJS its not clear what rendering engine it is using, therefor results may not be as desired, especially with newer HTML5 elements. The other problem is automation from a separate process, Java application. Its easy to print to a PDF from a browser providing you have a print driver. I am assuming we both have automation needs. – glend Jul 08 '15 at 07:19
1 Answers
1
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'));
});
Hope it helps.

David López
- 488
- 3
- 8
-
-
The project has stopped working again. Please is there a way of forking it to avoid unpredictable interuption in the future ? – John Max May 28 '20 at 14:50
-
Hi @JohnMax, I've answered you in the issue you created on Github: https://github.com/Dellos7/dhtml2pdf/issues/7 , there I explain you how you could fork it in order to set up your own Heroku instance with the app – David López May 29 '20 at 17:13