JQuery Print: How to Do More with Less Code!

jquery printJQuery lets you do a lot with very little code. JQuery is a JavaScript library that makes it much easier for the browser (and by extension you) to traverse documents, handle animations and respond to user generated events.  It is fast and feature rich. It is compatible with all the current popular web browsers.

In this article, we’re going to give you an overview of some of the jQuery print plugins you can use to print a webpage.

If you’re thinking about learning jQuery, you should have prior knowledge of HTML, CSS and JavaScript, as websites today are written with a combination of a couple (or all three) of these languages.  If you’re unfamiliar with any of these languages, you can hop over to our crash course on HTML and CSS. Once you’re ready to jump into jQuery, you can take this beginners jQuery course.

JQuery Print

You don’t need to write code in jQuery to print a single webpage, as it is much simpler to use the JavaScript window.print () method for it. If you’re unfamiliar with this method, the syntax for it is:

window.print();

Usually, the method is linked to a clickable button. When a user clicks on this button, the webpage gets printed. Here is some sample JavaScript code that you can use to create a print button on your webpage:

<!DOCTYPE html>
<html>
<body>
<p>Here's how you print the current page.</p>
<button onclick="Function()">Print</button>
<script>
function Function()
{
window.print();
}
</script>
</body>
</html>

If you’re familiar with HTML, the code should be familiar to you (if not, you may want to first learn some easy HTML with this course). All we’ve done is written a function called Function() and linked it to our button. When the user clicks on the button, the window.print() method, which is written inside the function, gets called and the current webpage gets printed. Simple, isn’t it?

JQuery Print Plugins

So why do you need to use jQuery to print webpages? jQuery provides several other print features that JavaScript cannot provide. Some jQuery print plugins will let you maintain the original css styles of the webpage, for example. Some users prefer to browse with JavaScript disabled. In such cases, jQuery plugins can be used to give the user an option to print the webpage without the user having to enable JavaScript.

Why use jQuery plugins instead of writing the code yourself? Because plugins can save you a lot of time and effort, of course! It’s not easy to create jQuey code to print a page (as simple as it sounds). If you want to write the code yourself, we recommend that you sign up for our ‘mastering’ jQuery course. In it, we cover basic as well as advanced techniques. You can also study the plugin coding and attempt to write code to print a page yourself.

Print Part of a Page with JQuery

You can print a part of a webpage with jQuery too. This plugin, created by Ben Nadel, lets you print a part of a webpage by creating an iframe, copying HTML to the body and then printing it. You can download the source code here: http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm

We’ll give you a brief explanation of the jQuery part of the source code. The print() plugin is used to actually carry out the print function:

// Create a jquery plugin that prints the given element.
jQuery.fn.print = function(){
// NOTE: We are trimming the jQuery collection down to the
// first element in the collection.
if (this.size() > 1){
this.eq( 0 ).print();
return;
} else if (!this.size()){
return;
}
// ASSERT: At this point, we know that the current jQuery
// collection (as defined by THIS), contains only one
// printable element.
// Create a random name for the print frame.
var strFrameName = ("printer-" + (new Date()).getTime());
// Create an iFrame with the new name.
var jFrame = $( "<iframe name='" + strFrameName + "'>" );
// Hide the frame (sort of) and attach to the body.
jFrame
.css( "width", "1px" )
.css( "height", "1px" )
.css( "position", "absolute" )
.css( "left", "-9999px" )
.appendTo( $( "body:first" ) )
;
// Get a FRAMES reference to the new frame.
var objFrame = window.frames[ strFrameName ];
// Get a reference to the DOM in the new frame.
var objDoc = objFrame.document;
// Grab all the style tags and copy to the new
// document so that we capture look and feel of
// the current document.
// Create a temp document DIV to hold the style tags.
// This is the only way I could find to get the style
// tags into IE.
var jStyleDiv = $( "<div>" ).append(
$( "style" ).clone()
);
// Write the HTML for the document. In this, we will
// write out the HTML of the current element.
objDoc.open();
objDoc.write( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/x
tml1-transitional.dtd\">" );
objDoc.write( "<html>" );
objDoc.write( "<body>" );
objDoc.write( "<head>" );
objDoc.write( "<title>" );
objDoc.write( document.title );
objDoc.write( "</title>" );
objDoc.write( jStyleDiv.html() );
objDoc.write( "</head>" );
objDoc.write( this.html() );
objDoc.write( "</body>" );
objDoc.write( "</html>" );
objDoc.close();
// Print the document.
objFrame.focus();
objFrame.print();
// Have the frame remove itself in about a minute so that
// we don't build up too many of these frames.
setTimeout(
function(){
jFrame.remove();
},
(60 * 1000)
);}

The most important part of the code here is the objFrame.focus() and objFrame.print(). The focus () method is an HTML method that lets you focus on an element. In this case, the element you’re focusing on is the iframe. Once the iframe has been focused, it is printed. The other part of the code deals with creating the iframe (var jframe) and writing the content that is to be printed into its body. The frames get removed automatically (to prevent a buildup, even if it’s in the background).

JQuery printPage Plugin

The jQuery printPage Plugin lets you print a page on your website without navigating to a new window (you don’t have to exit from the webpage you are browsing). Instead, it opens an iframe and gives you the option of printing the contents of the webpage. This plugin works with browsers that have jQuery disabled.  You can download the plugin here: https://github.com/posabsolute/jQuery-printPage-plugin

If you want to learn how to write your own plugins, you can sign up for our JQuery training. We’ll teach you all the tricks you need to know to work effectively with jQuery!