Javascript 如何在不打开弹出窗口的情况下打印网页?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2651559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print a web page without opening a popup window?
提问by Gaurav Aroraa
I want to print a web page using JavaScript. But I do not want to open the page as a popup windows. How can I print directly a web page like 'mypage.aspx' using JavaScript window.print method without opening it as a popup window?
我想使用 JavaScript 打印网页。但我不想将页面作为弹出窗口打开。如何使用 JavaScript window.print 方法直接打印像“mypage.aspx”这样的网页而不将其作为弹出窗口打开?
Also the condition is 'I don't want to use any ActiveX for this'
此外,条件是“我不想为此使用任何 ActiveX”
Here is what I want to try:
这是我想尝试的:
var printWindow, printData; printWindow = window.open("", "printVersion", "menubar,scrollbars,width=640,height=480,top=0,left=0");
printData=document.getElementById("lblReport").innerHTML; printWindow.document.write(printData);
printWindow.document.close();
printWindow.print();
回答by jerjer
The simpliest solution is to load the content of that mypage.aspx to an iframe then on iframes onload event call the window.print.
最简单的解决方案是将 mypage.aspx 的内容加载到 iframe,然后在 iframes onload 事件上调用 window.print。
<button onclick="printPage()">print</button>
<div id="printerDiv" style="display:none"></div>
<script>
function printPage()
{
var div = document.getElementById("printerDiv");
div.innerHTML = '<iframe src="mypage.aspx" onload="this.contentWindow.print();"></iframe>';
}
</script>
回答by Rosdi Kasim
<html>
<head>
<title>Print</title>
<link rel="stylesheet" type="text/css" media="all" href="all.css" />
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
</head>
<body>
<p>I get printed</p>
<form>
<input type="button" onclick="window.print()" value="Print" />
</form>
</body>
</html>
Make sure all.cssis on top and print.cssat the bottom, it should work.
确保all.css在顶部和print.css底部,它应该可以工作。
回答by binaryLV
Not sure if it works, but you may try to create invisible iframe, load page2.aspx in it and then print it.
不确定它是否有效,但您可以尝试创建 invisible iframe,在其中加载 page2.aspx 然后打印它。
回答by Oded
Um. Just use window.print();directly on the page. By itself it does not open a new window (apart from the print properties window to set printing options).
嗯。window.print();直接在页面上使用即可。它本身不会打开一个新窗口(除了用于设置打印选项的打印属性窗口)。
回答by matpol
You could just use a CSS print style sheet and avoid using javascript altogether -all the user has to do them is print the page. e.g.
您可以只使用 CSS 打印样式表并避免完全使用 javascript - 用户所需要做的就是打印页面。例如
<link rel="stylesheet" type="text/css" media="print" href="print.css" />

