Printing Controls In ASP.NET Web Page

12 views
Skip to first unread message

Meet

unread,
Dec 30, 2010, 6:14:10 AM12/30/10
to DotNetProfessionals-Group
Step 1)

Create a class with name Printhelper
The code for the following is as below:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.IO;
using System.Web.SessionState;
/// <summary>
/// Summary description for PrintHelper
/// </summary>
public class PrintHelper
{
public PrintHelper()
{
//
// TODO: Add constructor logic here
//
}
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.DesignerI nitialize();
pg.RenderControl(htmlWrite);
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();
}
}






Step 2)

Now create two web pages one defalt.aspx where you have to put control
which you want to print and the second page is print.aspx where data
will be printed.

On default.aspx the control which we want to print must be inside a
container like “Panel”.
Take a button for giving the print command.

On button click event type the following code:

Session["ctrl"] = Panel1;
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script
language=javascript
>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</
script>");


Step 3)

On page load event of print.aspx type the following code:

Control ctrl = (Control)Session["ctrl"];
PrintHelper.PrintWebControl(ctrl);

That’s is you have done with printing the web page control in ASP.NET


Code by;
Harmeet Singh,
Sr. Software Engineer,
Lio Technologies, Rohtak.
Reply all
Reply to author
Forward
0 new messages