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?
Also the condition is ‘I don’t want to use any ActiveX for this’
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();
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The simpliest solution is to load the content of that mypage.aspx to an iframe then on iframes onload event call the 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>
Method 2
<html>
<head>
<title>Print</title>
<link rel="stylesheet" type="text/css" media="all" href="all.css" rel="nofollow noreferrer noopener" />
<link rel="stylesheet" type="text/css" media="print" href="print.css" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" />
</head>
<body>
<p>I get printed</p>
<form>
<input type="button" onclick="window.print()" value="Print" />
</form>
</body>
</html>
Make sure all.css is on top and print.css at the bottom, it should work.
Method 3
Not sure if it works, but you may try to create invisible iframe, load page2.aspx in it and then print it.
Method 4
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).
Method 5
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.
<link rel="stylesheet" type="text/css" media="print" href="print.css" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" />
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0