Saturday, January 10, 2009

Print Buttons Anywhere

On item web developers often have to deal with is printing of web information for meetings. You have information on the web page that looks great but is difficult to print without having a lot of extra information on the page.

Often, this problem is solved by creating a specific HTML page that then is handled by the server which in turn regenerates the information in a limited view and is placed in a popup window. Which is not a bad solution but it does take some time to create that. If you're working in a framework this might be a lot of effort for you.

Here is a solution with jQuery that allows you to basically pick information off the page, stick it into a new document and then allow the user to print it. You'll love the elgance of this small piece of code.

First, lets start with the HTML. Simply include a DIV around any elements you want to pick off the page. Then, somewhere in there include a button, link, etc. which fires off the javascript to create the printable window.

Once you have the content on your site marked up (which you probably had done already) include this tasty nugget on your webpage.

Let me explain what we do here. We use jquery to pick off the webContent HTML. $("#webContent").html() we stuff that into msgHTML. We then use windowHTML to build up the actual HTML page that we will place into the new window.

Note that the windoHTML code could have included the $("#webContent").html() call, but I listed them separately to better illustrate what exactly we are doing here.

After we build the page, we open the web browser window with the call.

Last, we call the print dialog. Now you're probably wondering why I placed that in a settimeout. Well I found on a few browsers (namely firefox 2) that if the page hasnt rendered that the print button can create a blank page. This timeout allows the user to see the page, then a couple of seconds later the print dialog shows.

Alternatively (but not shown in this example) you could add jquery to the printable window then call the window.print() from within the actual page when the document is ready.

You get the idea though, this allows you to quickly be able to print any region of a website without all the extras and without having to create new pages on the server.

No comments: