直接从 JavaScript 打印 PDF [英] Print PDF directly from JavaScript

查看:21
本文介绍了直接从 JavaScript 打印 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 HTML 构建一个 PDF 列表.在列表中,我想包含一个下载链接和一个打印按钮/链接.有没有办法直接打开 PDF 的打印"对话框,而无需用户查看 PDF 或打开 PDF 查看器?

I am building a list of PDFs in HTML. In the list I'd like to include a download link and a print button/link. Is there some way to directly open the Print dialog for the PDF without the user seeing the PDF or opening a PDF viewer?

将 PDF 下载到隐藏的 iframe 并触发它使用 JavaScript 打印的一些变体?

Some variation of downloading the PDF into a hidden iframe and triggering it to print with JavaScript?

推荐答案

根据下面的评论,它不再适用于现代浏览器
这个问题展示了一种可能对您有帮助的方法:无声打印嵌入的 PDF

它使用 标签将 PDF 嵌入到文档中:

It uses the <embed> tag to embed the PDF in the document:

<embed
    type="application/pdf"
    src="path_to_pdf_document.pdf"
    id="pdfDocument"
    width="100%"
    height="100%" />

然后在加载 PDF 时在 Javascript 中调用元素上的 .print() 方法:

Then you call the .print() method on the element in Javascript when the PDF is loaded:

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();
    }
}

您可以将嵌入内容放置在隐藏的 iframe 中并从那里打印出来,为您提供无缝体验.

You could place the embed in a hidden iframe and print it from there, giving you a seamless experience.

这篇关于直接从 JavaScript 打印 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆