如何打印所有样式的iframe内容。
我只能得到文字:
app.ts
let bodyUrl="https://www.w3schools.com/tags/tag_iframe.asp"
print(){
let printContents, popupWin;
printContents = document.getElementById('iframe');
var innerDoc = printContents.contentDocument || printContents.contentWindow.document;
let printBody = innerDoc.body.innerText //got the text
//get whole iframe body with styles for print?
popupWin = window.open('', '_blank', 'top=0,left=0, width=900,height=700');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>My Print</title>
<style>
@media print{
.doNotPrint{
display:none;!important
}
}
</style>
</head>
<body onload="window.print();window.close()">
${printBody}
</body>
</html>`
);
popupWin.document.close();
}
HTML
<iframe id="iframe" class="iframe-content" [src]="bodyUrl"></iframe>
这是javascript解决方案:我发现:
window.frames["printf"].focus();
window.frames["printf"].print();
并使用
<iframe id="printf" name="printf"></iframe>
或者尝试好旧的
var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();
如何在TypeScript中打印iframe内容?
答案 0 :(得分:1)
问题最好总结如下。你似乎在帧,iframe和windows之间自由切换。您还将window.frames
称为地图,而不是数组。
选择一种方法并坚持下去......
document.getElementById('iframe');
iframe.contentWindow.document.write('<p>This is some content</p><script>window.print();</' + 'script>');
<iframe id="iframe" src="/blank.html"></iframe>
请记住,为了实现这一目标,值得在同一个域中使用src
来确保跨站点阻止不会阻止此操作。
答案 1 :(得分:0)
另一种解决方案可能会有所帮助:这将打印iframe和html的内容。
HTML
<iframe id="iframe" class="iframe-content" [src]="bodyUrl"></iframe>
<div id="print-section">
<h2>Print me too</h2>
</div>
TS。
print() {
let frame
let frameBody
frame = document.getElementById('iframe')
frameBody = frame.contentWindow.document.documentElement.outerHTML; //will get all html within the iframe
let printContents, popupWin;
let printHeader = document.getElementById('print-section').innerHTML; //will get html of the div by id
popupWin = window.open('', '_blank', 'top=0,left=0, width=900,height=700');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print Preview</title>
<style>
@media print{
.doNotPrint{
display:none;!important
}
.printVisible{
visability: content;
}
.print-header{
font-size: 14px;
font-weight: bold;
min-width: 100px;
}
.print-cont{
}
.print-header-wrapper{
padding-bottom: 50px
}
}
</style>
</head>
<body onload="window.print();window.close()">
${printHeader}
${frameBody}
</body>
</html>`
);
popupWin.document.close();
}