Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print PDF directly from JavaScript

Tags:

javascript

pdf

I am building a list of PDFs in HTML. In the list I'd like to include a download link and a print button/link. Is there some way to directly open the Print dialog for the PDF without the user seeing the PDF or opening a PDF viewer?

Some variation of downloading the PDF into a hidden iframe and triggering it to print with JavaScript?

like image 842
Craig Celeste Avatar asked Apr 26 '13 15:04

Craig Celeste


People also ask

How do you print using JavaScript?

JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the window.print() method in the browser to print the content of the current window.

How can I download a PDF from a URL using JavaScript?

download = 'file. pdf'; link. dispatchEvent(new MouseEvent('click')); } var fileURL = "link/to/pdf"; var fileName = "test. pdf"; download(fileURL,fileName);


2 Answers

Based on comments below, it no longer works in modern browsers
This question demonstrates an approach that might be helpful to you: Silent print an embedded PDF

It uses the <embed> tag to embed the PDF in the document:

<embed     type="application/pdf"     src="path_to_pdf_document.pdf"     id="pdfDocument"     width="100%"     height="100%" /> 

Then you call the .print() method on the element in Javascript when the PDF is loaded:

function printDocument(documentId) {     var doc = document.getElementById(documentId);      //Wait until PDF is ready to print         if (typeof doc.print === 'undefined') {             setTimeout(function(){printDocument(documentId);}, 1000);     } else {         doc.print();     } } 

You could place the embed in a hidden iframe and print it from there, giving you a seamless experience.

like image 150
nullability Avatar answered Sep 30 '22 09:09

nullability


Here is a function to print a PDF from an iframe.

You just need to pass the URL of the PDF to the function. It will create an iframe and trigger print once the PDF is load.

Note that the function doesn't destroy the iframe. Instead, it reuses it each time the function is call. It's hard to destroy the iframe because it is needed until the printing is done, and the print method doesn't has callback support (as far as I know).

printPdf = function (url) {   var iframe = this._printIframe;   if (!this._printIframe) {     iframe = this._printIframe = document.createElement('iframe');     document.body.appendChild(iframe);      iframe.style.display = 'none';     iframe.onload = function() {       setTimeout(function() {         iframe.focus();         iframe.contentWindow.print();       }, 1);     };   }    iframe.src = url; } 
like image 27
Nicolas BADIA Avatar answered Sep 30 '22 08:09

Nicolas BADIA