Freedom, Community & Sustainability

JS: Print page button

January 2, 2011 -- Webmaster
Last modified on November 2014
Duration: 5 minutes or less

-Make a button to print current page-

Printing web pages may seem counter-intuitive to some of us webmasters used to read everything on a screen but we shouldn't underestimate how big (and useful after all) is the demand. Users might want to print to keep a hard reference of the information or simply to read it later when in the subway. The reasons don't really matter and it's so simple to do that it's worth offering this possibility. Here is how:

The print button

Actually, you are not going to print the current page but you are going to redirect the user to a printer friendly page that will automatically require to print itself.

<form action="myprintablepage.html" target="_blank">
<input type=submit value="Print">

The whole secret lies on this second page (myprintablepage.html) that you are going to launch on a different browser window, print and then close, all automatically.

The printable page

The first step is to make this page printer friendly. The myprintablepage.html will contain only the essential information (no headers, footers or sidebars), no colors (only if absolutely essential), no animation or fancy interactive feature... well you get the idea, it should look pretty much like a page from a book. To make this easier you should attach a different CSS file to the original content, a CSS that is specific to all your printable pages as opposed to your usual, super-cool looking CSS file you use on your site.

The second step is rather simple and it makes all the magic of the print button happen. On the body tag of myprintablepage.html you should add this javascript instruction:

<body onload="window.print();window.close()">

This magical tag will first prompt the user with his usual printer options to configure, and then, upon print (or cancel) the page will close itself and the user will be back to step one (where the print button is) while his printer starts putting it on the paper.

This is it! The only thing you will really have to think about is to create a page that looks good on paper. Once you got all the styling rules right, just apply this same CSS to any other page you want to print. It's a good practice though not to encourage too much printing, as we all know our planet suffers from unconsidered consumption. That being said, sometimes a printed page can save all the electricity you would spend otherwise reading from a computer!

Add new comment