Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JS to print page as PDF in Chrome and open it

I have an internal site with lots of different pages, all of them has a printable version controlled by CSS only. My users create PDFs using Chrome's Print/Save As PDF menu command. I wonder if it would be possible to use JavaScript to initiate Save As PDF from a button and automatically open the saved PDF (actually saving is not important, just viewing it on a new tab is fine).

Chrome-only solution is OK. It's also not a problem if a Chrome extension needs to be installed. Anything is fine as long as I don't have to write extra PDF rendering code for each page layout.

like image 528
Arthur Avatar asked Feb 19 '17 06:02

Arthur


People also ask

How do I print a PDF in JavaScript?

An iframe is used to display a web page within a web page. The iframe needs a source of the web page to display. We can use the iframe to display contents of our PDF document and then print the contents using a JavaScript code. However, you can also directly print the PDF document, without opening the file.

Is it possible to save HTML page as PDF using JavaScript or jquery?

If you want a client-side solution to generate PDF document, JavaScript is the easiest way to convert HTML to PDF. There are various JavaScript library is available to generate PDF from HTML. The jsPDF is one of the best library to convert HTML to PDF using JavaScript.


1 Answers

There is no way to force a browser to print something as a PDF, or even send a request to a printer, the best method you can do it use the print() function in JavaScript.

A way you can do this is to make it an iframe object and print it like this:

document.getElementById('content-frame').contentWindow.window.print();

That would make it send a print menu for the iFrame, printing only the content within the iFrame.

like image 193
Steel Avatar answered Sep 27 '22 20:09

Steel