1

I want to open a new window/tab, put some HTML in the document, then bring up the browser print dialog to print that new window. I am using the following to accomplish this:

var w = window.open();
w.document.write(html);
w.document.close();

Where html contains:

...<body onload="window.print()">...</body>...

This all works, the window pops up, and the print dialog is shown for the new page, however, for some reason the browser isn't waiting for all the images on the page to load before showing the print dialog. It's causing some images not to print.

There are many images, and they are dynamically generated on the server side (takes about 1 sec each to load). How do I force the browser to only print once all the images are loaded?

This happens in Chrome and Firefox that I've confirmed. I appreciate any help.

Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
Samuel
  • 16,923
  • 6
  • 62
  • 75

2 Answers2

1

Try changing it from the body.onload event to the window.onload event.

w.window.onload = window.print()

Or something like that.

Samuel Reid
  • 1,756
  • 12
  • 22
  • I did try putting `` on the page, and while it did print, I still had the same issue where images were missing. After some research it appears that ` – Samuel Jul 09 '13 at 01:53
1

Try putting your printer call in an onload event for the last image.

<img onload="window.print()" ... />

EDIT:

Full answer by OP as seen below:

I came up with the following script using @chockleyc's answer as inspiration. I couldn't just use the last image because they don't necessarily load in order. The following script will print the page after all images have loaded (uses jQuery):

var hasPrinted = false;
$(document).ready(function(){
  $('img').load(function(){
    var imgs = $('img');
    var loadedAll=true;
    for(var i=0;i<imgs.length;i++){
      loadedAll &= $(imgs[i])[0].complete;
    }
    if (loadedAll && !hasPrinted) {
      console.log('printing');
      hasPrinted = true;
      window.print();
    }
    else {
      console.log('not all images have loaded');
    }
  })
});
chockleyc
  • 581
  • 2
  • 5
  • I'll try this tomorrow morning. Thanks for your help! – Samuel Jul 09 '13 at 01:54
  • 1
    I used your answer as inspiration, and I came up with a working solution. I don't think setting it just in the last image would work, however, because images don't necessarily load in order. Thanks for that! – Samuel Jul 09 '13 at 12:00
  • I appreciate you accepting my answer but for the knowledge of others what was the solution you used? If you post it in the comments I will update my answer to include it in an edit so that others can see it. – chockleyc Jul 09 '13 at 12:20
  • It's in my answer. If you update your answer that would be great. Thank you – Samuel Jul 09 '13 at 13:50