Home >Web Front-end >JS Tutorial >Can JavaScript Print PDFs Directly, Without User Interaction?

Can JavaScript Print PDFs Directly, Without User Interaction?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 20:13:30403browse

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

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