Friday, 21 March 2014

Simple gridview to pdf using iTextSharp

public void GridToPdf()
    {


        GridView gv = new GridView();
        DataTable Data = new DataTable();
        Data.Columns.Add("Sno");
        Data.Columns.Add("Name");
        DataRow DR = Data.NewRow();
        DR["Sno"] = "1";
        DR["Name"] = "Name of a person";

        Data.Rows.Add(DR);

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=" + lblTitle.Text + ".pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        gv.BorderStyle = BorderStyle.None;
        gv.DataSource = Data;
        gv.HeaderStyle.Font.Bold = true;
        gv.DataBind();
       
        gv.RenderControl(hw);
        string str1 = sw.ToString();
        System.IO.StringReader sr = new System.IO.StringReader(str1);
        iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 40f, 10f, 40f, 2f);
        iTextSharp.text.html.simpleparser.HTMLWorker htmlparser = new iTextSharp.text.html.simpleparser.HTMLWorker(pdfDoc);
        iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        iTextSharp.text.pdf.PdfWriter wrt = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.End();

    }

No comments:

Post a Comment