Pages

Thursday, December 24, 2009

MEDIA attribute of Link Tag - A solution to print Webpages

As commonly found in most of the web applications, I was ought to add a "Print" feature. This is where a problem started. When ever I attempt to print, I should hide unwanted sections like, Menus, Title Images, comment sections, calendars etc.

So I got into the tedious process of hiding all the unwanted portions and aligning the rest with the page, print them and get the application back to its normal GUI, which was not welcome. It was then I discovered this gorgeous MEDIA thing in link tags.

Now what It helps me to do is, the same tedious process, in a user friendly way.

I create a separate CSS which I want to apply when the page is about to be printed.
Let me call it as "Style2.css". My existing page uses a CSS named "Style1.css". In this case what I should do is add the following link tag to my HTML Head tag.

For IE6 and IE7:

<link rel="stylesheet" href="Style2.css" type="text/css" media="screen">
<link rel="stylesheet" href="Style1.css" type="text/css" media="print">


For IE8, Firefox, Opera and Safari:

<link rel="stylesheet" type="text/css" media="print" href="Style1.css" media="screen" href="Style2.css" />


Now have a button any where in your page and which says "window.print()"

I beauty is when you click that button, The Page on the browser does not change where as , the print outs that you receive will be of the page with styles governed by Style2.css

If I am not clear, please try this out.
1. Create a web page,
2. put some div tags with text contents,
3. apply styles using a style sheet , say Style1.css
4. create a new style sheet, say style2.css and hide a few div tags
5. Put the following in the head tag of your html page

For IE6 and IE7:

<link rel="stylesheet" href="Style2.css" type="text/css" media="screen">
<link rel="stylesheet" href="Style1.css" type="text/css" media="print">


For IE8, Firefox, Opera and Safari:

<link rel="stylesheet" type="text/css" media="print" href="Style1.css" media="screen" href="Style2.css" />


6. Add a button in your page with a label, say "Print" and in its on click event add the javascript code "window.print()"
7. Now print the page.
8. You will be able to see that the div tags that you have hidden using the style sheet "Style2.css" has not appeared on the print out where as the browser screen remains the same

No comments:

Post a Comment