简体   繁体   中英

JavaScript - opening new window in print mode after document is ready

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.

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)

onLoad is not the best solution. There is a good info about onLoad in: Javascript callback for knowing when an image is loaded

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM