1. Write a printhelper class
Code
Using System;
Using System. Data;
Using System. configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. webcontrols;
Using System. Web. UI. webcontrols. webparts;
Using System. Web. UI. htmlcontrols;
Using System. IO;
Using System. text;
Using System. Web. sessionstate;
namespace printpage
{< br> Public class printhelper
{< br> Public printhelper ()
{}
Public Static VoidPrintwebcontrol (Control)
{
Printwebcontrol (control,String. Empty );
}
Public Static Void Printwebcontrol (Control, String Script)
{
Stringwriter stringwrite = New Stringwriter ();
Htmltextwriter htmlwriter = New Htmltextwriter (stringwrite );
If (Control Is Webcontrol)
{
Unit W = New Unit ( 100 , Unittype. Percentage );
(Webcontrol) control). Width = W;
}
Page PG = New Page ();
Pg. enableeventvalidation = False ;
If (Script ! = String . Empty)
{
Pg. clientscript. registerstartupscript (pg. GetType (), " Print‑cipt " , Script );
}
Htmlform FRM = New Htmlform ();
Pg. Controls. Add (FRM );
FRM. Attributes. Add ( " Runat " , " Server " );
FRM. Controls. Add (control );
Pg. rendercontrol (htmlwriter );
String Strhtml = Stringwrite. tostring ();
Httpcontext. Current. response. Clear ();
Httpcontext. Current. response. Write (strhtml );
Httpcontext. Current. response. Write ( " <SCRIPT> window. Print (); </SCRIPT> " );
Httpcontext. Current. response. End ();
}
}
}
2. Create the default page:
Put a button btnprint and a Panel. The Panel contains the content to be printed. Code
Using System;
Using System. Data;
Using System. configuration;
Using System. collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. webcontrols;
Using System. Web. UI. webcontrols. webparts;
Using System. Web. UI. htmlcontrols;
NamespacePrintpage
{
Public Partial Class_ Default: system. Web. UI. Page
{
Protected VoidPage_load (ObjectSender, eventargs E)
{
}
Protected Void Btnprint_click ( Object Sender, eventargs E)
{
Session [ " Control " ] = Panel1;
Clientscript. registerstartupscript ( This . GetType (), " Onclick " , " <Script language = JavaScript> window. Open ('print. aspx ', 'printme', 'height = 300px, width = 300px, scrollbars = 1'); </SCRIPT> " );
}
}
}
3. Create a print page:
Call the print event in the form_load event: Code
Using System;
Using System. Data;
Using System. configuration;
Using System. collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. webcontrols;
Using System. Web. UI. webcontrols. webparts;
Using System. Web. UI. htmlcontrols;
Namespace Printpage
{
Public Partial Class Print: system. Web. UI. Page
{
Protected Void Page_load ( Object Sender, eventargs E)
{
Control = (Control) session [ " Control " ];
Printhelper. printwebcontrol (control );
}
}
}
Source code:
/Files/chenqingwei/printpage.rar