我想要构建的是,通过单击按钮,我想触发 PDF 文件的打印,但不打开它。
+-----------+
| Print PDF |
+-----------+
^ Click *---------> printPdf(pdfUrl)
我第一次尝试的方法是使用 iframe:
var $iframe = null;
// This is supposed to fix the onload bug on IE, but it's not fired
window.printIframeOnLoad = function() {
if (!$iframe.attr("src")) { return; }
var PDF = $iframe.get(0);
PDF.focus();
try {
// This doesn't work on IE anyways
PDF.contentWindow.print();
// I think on IE we can do something like this:
// PDF.document.execCommand("print", false, null);
} catch (e) {
// If we can't print it, we just open it in the current window
window.location = url;
}
};
function printPdf(url) {
if ($iframe) {
$iframe.remove();
}
$iframe = $('<iframe>', {
class: "hide",
id: "idPdf",
// Supposed to be a fix for IE
onload: "window.printIframeOnLoad()",
src: url
});
$("body").prepend($iframe);
}
这适用于 Safari(桌面和 iOS)和 Chrome(我们可以将其推广到 webkit 吗?)。
在火狐浏览器上,PDF.contentWindow.print()
以一个结尾permission denied
错误(即使pdf是从同一个域加载的)。
在 IE (11) 上,onload
处理程序只是不工作。
现在,我的问题是:是否有另一种更好的方法来打印 pdf 而无需向用户直观地打开它?
跨浏览器的事情在这里至关重要。我们应该支持尽可能多的浏览器。
实现这一目标的最佳方法是什么?我的开始是好的吗?如何完成呢?
We are now in 2016 and I feel like this is still a pain to implement across the browsers.