【问题标题】:Javascript Print Multiple Webpages iFrame Content (Print All Button)Javascript 打印多个网页 iFrame 内容(打印所有按钮)
【发布时间】:2015-04-03 11:53:08
【问题描述】:

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

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

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

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

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

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

现在,我正在寻找一个答案,以便通过 iFrame src 导航以一键打印内容。

【问题讨论】:

    标签: javascript loops iframe printing document


    【解决方案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>
    

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

    【讨论】:

    • 谢谢帕布。我花了一段时间才理解你提供的代码,因为我是一个新手。但是,我确实尝试了代码。它似乎多次弹出打印对话框。最后,我决定采用不同的方法让页面打印内容会更容易。我想让你知道我是多么感谢你的帮助。
    • @Sharma,您能告诉我们您使用的不同方法吗?我陷入了类似的情况,我似乎无法解决它。谢谢
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多