[javascript] Javascript Print iframe contents only

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?

This question is related to javascript jquery printing

The answer is


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.


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

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.


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

document.getElementById("printf").contentWindow.print();

Same origin policy applies.


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:

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


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

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

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.


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application