Friday, 9 January 2015

Gridview To Pdf in C# & VB.NET

Gridview To Pdf in C# & VB.NET:
 C#

private void PDF_Export()

{

    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition",

        "attachment;filename=GridViewExport.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    GridView1.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());

    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();

    htmlparser.Parse(sr);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End();

}



VB.Net

Private Sub PDF_Export()

  Response.ContentType = "application/pdf"

  Response.AddHeader("content-disposition", _

   "attachment;filename=GridViewExport.pdf")

  Response.Cache.SetCacheability(HttpCacheability.NoCache)

  Dim sw As New StringWriter()

  Dim hw As New HtmlTextWriter(sw)

  GridView1.AllowPaging = False

  GridView1.DataBind()

  GridView1.RenderControl(hw)

  Dim sr As New StringReader(sw.ToString())

  Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)

  Dim htmlparser As New HTMLWorker(pdfDoc)

  PdfWriter.GetInstance(pdfDoc, Response.OutputStream)

  pdfDoc.Open()

  htmlparser.Parse(sr)

  pdfDoc.Close()

  Response.Write(pdfDoc)

  Response.End()

End Sub

 Finally the method that one should not forget is the below otherwise the GridView export will throw the Error

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



C#.Net

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm(

ByVal control As Control)

        ' Verifies that the control is rendered

End Sub
 

No comments:

Post a Comment