我在 IE8 中遇到了上述所有解决方案的问题,找到了一个在 IE 8+9、Chrome、Safari 和 Firefox 中测试的不错的解决方法。对于我的情况,我需要打印一份动态生成的报告:
// create content of iframe
var content = '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+
'<head><link href="/css/print.css" media="all" rel="stylesheet" type="text/css"></head>'+
'<body>(rest of body content)'+
'<script type="text/javascript">function printPage() { window.focus(); window.print();return; }</script>'+
'</body></html>';
注意正文关闭标记之前的 printPage() javascript 方法。
接下来创建 iframe 并将其附加到父正文,以便其 contentWindow 可用:
var newIframe = document.createElement('iframe');
newIframe.width = '0';
newIframe.height = '0';
newIframe.src = 'about:blank';
document.body.appendChild(newIframe);
接下来设置内容:
newIframe.contentWindow.contents = content;
newIframe.src = 'javascript:window["contents"]';
这里我们将动态内容变量设置为 iframe 的窗口对象,然后通过 javascript: 方案调用它。
终于打印出来了;聚焦 iframe 并在 iframe 内容中调用 javascript printPage() 函数:
newIframe.focus();
setTimeout(function() {
newIframe.contentWindow.printPage();
}, 200);
return;
不一定需要 setTimeout,但是如果您要加载大量内容,我发现 Chrome 偶尔会在没有它的情况下无法打印,因此建议执行此步骤。另一种方法是包装 'newIframe.contentWindow.printPage();'在 try catch 中,将 setTimeout 包装的版本放在 catch 块中。
希望这对某人有所帮助,因为我花了很多时间寻找在多个浏览器中运行良好的解决方案。感谢SpareCycles。
编辑:
不要使用 setTimeout 来调用 printPage 函数,而是使用以下代码:
newIframe.onload = function() {
newIframe.contentWindow.printPage();
}