79

This is my code

<script>
var body = "dddddd"    
var script = "<script>window.print();</scr'+'ipt>";

var newWin = $("#printf")[0].contentWindow.document; 
newWin.open();
newWin.close();

$("body",newWin).append(body+script);

</script>
<iframe id="printf"></iframe>

This works but it prints the parent page, how do I get it to print just the iframe?

Evert
  • 8,161
  • 1
  • 15
  • 17
user1083382
  • 799
  • 1
  • 6
  • 9

12 Answers12

140

I would not expect that to work

try instead

window.frames["printf"].focus();
window.frames["printf"].print();

and use

<iframe id="printf" name="printf"></iframe>

Alternatively try good old

var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();

if jQuery cannot hack it

Live Demo

animuson
  • 53,861
  • 28
  • 137
  • 147
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 5
    I was using jQuery and I found the same methods through the Dom object. i.e. `var iframe = $('#printf')[0]; iframe.contentWindow.focus(); iframe.contentWindow.print();` Does this work in IE 9 or lower? – gawpertron Oct 25 '13 at 13:38
  • 6
    As of 1/22/2014, this does not work in Chrome, whether you add contentWindow or call window.frames["printf"].print(). It prints the entire page, not just the frame. – Gullbyrd Jan 22 '14 at 16:44
  • 1
    BOTH my suggestions work for me http://plungjan.name/SO/testprintiframe.html on Chrome 32.0.1700.76 m on XP. – mplungjan Jan 23 '14 at 07:34
  • 2
    @Gullbyrd I had the same problem as you, and this code worked: `var PDF = document.getElementById('fileframe'); PDF.focus(); PDF.contentWindow.print();` From: http://www.sitepoint.com/load-pdf-iframe-call-print/ – degenerate Jul 02 '14 at 16:55
  • The Live Demo link worked for me on Google Chrome Version 34.0.1847.131. – taco Aug 07 '14 at 04:34
  • And for me on 36.0.1985.125 m Win7 – mplungjan Aug 07 '14 at 05:45
  • Unfortunately not working on Chrome in Android 6. Prints the whole page. – Jpsy Feb 24 '16 at 15:55
  • I know that initially this was for desktop browsers. Any alternative for Mobile? – Sposmen Apr 01 '16 at 12:44
  • 2
    this does not work when loading an iframe with pdf data like so `` it gives a CORS error even though the frame isn't even loading an external URL. Does anyone know how to get around this? – jtate Nov 07 '16 at 15:16
  • You could load a self printing PDF into a hidden frame instead. – mplungjan Nov 07 '16 at 15:17
  • @mplungjan self printing PDF? do you have a sample? – jtate Nov 07 '16 at 15:48
  • Not as a data source - but have a look here http://stackoverflow.com/questions/687675/can-a-pdf-files-print-dialog-be-opened-with-javascript – mplungjan Nov 07 '16 at 15:52
  • @mplungjan so I generated a pdf with the embedded javascript but it still doesn't work for me. It gives a CORS error when I do a `window.open()` on the pdf's data uri. It's so weird, because if I open the pdf in Chrome directly it triggers the print immediately. There seems to be something wrong with how Chrome see's the domain for a data uri window. – jtate Nov 07 '16 at 20:05
  • Sorry I do not have other suggestions – mplungjan Nov 07 '16 at 20:07
  • @mplungjan Does your 'live demo' link work for you in IE 11? I'm using version 11.0.9600.18697CO and [this is what I get when printing to PDF](http://i.imgur.com/PBaJDB0.png) – sab669 Jun 20 '17 at 15:00
  • I do get some result in IE11 and edge but there was some complaint from Win 10 while doing it – mplungjan Jun 20 '17 at 15:37
39
document.getElementById("printf").contentWindow.print();

Same origin policy applies.

James Heazlewood
  • 862
  • 9
  • 12
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • @HeemanshuBhalla Your iframe is not loaded into the page or you are using an incorrect ID on `document.getElementById`. Make sure you can obtain a valid reference to the iframe before trying to print it. – Dinei Apr 29 '20 at 14:41
14

Easy way (tested on ie7+, firefox, Chrome,safari ) would be this

//id is the  id of the iframe
function printFrame(id) {
            var frm = document.getElementById(id).contentWindow;
            frm.focus();// focus on contentWindow is needed on some ie versions
            frm.print();
            return false;
}
Kiarash
  • 1,701
  • 2
  • 16
  • 20
11

You can use this command:

document.getElementById('iframeid').contentWindow.print();

This command basically is the same as window.print(), but as the window we would like to print is in the iframe, we first need to obtain an instance of that window as a javascript object.

So, in reference to that iframe, we first obtain the iframe by using it's id, and then it's contentWindow returns a window(DOM) object. So, we are able to directly use the window.print() function on this object.

Perx
  • 123
  • 1
  • 6
  • Hi, Welcome to Stackoverflow.Please add some details on your answer or [take a look at here](http://stackoverflow.com/help/how-to-answer) . – Kiran RS Feb 20 '15 at 05:57
  • While this code block may answer the question, it would be a better answer if you could provide some explanation for why it does so. – DavidPostill Feb 20 '15 at 08:03
11

an alternate option, which may or may not be suitable, but cleaner if it is:

If you always want to just print the iframe from the page, you can have a separate "@media print{}" stylesheet that hides everything besides the iframe. Then you can just print the page normally.

Evert
  • 8,161
  • 1
  • 15
  • 17
7

I had issues with all of the above solutions in IE8, have found a decent workaround that is 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 printPage() javascript method before the body close tag.

Next create the iframe and append it to the parent body so its contentWindow is available:

var newIframe = document.createElement('iframe');
newIframe.width = '0';
newIframe.height = '0';
newIframe.src = 'about:blank';
document.body.appendChild(newIframe);

Next set the content:

newIframe.contentWindow.contents = content;
newIframe.src = 'javascript:window["contents"]';

Here we are setting the dynamic content variable to the iframe's window object then invoking it via the javascript: scheme.

Finally to print; focus the iframe and call the javascript printPage() function within the iframe content:

newIframe.focus();
setTimeout(function() {
  newIframe.contentWindow.printPage();
}, 200);
return;

The setTimeout is not necessarily needed, however if you're loading large amounts of content i found Chrome occasionally failed to print without it so this step is recommended. The alternative is to wrap 'newIframe.contentWindow.printPage();' in a try catch and place the setTimeout wrapped version in the catch block.

Hope this helps someone as i spent a lot of time finding a solution that worked well across multiple browsers. Thanks to SpareCycles.

EDIT:

Instead of using setTimeout to call the printPage function use the following:

newIframe.onload = function() {
    newIframe.contentWindow.printPage();
}
Jon TJ
  • 145
  • 1
  • 6
  • I really thought this would work. But it's not working in any browsers for me. :( – user158017 Mar 28 '14 at 19:20
  • it works fine for me, any way i can help? post/message me your code and will take a look, or take a look at an example of where im using it: [DIYInvestor](http://www.diyinvestor.co.uk/compare/) go through the comparison page 1, its being implemented successfully on the print icon above the results table. – Jon TJ Apr 04 '14 at 13:07
  • @user158017, please check my EDIT above - does this help? Am aware quite a long time has passed.. – Jon TJ Oct 09 '14 at 11:32
3

At this time, there is no need for the script tag inside the iframe. This works for me (tested in Chrome, Firefox, IE11 and node-webkit 0.12):

<script>
window.onload = function() {
    var body = 'dddddd';
    var newWin = document.getElementById('printf').contentWindow;
    newWin.document.write(body);
    newWin.document.close(); //important!
    newWin.focus(); //IE fix
    newWin.print();
}
</script>

<iframe id="printf"></iframe>

Thanks to all answers, save my day.

evalarezo
  • 1,134
  • 7
  • 13
1

If you are setting the contents of IFrame using javascript document.write() then you must close the document by newWin.document.close(); otherwise the following code will not work and print will print the contents of whole page instead of only the IFrame contents.

var frm = document.getElementById(id).contentWindow;
frm.focus();// focus on contentWindow is needed on some ie versions
frm.print();
Imran
  • 11
  • 1
1

I was stuck trying to implement this in typescript, all of the above would not work. I had to first cast the element in order for typescript to have access to the contentWindow.

let iframe = document.getElementById('frameId') as HTMLIFrameElement;
iframe.contentWindow.print();
ModestMonk
  • 402
  • 1
  • 7
  • 16
0

Use this code for IE9 and above:

window.frames["printf"].focus();
window.frames["printf"].print();

For IE8:

window.frames[0].focus();
window.frames[0].print();
Bhavana
  • 311
  • 2
  • 12
-1

I am wondering what's your purpose of doing the iframe print.

I met a similar problem a moment ago: use chrome's print preview to generate a PDF file of a iframe.

Finally I solved my problem with a trick:

$('#print').click(function() {
    $('#noniframe').hide(); // hide other elements
    window.print();         // now, only the iframe left
    $('#noniframe').show(); // show other elements again.
});
-1

document.getElementById('iframeid').contentWindow.print(); This is tested and working code and after many days speent. it will work with <iFrame tag only, avoid <embed, <object tag for pdf include.

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 15 '23 at 11:31