【发布时间】:2013-07-11 14:25:43
【问题描述】:
对于当前的非 IE 浏览器(Chrome、Firefox、Opera、Safari),我想将 PDF 文档发送到打印机,并提供该 PDF 的 URL。
为避免弹出多余的窗口,我目前使用<iframe> 执行此操作,但我想在打印完成后关闭 iframe,否则某些浏览器会在尝试离开页面时弹出一个对话框。
这是我目前为止的想法(为了简单起见,使用 lodash 和 jQuery):
var _print_url, _remove_iframe, _set_print;
_print_url = function(src_url) {
$("<iframe src='" + src_url + "' type='application/pdf'>").css({
visibility: 'hidden',
position: 'fixed',
right: '0',
bottom: '0'
}).on('load', _set_print).appendTo(document.body);
};
_remove_iframe = function(iframe) {
return $(iframe).parent().find(iframe).detach();
};
_set_print = function() {
this.contentWindow.print();
/*
* Where we could do @contentWindow.close() with a window, we must remove the
* print iframe from the DOM. We have to engage in some async madness
* it seems, for no apparent reason other than this won't work
* synchronously (@cw.print above must be async, it seems) - even though
* window.close() appears to work synchronously.
*/
_.delay(_.partial(_remove_iframe, this), 100);
};
有时它似乎在Google Chrome中,打印对话框最终正确显示PDF,但是当一个选择打印机并确认打印的意图时,它将实际将框架的父页面的内容发送到打印机而不是PDF自己。
有一个链接suggestions on the Mozilla page,但该文档目前似乎已过时。我能找到的最好的例子是对发票的 Amazon Web Services 打印对话框进行逆向工程,但这会打开一个窗口。
我考虑过的另一种选择是Google Cloud Print,但显然这需要安装额外的软件或配置 Google 帐户,除非必要,否则我不希望将这些强加给用户。
是否有其他示例可以说明如何在给定 URL 的情况下打印 PDF,尤其是使用 Javascript 并且没有其他多余的额外浏览器插件或人工制品(例如弹出窗口)?
【问题讨论】:
-
这只是一个怀疑,但是如果你在调用
print()之前调用this.contentWindow.focus()会发生什么? -
@YatinSaraiya 它指的是 iframe。 jQuery 将
this绑定到定义了事件处理程序的元素。 (See here, last paragraph in the section.)
标签: javascript printing