如何使用 JavaScript 打开带有打印对话框的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5674440/
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
How to open a file with print dialogue box using JavaScript
提问by Coder
I want to open one word document using JavaScript as well as open print dialogue box for that opened document window.
我想使用 JavaScript 打开一个 word 文档,并为该打开的文档窗口打开打印对话框。
Here is my code.
这是我的代码。
window.open('http://www.tizaq.com');
window.print();
It works, but the print dialogue gets opened for the current window, not the newly opened window. How do I do it?
它有效,但打印对话框为当前窗口打开,而不是新打开的窗口。我该怎么做?
回答by T.J. Crowder
Call print
on the new window rather than the old:
调用print
新窗口而不是旧窗口:
var wnd = window.open('http://stackoverflow.com');
wnd.print();
I don't like your odds, though, of it not falling afoul of browser security. :-) The "external" window object may well not support print
(window
objects come in two types, the "external" type that other windows have access to, and the "internal" type that references itself, which has more permissions, etc.) At the least, you'll probably have to wait for the load event, but I best in general it's going to be tricky.
不过,我不喜欢您认为它不会违反浏览器安全性的可能性。:-) “外部”窗口对象可能不支持print
(window
对象有两种类型,其他窗口可以访问的“外部”类型,以及引用自身的“内部”类型,具有更多权限等)至少,您可能必须等待加载事件,但我最好总的来说它会很棘手。
It seems to workfor documents with the same origin, so the Same Origin Policyis a factor. That example crashes in IE6 (literally crashes the browser), but works for me in IE7 on Windows, and Chrome and Firefox 3.6 on Linux (and not in Opera 11 on Linux). Probably wouldn't hurt to put a delay / yield in there, e.g.:
它似乎适用于具有相同来源的文档,因此同源策略是一个因素。该示例在 IE6 中崩溃(字面上使浏览器崩溃),但在 Windows 上的 IE7 和 Linux 上的 Chrome 和 Firefox 3.6(而不是 Linux 上的 Opera 11)中对我有用。在那里放置延迟/产量可能不会有什么坏处,例如:
var wnd = window.open(your_path_here);
setTimeout(function() {
wnd.print();
}, 0);
You said "word document" in your question, but your example looks like a website. I have no idea whether this would work if you were opening a Microsoft Word document by loading it into a browser window.
您在问题中说的是“word 文档”,但您的示例看起来像一个网站。如果您通过将 Microsoft Word 文档加载到浏览器窗口中来打开它,我不知道这是否可行。
回答by Anand Thangappan
Well, Better way
好吧,更好的方法
var my_window = window.open("", "mywindow1", "status=1,width=350,height=150");
my_window.document.write("<scr" + "ipt>window.location.href='http://stackoverflow.com';window.print();</scr" + "ipt>");
try Like this or better to make another page using iframe for print
尝试像这样或更好地使用 iframe 制作另一个页面进行打印