Direct PDF Printing from JavaScript
Creating a list of PDFs in HTML with both download links and print options is a common requirement. To streamline the user experience, avoiding the need to open PDF viewers or display PDFs before printing is desirable.
This question explores a solution using JavaScript to directly open the print dialog for a PDF without displaying it. One proposed approach involves embedding the PDF in a hidden iframe and triggering its printing via JavaScript.
Embed and Print Method
The provided solution utilizes an
<code class="html"><embed type="application/pdf" src="path_to_pdf_document.pdf" id="pdfDocument" width="100%" height="100%" /></code>
Once embedded, JavaScript is used to invoke the .print() method on the PDF element:
<code class="javascript">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(); } }</code>
This technique allows the PDF to be printed seamlessly without any user interaction or visible display. Incorporating this approach into a hidden iframe can provide a seamless and user-friendly printing experience.
The above is the detailed content of How to Direct Print PDFs from JavaScript Using embed and .print()?. For more information, please follow other related articles on the PHP Chinese website!