直接从 JavaScript 打印 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16239513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print PDF directly from JavaScript
提问by Craig Celeste
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?
我正在用 HTML 构建一个 PDF 列表。在列表中,我想包含一个下载链接和一个打印按钮/链接。有没有办法直接打开 PDF 的“打印”对话框,而无需用户查看 PDF 或打开 PDF 查看器?
Some variation of downloading the PDF into a hidden iframe and triggering it to print with JavaScript?
将 PDF 下载到隐藏的 iframe 并触发它使用 JavaScript 打印的一些变体?
采纳答案by nullability
Based on comments below, it no longer works in modern browsers
This question demonstrates an approach that might be helpful to you: Silent print an embedded PDF
根据下面的评论,它不再适用于现代浏览器
这个问题展示了一种可能对您有帮助的方法:Silent print an Embedded PDF
It uses the <embed>
tag to embed the PDF in the document:
它使用<embed>
标签将 PDF 嵌入到文档中:
<embed
type="application/pdf"
src="path_to_pdf_document.pdf"
id="pdfDocument"
width="100%"
height="100%" />
Then you call the .print()
method on the element in Javascript when the PDF is loaded:
然后.print()
在加载 PDF 时在 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();
}
}
You could place the embed in a hidden iframe and print it from there, giving you a seamless experience.
您可以将嵌入内容放置在隐藏的 iframe 中并从那里打印出来,从而为您提供无缝体验。
回答by Nicolas BADIA
Here is a function to print a PDF from an iframe.
这是一个从 iframe 打印 PDF 的函数。
You just need to pass the URL of the PDF to the function. It will create an iframe and trigger print once the PDF is load.
您只需要将 PDF 的 URL 传递给函数。加载 PDF 后,它将创建一个 iframe 并触发打印。
Note that the function doesn't destroy the iframe. Instead, it reuses it each time the function is call. It's hard to destroy the iframe because it is needed until the printing is done, and the print method doesn't has callback support (as far as I know).
请注意,该函数不会破坏 iframe。相反,它每次调用函数时都会重用它。很难销毁 iframe,因为在打印完成之前需要它,并且打印方法没有回调支持(据我所知)。
printPdf = function (url) {
var iframe = this._printIframe;
if (!this._printIframe) {
iframe = this._printIframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function() {
setTimeout(function() {
iframe.focus();
iframe.contentWindow.print();
}, 1);
};
}
iframe.src = url;
}
回答by user1892203
Download the Print.js from http://printjs.crabbly.com/
从http://printjs.crably.com/下载 Print.js
$http({
url: "",
method: "GET",
headers: {
"Content-type": "application/pdf"
},
responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
var pdfFile = new Blob([data], {
type: "application/pdf"
});
var pdfUrl = URL.createObjectURL(pdfFile);
//window.open(pdfUrl);
printJS(pdfUrl);
//var printwWindow = $window.open(pdfUrl);
//printwWindow.print();
}).error(function (data, status, headers, config) {
alert("Sorry, something went wrong")
});
回答by user2311177
https://github.com/mozilla/pdf.js/
https://github.com/mozilla/pdf.js/
for a live demo http://mozilla.github.io/pdf.js/
现场演示http://mozilla.github.io/pdf.js/
it's probably what you want, but I can't see the point of this since modern browsers include such functionality, also it will run terribly slow on low-powered devices like mobile devices that, by the way, have their own optimized plugins and apps.
这可能是你想要的,但我看不出这有什么意义,因为现代浏览器包括这样的功能,而且它在低功耗设备上运行速度也会非常慢,比如移动设备,顺便说一下,这些设备有自己优化的插件和应用程序.
回答by Adnan shah
I used this function to download pdf stream from server.
我使用此功能从服务器下载 pdf 流。
function printPdf(url) {
var iframe = document.createElement('iframe');
// iframe.id = 'pdfIframe'
iframe.className='pdfIframe'
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function () {
setTimeout(function () {
iframe.focus();
iframe.contentWindow.print();
URL.revokeObjectURL(url)
// document.body.removeChild(iframe)
}, 1);
};
iframe.src = url;
// URL.revokeObjectURL(url)
}
回答by Papi
Cross browser solution for printing pdf from base64 string:
从 base64 字符串打印 pdf 的跨浏览器解决方案:
- Chrome: print window is opened
- FF: new tab with pdf is opened
- IE11: open/save prompt is opened
- Chrome:打印窗口已打开
- FF:打开带有 pdf 的新标签
- IE11:打开/保存提示被打开
.
.
const blobPdfFromBase64String = base64String => {
const byteArray = Uint8Array.from(
atob(base64String)
.split('')
.map(char => char.charCodeAt(0))
);
return new Blob([byteArray], { type: 'application/pdf' });
};
const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // or however you want to check it
const printPDF = blob => {
try {
isIE11
? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
: printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
} catch (e) {
throw PDFError;
}
};
printPDF(blobPdfFromBase64String(base64String))
BONUS - Opening blob file in new tab for IE11
奖励 - 在 IE11 的新选项卡中打开 blob 文件
If you're able to do some preprocessing of the base64 string on the server you could expose it under some url and use the link in printJS
:)
如果您能够在服务器上对 base64 字符串进行一些预处理,则可以在某个 url 下公开它并使用printJS
:) 中的链接