Saturday, June 25, 2011

How to: perform page break by printing ASP.NET Web forms

Once we created an ASP.NET Web Application having web forms the next request was to organize carbon copy of these forms: do print them and support page breaks.

The solution is:

  • declare dedicated div style class for separate print pages
  • add page-break-after: always; property to this class
  • enclose the print pages in separate div elements and set their style to the class declared above

Example:

the ASP.net Form:

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="WebForm.aspx.cs"Inherits="WebForm"%>
<!DOCTYPEhtml PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
htmlxmlns
="http://www.w3.org/1999/xhtml">
<
headrunat
="server">
    <
styletype="text/css"media
="screen">
      
.formLabel
      
{
            min-width: 100px;
            color: Blue;
        }
       
.formTextBox
      
{
            width: 200px;
        }
    </style
>
    <
styletype="text/css"media
="print">
      
.formLabel
      
{
            min-width: 100px;
            color: Black;
        }
       
.formPage
      
{
            page-break-after: always;
        }
       
.formTextBox
      
{
            width: 200px;
        }
    </style
>
    <
title>Department Form</title
>
</
head
>
<
body
>
    <
formid="form1"runat
="server">
    <
div
>
        <
divclass
="formPage">
            <
asp:LabelID="LabelName"runat="server"Text="Name:"CssClass="formLabel"Width="100px"></asp:Label
>
            <
asp:TextBox ID="TextBoxName"runat="server"CssClass="formTextBox"></asp:TextBox
>
            <
br
/>
            <
asp:LabelID="LabelPhone"runat="server"Text="Phone:"CssClass="formLabel"Width="100px"></asp:Label
>
            <
asp:TextBox ID="TextBoxPhone"runat="server"CssClass="formTextBox"></asp:TextBox
>
            <
br
/>
        </
div
>
        <
divclass
="formPage">
            <
asp:LabelID="LabelAddress"runat="server"Text="Address:"CssClass
="formLabel"
              
Width="100px"></asp:Label
>
            <
asp:TextBox ID="TextBoxAddress"runat="server"CssClass="formTextBox"></asp:TextBox
>
            <
br
/>
            <
asp:LabelID="LabelRegPlate"runat="server"Text="Reg. Plate:"CssClass
="formLabel"
              
Width="100px"></asp:Label
>
            <
asp:TextBox ID="TextBoxRegPlate"runat="server"CssClass="formTextBox"></asp:TextBox
>
            <
br
/>
        </
div
>
    </
div
>
    </
form
>
</
body
>
</
html
>

The form in browser:
image

The form in print view:

imageimage

Enjoy!

1 comment:

JanisB said...

Thanks a bunch! Frankly I didn't think it was possible to effect a printer page break via an aspx program. This saves me a lot of trouble!