Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-20 20:12:02
Original
871 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!