Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Tuesday, February 1, 2011

Print HTML Table in Asp.net

1: Add a print button to the aspx page and in the code behind, type the following code:
protected void ImageBtnPrint_Click(object sender, ImageClickEventArgs e)
    {
        PrintWebControl(table1, string.Empty);
    }
2: Here is the code sample for table
     <table id="table1" runat="server">
        <tr><td></td></tr>
         ...
         ......
        <tr><td></td></tr>
   </table>


3: Define PrintWebControl() class
    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("<script>window.print();</script>");
        HttpContext.Current.Response.End();
    }

No comments:

Post a Comment