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.
-
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 filePhil– Phil2015-07-08 06:18:43 +00:00Commented Jul 8, 2015 at 6:18
-
1In my project I cannot user a server, I have to do it on the client side...István– István2015-07-08 06:28:31 +00:00Commented Jul 8, 2015 at 6: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– glend2015-07-08 07:19:34 +00:00Commented Jul 8, 2015 at 7:19
Add a comment
|
1 Answer
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.
3 Comments
John Max
The project is no longer working. Can you please update it ?
John Max
The project has stopped working again. Please is there a way of forking it to avoid unpredictable interuption in the future ?
David López
Hi @JohnMax, I've answered you in the issue you created on Github: 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