Created
June 20, 2014 21:32
-
-
Save andrewthauer/a46c6ff51255227609e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create a jquery plugin that prints the given element. | |
jQuery.fn.print = function () { | |
// Ensure there is only a single element in the jquery collection | |
if (this.size() > 1) { | |
this.eq(0).print(); | |
return; | |
} | |
else if (!this.size()) { | |
return; | |
} | |
// Create a print frame and random name. | |
var frameName = ("printer-" + (new Date()).getTime()); | |
var jFrame = $("<iframe name='" + frameName + "'>"); | |
jFrame | |
.css("width", "1px") | |
.css("height", "1px") | |
.css("position", "absolute") | |
.css("left", "-9999px") | |
.appendTo($("body:first")); | |
// Get the frame | |
var frame = window.frames[frameName]; | |
// Write the HTML for the document. In this, we will write out the HTML of the current element. | |
var doc = frame.document; | |
doc.open(); | |
doc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); | |
doc.write("<html>"); | |
doc.write( | |
$("<head>") | |
.append("<title>" + document.Title + "</title>") | |
.append($("link").clone()) | |
.append($("style").clone()) | |
.html() | |
); | |
doc.write("<body></body>"); | |
doc.write("</html>"); | |
doc.close(); | |
// Append the body - doing this in doc.write causes errors in IE | |
jFrame.contents().find("body").append(this.clone()); | |
// Print the document. | |
frame.focus(); | |
frame.print(); | |
// Remove temp frame in about a minute | |
setTimeout(function () { | |
jFrame.remove(); | |
}, (60 * 1000)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment