I had problems with all of the above solutions in IE8, they found a decent workaround that was tested in IE 8 + 9, Chrome, Safari and Firefox. For my situation, I needed to print a report that was generated dynamically:
// create content of iframe var content = '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+ '<head><link href="/css/print.css" media="all" rel="stylesheet" type="text/css"></head>'+ '<body>(rest of body content)'+ '<script type="text/javascript">function printPage() { window.focus(); window.print();return; }</script>'+ '</body></html>';
Note the javascript printPage () method before the body close tag.
Then create an iframe and add it to the parent body so that its contents are accessible:
var newIframe = document.createElement('iframe'); newIframe.width = '0'; newIframe.height = '0'; newIframe.src = 'about:blank'; document.body.appendChild(newIframe);
Then set the contents:
newIframe.contentWindow.contents = content; newIframe.src = 'javascript:window["contents"]';
Here we set the dynamic content variable to an iframe window object, and then call it through the javascript: schema.
Finally, for printing; focus the iframe and call the javascript printPage () function on the iframe content:
newIframe.focus(); setTimeout(function() { newIframe.contentWindow.printPage(); }, 200); return;
SetTimeout is not necessary, however, if you download a large amount of content, I find that Chrome sometimes did not print without it, so this step is recommended. An alternative is wrap 'newIframe.contentWindow.printPage ();' in try catch and put the completed version of setTimeout in the catch block.
Hope this helps someone as I spent a lot of time finding a solution that worked well in multiple browsers. Thanks SpareCycles .
EDIT:
Instead of using the setTimeout function to call the printPage function, use the following:
newIframe.onload = function() { newIframe.contentWindow.printPage(); }