打印iframe内容不能打印所有内容

时间:2018-12-18 17:06:19

标签: javascript html

我创建了一个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>

但是,它不能打印所有内容。看起来只是打印第一页。有人知道为什么吗?

谢谢

1 个答案:

答案 0 :(得分: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>

相关问题