Home  >  Article  >  Web Front-end  >  How to Direct Print PDFs from JavaScript Using embed and .print()?

How to Direct Print PDFs from JavaScript Using embed and .print()?

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 20:12:02878browse

How to Direct Print PDFs from JavaScript Using embed and .print()?

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 tag to embed the PDF within the document:

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn