I\'m trying to print a page using this code
This worked for me (as well as implementing Anand's observed IE 10+ requirements):
function Popup() {
var _window = window.open('');
_window.document.write(data);
// required for IE >= 10
_window.document.close();
_window.focus();
_window.document.body.onload = function() {
// continue to print
_window.print();
_window.close();
};
return true;
}
Instead of waiting for the window to load and attempting to print it prematurely, this just waits for the entire document.body
to load.
You need to put delay before print. There is a native defect in chrome.
Code would as under :-
function PrintDiv(data) {
var mywindow = window.open();
var is_chrome = Boolean(mywindow.chrome);
mywindow.document.write(data);
if (is_chrome) {
setTimeout(function() { // wait until all resources loaded
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print(); // change window to winPrint
mywindow.close(); // change window to winPrint
}, 250);
} else {
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();
}
return true;
}
I moved the window.print() command on the pop up window it self so it can load the jquery function first before printing.
This is the line that I added.
mywindow.document.write('<script type="text/javascript">window.print();<'+'/script>');
This is the whole code:
<html>
<head>
<script type="text/javascript">
function Popup()
{
var mywindow = window.open('', 'Ticket info', 'height=400,width=600');
mywindow.document.write('<html><head><title>my div</title>');
mywindow.document.write('<style type="text/css"> *{margin: 0; padding: 0;} body{padding: 3px; padding-left:20px;font:6px bold Arial;}</style>');
mywindow.document.write('<script src="http://code.jquery.com/jquery-latest.min.js"><'+'/script>');
mywindow.document.write('<script src="jquery-barcode.min.js"><'+'/script>');
mywindow.document.write('</head><body>');
mywindow.document.write('<div id="demo"></div>');
mywindow.document.write('<script type="text/javascript">$("#demo").barcode("1234567890128", "code39");<'+'/script>');
mywindow.document.write('<script type="text/javascript">window.print();<'+'/script>');
mywindow.document.write('</body></html>');
return true;
}
</script>
</head>
<body>
<input type="button" value="Print Div" onclick="Popup();" />
</body>
</html>
actually you can create an extension css and place all your css in there...
Default
mywindow.document.write('<link rel="stylesheet" type="text/css" href="/css/default.css"/>');
Then just replace it like this
mywindow.document.write('<link rel="stylesheet" type="text/css" href="/css/default.css" media="print"/>');
just add media='print' to recognize it..
Hope it will help...