【问题标题】:print iframe content is not printing everything打印 iframe 内容没有打印所有内容
【发布时间】:2020-07-16 19:06:54
【问题描述】:

我创建了一个 JavaScript 函数来打印 iFrame 的内容。

    <a href="#" onclick="printBGReport();" align="center">Print Report</a> <br/>
    <script>
        function printBGReport(){
            var content = document.getElementById("printBGReport").innerHTML;
            var mywindow = window.open('', 'Print', 'height=600,width=800');
            mywindow.document.write(content);
            mywindow.document.close();
            mywindow.focus()
            mywindow.print();
            mywindow.close();
            //return;
        }
    </script>
<div id="printBGReport">
    <iframe id="reportBGID" name="reportBGID" src="myiFrameURL" width="900" height="1000" align="center" target="_self" valign="top" scrolling="yes" frameborder="no">
</div>

但是,它并未打印所有内容。看起来它只是打印第一页。有谁知道为什么?

谢谢

【问题讨论】:

  • iframe 内容的结构是怎样的? “首页”是什么意思?
  • iframe 内容在我的
  • 它只是打印到 iframe 高度。 height="1000"

标签: javascript html


【解决方案1】:

假设 iframe 指向同一域中的页面(参见CORS restrictions),您可以调用iframe.contentWindow.print()

document.getElementById("reportBGID").contentWindow.print()

如果 iframe 指向另一个域(您可以控制),您可以使用 postMessage 触发页面上的函数以调用 window.print()


或者,您可以将 iframe 复制到新窗口中,然后打印:

function printIframe(iframe) {
  const tempWindow = window.open('', 'Print', 'height=600,width=800')

  const newIframe = document.createElement('iframe')
  newIframe.src = iframe.src

  newIframe.style = `border: 0; width: 100%; height: 100%;`
  tempWindow.document.body.style = `margin: 0;`

  tempWindow.document.body.appendChild(newIframe)

  newIframe.onload = () => {
    tempWindow.print()
    tempWindow.close()
  }
}
<button onclick="printIframe(document.getElementById('iframe'));">
    Print Iframe
    </button>

<iframe id="iframe" src="https://example.com"></iframe>

【讨论】:

  • 它不在同一个域中,我没有域的控制权
  • @CodeGuy 那么由于 CORS 限制是不可能的
  • 它只是打印到 iframe 高度。 height="1000"
  • @CodeGuy iframe 没有 innerHTML,因为它们是影子元素。获取 iframe 内容的唯一方法是使用contentWindow
  • 这就是我使用 div 的原因。然后,我将 iframe 放入 div 并打印 div。
猜你喜欢
  • 2011-01-14
  • 2015-04-03
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 2015-12-20
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多