Skip to content

Instantly share code, notes, and snippets.

@provideal
Created February 10, 2010 08:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save provideal/300155 to your computer and use it in GitHub Desktop.
Save provideal/300155 to your computer and use it in GitHub Desktop.
Printing an iFrame with jQuery
(function($) {
$(function() {
$(".print").live('click', function(e) {
e.preventDefault();
// remove old printframe
$("#printframe").remove();
// create new printframe
var iFrame = $('<iframe></iframe>');
iFrame
.attr("id", "printframe")
.attr("name", "printframe")
.attr("src", "about:blank")
.css("width", "0")
.css("height", "0")
.css("position", "absolute")
.css("left", "-9999px")
.appendTo($("body:first"));
// load printframe
var url = $(this).attr("href");
if (iFrame != null && url != null) {
iFrame.attr('src', url);
iFrame.load(function() {
// nasty hack to be able to print the frame
var tempFrame = $('#printframe')[0];
var tempFrameWindow = tempFrame.contentWindow? tempFrame.contentWindow : tempFrame.contentDocument.defaultView;
tempFrameWindow.focus();
tempFrameWindow.print();
});
}
});
});
})(jQuery);
@stickhandle
Copy link

thanks for this ... after much searching and testing, i'm still hunting for a solution like this. Tell me -- did you test this cross browser?

@adarinnovation
Copy link

that's not work when the iframe scr is adress of .pdf file ???

@adarinnovation
Copy link

note have to change:
$("#printframe").remove();
by
if($("#printframe"))
$("#printframe").remove();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment