我创建了一个 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>
Run Code Online (Sandbox Code Playgroud)
但是,它并没有打印所有内容。看起来只是打印第一页。有谁知道为什么?
谢谢
假设 iframe 指向同一域上的页面(请参阅CORS 限制),您可以调用iframe.contentWindow.print()
.
document.getElementById("reportBGID").contentWindow.print()
Run Code Online (Sandbox Code Playgroud)
如果 iframe 指向另一个域(您可以控制),您可以使用postMessage
触发页面上的函数来调用window.print()
.
或者,您可以将 iframe 复制到新窗口中,然后打印:
document.getElementById("reportBGID").contentWindow.print()
Run Code Online (Sandbox Code Playgroud)
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()
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5892 次 |
最近记录: |