I need a js code which will close window right after appearing of pop up print window. Here is my code:
P
In this way, the window will close after print, works perfect!
function printme() {
var newWindow = window.open();
newWindow.document.open("text/html");
newWindow.document.write('<html><head>blablabla.......');
newWindow.document.close();
newWindow.print();
newWindow.onfocus = function () {
newWindow.close(); // Close the window
}
};
And this was what worked for me (on Chrome):
var html = "<html>...</html>";
var win = window.open();
win.document.write(html);
win.document.close();
setTimeout(function () {
win.focus();
win.print();
win.close();
}, 100);
The crucial bit was doing the focus() and print() async. Without that I was seeing a blank page in the print preview.
This code worked for me:
print = function() {
var printContents = document.getElementById('div').innerHTML,
params = [
'height=' + screen.height,
'width=' + screen.width,
'fullscreen=yes'].join(','),
popup = window.open("", 'popUpWindow', params);
popup.document.write('<html><head><link rel="stylesheet" type="text/css" href="/style.css" /></head><body class="print" onload="window.print()" onmousemove="setTimeout(function () {window.close()},1000);" >'
+ printContents
+ '</body></html>');
popup.onfocus = function () {
setTimeout(function () {
popup.focus();
popup.document.close();
}, 200);
};
};
This snippet in JQuery
prints also dynamic images rendered inside the html.
<button id="printreceipt">
Print
</button>
<div id="receipt">
Colombo was great..
</div>
$(function(){
$('body').on('click','button#printreceipt',function(e){
e.preventDefault();
e.stopPropagation();
var printWindow = window.open('');
var divContents = $("#receipt").html() +
"<script>" +
"window.onload = function() {" +
" window.print();" +
"};" +
"setInterval(function() { { clearInterval();window.close(); } }, 300);" +
"<" + "/script>";
printWindow.document.write(divContents);
printWindow.document.close();
});
});
<a href="javascript:;" onclick="print()">Print</a>
function print()
{
win = window.open();
win.document.write('<html><head>blablabla.......');
var document_focus = false; // var we use to monitor document focused status.
// Now our event handlers.
$(document).ready(function() { win.window.print();document_focus = true; });
setInterval(function() { if (document_focus === true) { win.window.close(); } }, 300);
}
Thanks Stilltorik for link.