It is a frequent reuirement that you want to print a particular section of .aspx page or just a control like DataGrid with data populated. Usually the Javascript window.print will print the whole page that includes Navigation controls and other un desired items on the printed page. In order o solve this we need to render only the User control and print it but the caviar is that this page shuld not appear to the user. Also ASP.Net requires form tag for the ASP.Net Server controls to be rendered. There are issues dynamically adding form tag to the page.
Here is my Print Solution.It takes any web control and prints it at the Client. For some reason I can not includ < then sign in the code so you have to replace < with < sign in the following code.
For e.g: (inside User Control where this references current User Control)
WebPrinting.PrintWebControl(this);
or (dgCustomers is the id of the DataGrid containing Customer records)
WebPrinting.PrintWebControl(dgCustomers);
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace Jawad.Utils.Printing
{
/// <summary>
/// Summary description for WebPrinting.
/// </summary>
public class WebPrinting
{
public WebPrinting()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Prints any Control i.e. User Control, DataGrid, Page , Panel etc.
/// </summary>
/// <param name="ctrl">Control to be printed</param>
/// <param name="StyleText">Style to be added in the Head Section</param>
public static void PrintWebControl(Control ctrl)
{
PrintWebControl(ctrl, string.Empty );
}
/// <summary>
/// Prints any Control i.e. User Control, DataGrid, Page , Panel etc.
/// </summary>
/// <param name="ctrl">Control to be printed</param>
public static void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter ();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
if ( ctrl is WebControl )
{
Unit w = new Unit(50, UnitType.Pixel);
((WebControl)ctrl).Width = w;
}
Page pg = new Page ();
if (Script != string.Empty )
{
pg.RegisterStartupScript ("PrintJavaScript",Script);
}
HtmlForm frm = new HtmlForm ();
pg.Controls.Add (frm);
frm.Attributes.Add ("runat","server");
frm.Controls.Add (ctrl);
string scr = "<script>function window.onafterprint(){history.back(1);}</script>";
htmlWrite.Write(scr);
pg.DesignerInitialize();
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();
}
}
}
For converting the code to Visual Basic.net