I have created a simple & very easy to use API that uses the snappy library, based on the wkhtmltopdf webkit-based CLI, in order to convert an HTML page from the URL to PDF. Here is the Github repo: https://github.com/Dellos7/dhtml2pdf
This is an example of how to use it from an anchor tag. This will show the generated PDF of the https://www.github.com site in a new browser tab:
Show PDF
Example of how to use it to download the PDF:
Download PDF
With this solution you don't even need to use javascript in order to generate your PDF.
But if you still need to do it using javascript, you can do it like this:
document.getElementById("your-button-id").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'));
});
In the repo I also explain how to very easily clone & deploy your own API in Heroku so you can mantain the API yourself and not to depend on external services.