简体   繁体   English

Javascript仅打印iframe内容

[英]Javascript Print iframe contents only

This is my code 这是我的代码

<script>
var body = "dddddd"    
var script = "<script>window.print();</scr'+'ipt>";

var newWin = $("#printf")[0].contentWindow.document; 
newWin.open();
newWin.close();

$("body",newWin).append(body+script);

</script>
<iframe id="printf"></iframe>

This works but it prints the parent page, how do I get it to print just the iframe? 这可以,但它打印父页面,我如何让它只打印iframe?

I would not expect that to work 我不希望这样做

try instead 试着改为

window.frames["printf"].focus();
window.frames["printf"].print();

and use 并使用

<iframe id="printf" name="printf"></iframe>

Alternatively try good old 或者尝试好老

var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();

if jQuery cannot hack it 如果jQuery不能破解它

Live Demo 现场演示

document.getElementById("printf").contentWindow.print();

同源政策适用。

Easy way (tested on ie7+, firefox, Chrome,safari ) would be this 简单的方法(在ie7 +,firefox,Chrome,safari上测试)就是这样

//id is the  id of the iframe
function printFrame(id) {
            var frm = document.getElementById(id).contentWindow;
            frm.focus();// focus on contentWindow is needed on some ie versions
            frm.print();
            return false;
}

an alternate option, which may or may not be suitable, but cleaner if it is: 替代选项,可能适用也可能不适合,但如果是:

If you always want to just print the iframe from the page, you can have a separate "@media print{}" stylesheet that hides everything besides the iframe. 如果您始终只想从页面打印iframe,则可以使用单独的“@media print {}”样式表来隐藏除iframe之外的所有内容。 Then you can just print the page normally. 然后你可以正常打印页面。

You can use this command: 您可以使用此命令:

document.getElementById('iframeid').contentWindow.print();

This command basically is the same as window.print(), but as the window we would like to print is in the iframe, we first need to obtain an instance of that window as a javascript object. 这个命令基本上与window.print()相同,但是我们想要打印的窗口在iframe中,我们首先需要获取该窗口的实例作为javascript对象。

So, in reference to that iframe, we first obtain the iframe by using it's id, and then it's contentWindow returns a window(DOM) object. 因此,在参考iframe时,我们首先使用它的id获取iframe,然后它的contentWindow返回一个窗口(DOM)对象。 So, we are able to directly use the window.print() function on this object. 因此,我们可以直接在此对象上使用window.print()函数。

I had issues with all of the above solutions in IE8, have found a decent workaround that is tested in IE 8+9, Chrome, Safari and Firefox. 我在IE8中遇到了上述所有解决方案的问题,找到了一个在IE 8 + 9,Chrome,Safari和Firefox中测试过的体面解决方案。 For my situation i needed to print a report that was generated dynamically: 对于我的情况,我需要打印一个动态生成的报告:

// 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>';

Note the printPage() javascript method before the body close tag. 请注意body关闭标记之前的printPage()javascript方法。

Next create the iframe and append it to the parent body so its contentWindow is available: 接下来创建iframe并将其附加到父主体,以使其contentWindow可用:

var newIframe = document.createElement('iframe');
newIframe.width = '0';
newIframe.height = '0';
newIframe.src = 'about:blank';
document.body.appendChild(newIframe);

Next set the content: 接下来设置内容:

newIframe.contentWindow.contents = content;
newIframe.src = 'javascript:window["contents"]';

Here we are setting the dynamic content variable to the iframe's window object then invoking it via the javascript: scheme. 在这里,我们将动态内容变量设置为iframe的窗口对象,然后通过javascript:scheme调用它。

Finally to print; 最后打印; focus the iframe and call the javascript printPage() function within the iframe content: 关注iframe并在iframe内容中调用javascript printPage()函数:

newIframe.focus();
setTimeout(function() {
  newIframe.contentWindow.printPage();
}, 200);
return;

The setTimeout is not necessarily needed, however if you're loading large amounts of content i found Chrome occasionally failed to print without it so this step is recommended. 不一定需要setTimeout,但是如果您正在加载大量内容,我发现Chrome偶尔会在没有它的情况下打印,因此建议执行此步骤。 The alternative is to wrap 'newIframe.contentWindow.printPage();' 另一种方法是包装'newIframe.contentWindow.printPage();' in a try catch and place the setTimeout wrapped version in the catch block. 在try catch中将setTimeout包装的版本放在catch块中。

Hope this helps someone as i spent a lot of time finding a solution that worked well across multiple browsers. 希望这有助于某人,因为我花了很多时间找到一个在多个浏览器中运行良好的解决方案。 Thanks to SpareCycles . 感谢SpareCycles

EDIT: 编辑:

Instead of using setTimeout to call the printPage function use the following: 而不是使用setTimeout来调用printPage函数使用以下内容:

newIframe.onload = function() {
    newIframe.contentWindow.printPage();
}

At this time, there is no need for the script tag inside the iframe. 目前,iframe中不需要脚本标记。 This works for me (tested in Chrome, Firefox, IE11 and node-webkit 0.12): 这对我有用(在Chrome,Firefox,IE11和node-webkit 0.12中测试):

<script>
window.onload = function() {
    var body = 'dddddd';
    var newWin = document.getElementById('printf').contentWindow;
    newWin.document.write(body);
    newWin.document.close(); //important!
    newWin.focus(); //IE fix
    newWin.print();
}
</script>

<iframe id="printf"></iframe>

Thanks to all answers, save my day. 感谢所有答案,保存我的一天。

If you are setting the contents of IFrame using javascript document.write() then you must close the document by newWin.document.close(); 如果使用javascript document.write()设置IFrame的内容,则必须通过newWin.document.close();关闭文档newWin.document.close(); otherwise the following code will not work and print will print the contents of whole page instead of only the IFrame contents. 否则以下代码将无效,打印将打印整页内容而不是仅打印IFrame内容。

var frm = document.getElementById(id).contentWindow;
frm.focus();// focus on contentWindow is needed on some ie versions
frm.print();

Use this code for IE9 and above: 将此代码用于IE9及更高版本:

window.frames["printf"].focus();
window.frames["printf"].print();

For IE8: 对于IE8:

window.frames[0].focus();
window.frames[0].print();

I was stuck trying to implement this in typescript, all of the above would not work. 我被困在尝试在打字稿中实现这一点,以上所有都无法正常工作。 I had to first cast the element in order for typescript to have access to the contentWindow. 我必须首先强制转换元素,以便typescript可以访问contentWindow。

let iframe = document.getElementById('frameId') as HTMLIFrameElement;
iframe.contentWindow.print();

I am wondering what's your purpose of doing the iframe print. 我想知道你做iframe打印的目的是什么。

I met a similar problem a moment ago: use chrome's print preview to generate a PDF file of a iframe. 我刚才遇到了类似的问题:使用chrome的打印预览生成iframe的PDF文件。

Finally I solved my problem with a trick: 最后我用一招来解决了我的问题:

 $('#print').click(function() { $('#noniframe').hide(); // hide other elements window.print(); // now, only the iframe left $('#noniframe').show(); // show other elements again. }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM