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

Can JavaScript Print PDFs Directly, Without User Interaction?

Barbara Streisand
Release: 2024-10-20 20:13:30
Original
310 people have browsed it

Can JavaScript Print PDFs Directly, Without User Interaction?

Printing PDFs Directly from JavaScript

Embedding PDFs in HTML lists often requires a download link and a print button or link. Can we directly open the Print dialog for the PDF without revealing the document itself or using a PDF viewer?

A potential solution involves using a hidden iframe. Here's how it works:

  1. Embed the PDF in a hidden iframe using the tag:

    <code class="html"><embed
        type="application/pdf"
        src="path_to_pdf_document.pdf"
        id="pdfDocument"
        width="100%"
        height="100%"
    /></code>
    Copy after login
  2. Define a JavaScript function to print the document:

    <code class="javascript">function printDocument(documentId) {
        var doc = document.getElementById(documentId);
    
        // Wait until PDF is ready
        if (typeof doc.print === 'undefined') {
            setTimeout(function() { printDocument(documentId); }, 1000);
        } else {
            doc.print();
        }
    }</code>
    Copy after login
  3. Call the printDocument() function when the PDF is loaded.

By using a hidden iframe, you can seamlessly print the PDF without the user seeing it or opening a PDF viewer.

The above is the detailed content of Can JavaScript Print PDFs Directly, Without User Interaction?. 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!