Tuesday, June 17, 2008

Printing a Web Page

I found a useful article to print a web page. The fastest and simplest solution is using javascript window.print()

<input type="button" value="Print" onclick="window.print();">

If you click this button , it will show this print dialog

printdialog

This example will print the entire web page,including the print button and anything else. To get better result, we can make two versions of web page, one for showing on screen and the other one for printing

On Screen 1
===========
<input type="button" value="Print" onclick="window.open("Print.aspx");">

On Screen 2 (Print.aspx)
======================
<script language="javascript"> window.print(); </script>

For screen version it is best to use pixels to define size of fonts, tables, images etc., as you probably already do. But, for print version use points instead of pixels. Example:

body {   font: 12pt; }

Actually, we don't have to make separate page to prepare printing version. There is a way use only 1 page, but we can differentiate show-on-screen version and printing version by using CSS like this example

<LINK rel="stylesheet" href="style-for-screen.css" type="text/css" media="screen">
<LINK rel="stylesheet" href="style-for-print.css" type="text/css" media="print">

As you may notice, there is media attribute inside the LINK tag. Web browsers will use style-for-screen.css to show page on screen and style-for-print.css to print the page. For example, let say we want to hide <div id="menu"> in printing version, so in style-for-print.css we can add this code:

#menu {   display: none; }

Or if we don't want to have two separate CSS files, we can do it all in one file, like this :

@media print  {
    /*****   Styles for print   ******/
      h1, h2, h3 {color:black;}
      #navigation {display:none}
}
 
@media screen {
      /*****   Styles for screen  ******/
}

You can see the details on this Printing in ASP.NET article. All credits should go to the original poster of this article.

No comments: