Javascript打印多个网页iFrame内容(打印全部按钮)

时间:2015-02-04 03:58:51

标签: javascript loops iframe printing document

使用JavaScript,如何创建全部打印按钮?

每次点击时,“全部打印”按钮将遍历iFrame的不同src并打印内容。

作为备注,iFrame目前在主网页上设置。有一些导航按钮可以更改iFrame的内容src。此主网页设置为类似于使用导航按钮浏览幻灯片内容。导航按钮实际上导航到不同的网页。

因此,我猜测内容需要附加到文档或阵列中,以便可以使用“全部打印”按钮一次打印内容。

我使用以下代码成功打印了“当前幻灯片”(或iFrame内容):

function PrintCurrentSlide()
{
    var el = document.getElementById('ifMain');
    el.contentWindow.focus();
    el.contentWindow.print();
    return;
}

现在,我正在寻找一个答案来浏览iFrame src,只需点击一下即可打印内容。

2 个答案:

答案 0 :(得分:1)

在您的脚本中尝试此操作

window.onload=function() {
  window.frames["printf"].focus();
  window.frames["printf"].print();
}
function print() {
var newWin = window.frames['printf'];
newWin.document.write('<body onload=window.print()>This is a new page I inserted</body>');
newWin.document.close();
}
function change(){
var url="http://www.apple.com/";
    var $iframe = $('#ifrm');
    if ( $iframe.length ) {
        $iframe.attr('src',url);   
        return false;
    }
    return true;
}

和HTML

<input type="button" onclick="print()" value="Test print"/>
<button onclick="change()">next</button>
<iframe id="printf" name="printf" src="dfgdf.html"></iframe>

这里动态显示您的页面并打印。使用您的逻辑自动或单击或任何

打印

答案 1 :(得分:0)

我想出了一种解决方法。 这样,您只会得到一个打印对话框。

目标是通过使用javascript操纵DOM,将所有iframe的内容放入父窗口。 这是代码:

<script>

 pages =[] // initiate an empty list here

function printPage() {

var frames = document.getElementsByTagName('iframe');
// get all the iframes and loop over them
// then push their innerHTML into the list
for (var i = 0; i < frames.length; i++){ 
   pages.push(frames[i].contentWindow.document.body.innerHTML); 
;
}
if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated iframes innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
} 
else {
// do nothing
}


}

使用此解决方案,您甚至可以避免iframe超过一页时被切断的问题。

请记住,在您的父页面HTML中,您将具有下面的代码来调用printPage函数。

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />
相关问题