Wednesday, April 14, 2010

Printing a control in ASP.NET

Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy to add a reference in case someone knows.



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;
public class PrintHelper
{
public PrintHelper()
{
}
public static void PrintWebControl(Control ctrl)
{
PrintWebControl(ctrl, string.Empty);
}
public static void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(),"PrintJavaScript", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.End();
}
}





Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will contain the controls to be printed. Print.aspx will act as a popup page to invoke the print functionality.

Step 3: In your Default.aspx, drag and drop a few controls that you would like to print. To print a group of controls, place them all in a container control like a panel. This way if we print the panel using our PrintHelper class, all the controls inside the panel gets printed.


Step 4: Add a print button to the Default.aspx and in the code behind, type the following code:


protected void btnPrint_Click(object sender, EventArgs e)
{
Session["ctrl"] = Panel1;
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "");
}





Step 5: In the Page_Load event of Print.aspx.cs, add the following code:


protected void Page_Load(object sender, EventArgs e)
{
Control ctrl = (Control)Session["ctrl"];
PrintHelper.PrintWebControl(ctrl);
}





IMP: If the popups are blocked you can not get the print window, make sure allow popup for this page

No comments:

Post a Comment