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

Javascript Print Multiple Webpages iFrame Content (Print All Button)

本文关键字:打印 全部 内容 按钮 iFrame 网页 Javascript      更新时间:2023-09-26

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

每当单击时,"全部打印"按钮都会遍历iFrame的不同src并打印内容。

请注意,iFrame 当前设置在主网页上。 有导航按钮可以更改iFrame的内容源。 此主网页的设置类似于使用导航按钮浏览幻灯片内容。 导航按钮实际上是导航到不同的网页。

因此,我猜测需要将内容附加到文档或排列,以便可以使用"全部打印"按钮一次打印所有内容。

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

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

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

在你的脚本中试试这个

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>

在这里动态放置您的页面并打印。 使用您的逻辑自动或单击或其他方式进行打印

我想

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

目的是通过使用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()"
 />