Thursday, July 28, 2005

CSS Tip: Using media=print for printer-friendly pages

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/css_tip_using_mediaprint_for_printerfriendly_pages.htm]

When you print a page, you want just the workspace of the page in normal portrait view - not banner ads, left navigation bars or text that extends off the printed page . This is a printer-friendly view. There are at least two categories of solutions:

  1. Have a "click here for printer-friendly version" link that posts back to the server, does manipulation such as hiding menus, and creates a new instance of the page in printer-friendly mode
  2. Use Cascading Style Sheets (CSS).

The former has several problems that the latter solves:

  • It posts back to the server, which hurts performance
  • It becomes a nightmare if you want to open a new instance of the page for printing, such that closing this print-page won't accidentally close the main app page.
  • It is a pain for editable pages because it requires the developer to manually persist all values to the new print page. Say the user enters a value in a text field, how do you persist that to a new page instance, perhaps via querystring or session? But what if the values are large?
  • It requires additional effort for each page.

CSS provides a "media" attribute that can apply different style sheets to different media. The two media we're looking at here are screen (default) and print.

A stylesheet can set the color, visibility, or any other style that's relevant to a print-version. Here's a practical example that hides buttons (you can click a button in printview) and formats all text in greycolor (you many not want to waste color printing on text):

Html page:

<HTML>
    <HEAD>
       
        <LINK href="Print.css" type="text/css" rel="stylesheet" media="print">
        <LINK href="StyleSheet1.css" type="text/css" rel="stylesheet" media="screen">
    HEAD>
    <body MS_POSITIONING="FlowLayout">
        <form id="Form1" method="post" runat="server">
            <P>This tests styles.P>
            <P>
                <asp:Label id="Label1" runat="server" CssClass="MainFont">
                Labelasp:Label>P>
            <P>
                <asp:Button id="Button1" runat="server" CssClass="PrintButton"
                Text="Button">asp:Button>P>
        form>
    body>
HTML
>

Stylesheet (Normal):

body
{
}
.MainFont
{
    font-weight: bold;
    color: red;
}

Stylesheet (Print):

body
{
}
.PrintButton
{
    display: none;
}
.Template
{
    display: none;
}

Eric Myer has a great article that explains how to use CSS for printing.

No comments:

Post a Comment