Reputation: 4004
I want to open a new window in print mode, after all images loaded(and the document is ready). Here is my code:
var win = window.open();
//css ltr
win.document.write('<style>body { direction: rtl; unicode-bidi: bidi-override; }</style>');
//insert img
win.document.write('<img src="assets/imgs/logo.png">' + '<br>');
//insert txt
win.document.write(pdf);
win.document.write('<br>');
win.document.write('<img src="assets/imgs/buttomLogo.png">' + '<br>');
win.print();
win.close();
I had tried to use onLoad()
but it print the document without the pictures:
win.onload = function () {
win.print();
win.close();
}
How can I open the document in print mode with all the images? Fiddle - printer.
Thanks.
Upvotes: 3
Views: 3180
Reputation: 5244
Way 1 : Try with below code. Added body tag before HTML start and added onload
function on it and defined window.print()
function in body onload
function.
var win = window.open();
//css ltr
win.document.write('<style>body { direction: rtl; unicode-bidi: bidi-override; }</style>');
//insert img
win.document.write('<body onload="javascript:PrintMe()"><img src="assets/imgs/logo.png">' + '<br>');
//insert txt
win.document.write(pdf);
win.document.write('<br>');
win.document.write('<img src="assets/imgs/buttomLogo.png">' + '<br><body>');
function PrintMe()
{
win.print();
win.close();
}
Way 2: Use image event listner image.attachEvent("onload"
var win = window.open();
//css ltr
win.document.write('<style>body { direction: rtl; unicode-bidi: bidi-override; }</style>');
//insert img
win.document.write('<body onload="javascript:PrintMe()"><img src="assets/imgs/logo.png">' + '<br>');
//insert txt
win.document.write(pdf);
win.document.write('<br>');
win.document.write('<img src="assets/imgs/buttomLogo.png">' + '<br><body>');
image.attachEvent("onload", function() {
win.print();
win.close();
});
Upvotes: 1
Reputation: 1206
onLoad is not the best solution. There is a good info about onLoad in: Javascript callback for knowing when an image is loaded
Upvotes: 1
Reputation: 104795
Pretty hacky - but that way I did this to wait for images to load was write in a script
tag to the new window, and add a listener for images:
mywindow.document.write('<script type="text/javascript">var img = document.getElementById("js-company-logo"); var src = img.src; img.addEventListener("load", function() { window.print(); window.close(); }); img.src = ""; img.src = src;</script>');
I also had to set the src
of the images each time (an issue with Chrome caching the images and not displaying on print previews after being used the first time)
Upvotes: 2