Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iframe.print vs. window.print on IE - small font in former

In our web application, we have print functionality for a couple of our pages and the approach we take is to put the current page's content in a globally available iframe's document and print the iframe (using Javascript). This works totally fine in Firefox but in IE it prints the iframe in a very small font, almost unreadable.

All the CSS's applied in both the browsers are same, I ensured that the HTML being printed is not overflowing in any way (making IE to fit the content or something)...and still IE print is very small. Interestingly, if I change the printing logic to write to a new window and then do window.print(), everything works fine in IE as well and the font is as big as required/specified by CSS.

Has anyone faced a similar problem with iframe.print() in IE?

Thanks for the help.

Nitin

like image 582
legendofawesomeness Avatar asked Nov 08 '11 19:11

legendofawesomeness


Video Answer


2 Answers

I found this thread after grappling with the same issue. It looks like this behavior persists even in IE11. The good news is I was able to find a solution without resorting to opening a new window and then calling window.print().

The trick is to use document.execCommand in IE (works all the way up to IE11), and fall back gracefully to iframe.print() in other browsers. The complete solution could look something like this (using jQuery to select an iframe, but that's entirely optional):

var target = $('iframe')[0];
try {
    target.contentWindow.document.execCommand('print', false, null);
} catch(e) {
    target.contentWindow.print();
}

This solution was inspired by a very old thread about IE7 from here: http://bytes.com/topic/misc/answers/629926-ie7-printing-iframe-solution. It's still relevant, though.

like image 165
Heston Liebowitz Avatar answered Dec 09 '22 16:12

Heston Liebowitz


Was having the small print on IE issue today, and to fix I simply adjusted my print function as so:

$(document).ready(function(){
$("#printFrame").click(function(){    
    if (document.queryCommandSupported('print')) 
    {
        $("#iframe").get(0).contentWindow.document.execCommand('print', false, null);
    } 
    else 
    {
        $("#iframe").get(0).contentWindow.focus();
        $("#iframe").get(0).contentWindow.print();
    }
  });
});

Now it seems to print out the same on IE, Chrome and Firefox. Posted here because this solution was hard for me to find, so hopefully this will help someone.

like image 33
Connor Avatar answered Dec 09 '22 17:12

Connor