Sunday, 30 June 2013

How To- Export Gridview to PDF in ASP.Net with Image

How To- Export Gridview to PDF in ASP.Net with Image


Exporting Gridview to PDF


For exporting the data, I am using the iTextSharp (third party dll) in this post. Download the iTextSharp .
I have following Table which contains the Image Information like Image Name and Image Path.
Export Gridview to PDF in ASP.Net with Image
For exporting images into PDF we need to convert the ImagePath shown in table into its absolute URl. For example, In the above image-

Images/Chrysanthemum.jpg
Now we have to change it in to-
http://localhost/Images/Chrysanthemum.jpg
So for this conversion, You can use the following function-
public string GetImageUrl(string imagepath)
{
  string[] splits = Request.Url.AbsoluteUri.Split('/');
  if (splits.Length >= 2)
  {
    string url = splits[0] + "//";
    for (int i = 2; i < splits.Length - 1; i++)
    {
       url += splits[i];
       url += "/";
    }
      return url + imagepath;
  }
  return imagepath;
}
Now we have to call this function for creating absolute URL of images. Here,I am calling this function as shown below- 
<asp:GridView ID="grdSample" runat="server" AutoGenerateColumns="False" 
            DataSourceID="SqlDataSource1" Width="400px">
            <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
           <asp:BoundField DataField="ImageName" HeaderText="ImageName" 
                    SortExpression="ImageName" />
                <asp:TemplateField ItemStyle-Height="100" ItemStyle-Width="100" HeaderText="Image"> 
                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ImagePath", GetImageUrl("{0}")) %>' Height="100" Width="100" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestTableConnectionString %>"
            SelectCommand="SELECT * FROM [ImageInfo]"></asp:SqlDataSource>
        <br />
        <asp:Button ID="btnExport" runat="server" Text="Expot to PDF" OnClick="btnExport_Click" />
In the above markup you can see that I am passing the "ImagePath" getting from database to "GetImageUrl" method for getting absolute image URL. Now write the following code on Click event of button. 
protected void btnExport_Click(object sender, EventArgs e)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Sample.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            //Set AllowPaginf false to export the full data
            grdSample.AllowPaging = false;
            grdSample.DataBind();
            //Start the rendering of control here
            grdSample.RenderBeginTag(hw);
            grdSample.HeaderRow.RenderControl(hw);
            foreach (GridViewRow row in grdSample.Rows)
            {
                row.RenderControl(hw);
            }
            grdSample.FooterRow.RenderControl(hw);
            grdSample.RenderEndTag(hw);
            //Apply some style settimgs
            grdSample.Caption = "Your caption";
            grdSample.Style.Add("width", "400px");
            grdSample.HeaderRow.Style.Add("font-size", "12px");
            grdSample.HeaderRow.Style.Add("font-weight", "bold");
            grdSample.Style.Add("border", "1px solid black");
            grdSample.Style.Add("text-decoration", "none");
            grdSample.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
            grdSample.Style.Add("font-size", "8px");
            StringReader sr = new StringReader(sw.ToString());
            //creating new pdf document
            Document pdfDoc = new Document(PageSize.A4, 7f, 7f, 7f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
            Response.Clear();
        }
Output Screens
Export Gridview to PDF in ASP.Net with Image
Fig-Gridview on WebPage
Export Gridview to PDF in ASP.Net with Image

No comments:

Post a Comment