Click here to Skip to main content
16,019,577 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to download the content of gridview1 to Excel and PDF file. Tried Lots of ways using iTextSharp. I tried rendering , also copying cell by cell creating pdfTable. None worked. Please Help





Please help me as I am new to chart control in ASP.NET


What I have tried:

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();
}


also I tried with following code in Button Click Event mwthod. Still Failed.


int columnsCount = GridView1.HeaderRow.Cells.Count;

PdfPTable pdfTable = new PdfPTable(columnsCount);


foreach(TableCell gridViewHeaderCell in GridView1.HeaderRow.Cells)
{

Font font = new Font();

font.Color = new BaseColor(GridView1.HeaderStyle.ForeColor);


PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewHeaderCell.Text, font));


pdfCell.BackgroundColor = new BaseColor(GridView1.HeaderStyle.BackColor);

// Add the cell to PDF table
pdfTable.AddCell(pdfCell);
}


foreach (GridViewRow gridViewRow in GridView1.Rows)
{
if (gridViewRow.RowType == DataControlRowType.DataRow)
{

foreach (TableCell gridViewCell in gridViewRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(GridView1.RowStyle.ForeColor);

PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewCell.Text, font));

pdfCell.BackgroundColor = new BaseColor(GridView1.RowStyle.BackColor);

pdfTable.AddCell(pdfCell);
}
}
}


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

PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

pdfDocument.Open();
pdfDocument.Add(pdfTable);
pdfDocument.Close();

Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition",
"attachment;filename=Employees.pdf");
Response.Write(pdfDocument);
Response.Flush();
Response.End();
Posted
Updated 9-Sep-16 1:50am

Here is the updated code for exporitng gridview to pdf along with the charts

Step 1: Place this gridview and button on your aspx page :

ASP.NET
<asp:Button ID="btnExportGridView" runat="server" Text="ExportChart" OnClick="btnExportGridView_Click" />

<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false" 
onrowcreated="gvData_RowCreated" onrowdatabound="gvData_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Username" DataField="Username" ItemStyle-Width="120px" />

<asp:TemplateField HeaderText="marks Report">
<ItemTemplate>

<asp:Chart ID="Chart2" runat="server" Width="250px" Height="200px">
<Series>
 <asp:Series Name="Series1" LegendText="LEVEL 1"      IsValueShownAsLabel="false" ChartArea="ChartArea1"
 MarkerBorderColor="#DBDBDB" XValueMember="col1"    YValueMembers="col2">
 </asp:Series>                                
 </Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1">
</asp:ChartArea>
</ChartAreas>
</asp:Chart>

</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>



Step 2: Binding Sample Data to GridView :


C#
DataTable dtData;
protected void Page_Load(object sender, EventArgs e)
   {
       BindData();
   }



C#
private void BindData()
 {
     dtData = GetData();
     gvData.DataSource = dtData;
     gvData.DataBind();
 }



C#
private DataTable GetData()
    {
        DataTable dtDataTmp = new DataTable();
        dtDataTmp.Columns.Add("Username", typeof(string));
        dtDataTmp.Columns.Add("Marks", typeof(DataTable));

        DataTable dt1 = new DataTable();
        dt1.Columns.Add("col1", typeof(string));
        dt1.Columns.Add("col2", typeof(decimal));

        DataTable dt2 = new DataTable();
        dt2.Columns.Add("col1", typeof(string));
        dt2.Columns.Add("col2", typeof(decimal));

        dt1.Rows.Add("Math", 40);
        dt1.Rows.Add("Science", 65);
        dt1.Rows.Add("English", 74);
        dt1.AcceptChanges();

        dt2.Rows.Add("Math", 45);
        dt2.Rows.Add("Science", 60);
        dt2.Rows.Add("English", 30);
        dt2.AcceptChanges();

        dtDataTmp.Rows.Add("Rohit", dt1);
        dtDataTmp.Rows.Add("Mohit", dt2);
        dtDataTmp.AcceptChanges();

        return dtDataTmp;
    }



C#
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dtTmp = (DataTable)dtData.Rows[e.Row.RowIndex]["Marks"];
            Chart chart = (Chart)e.Row.FindControl("Chart2");

            chart.DataSource = dtTmp;
            chart.DataBind();

        }
    }



Step 3: Code to Export the Gridview alongwith chart to pdf format using iTextSharp :


C#
protected void btnExportGridView_Click(object sender, EventArgs e)
   {
       Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
       using (MemoryStream output = new MemoryStream())
       {
           PdfWriter wri = PdfWriter.GetInstance(doc, output);
           doc.Open();

           GridViewRow gvr = null;
           PdfPTable tab = new PdfPTable(2);
           PdfPCell[] cells = null;
           Chart chrt = null;
           Random rnd = new Random();
           string img_path = "";
           List<string> lstImgs = new List<string>();

           for (int i = 0; i < gvData.Rows.Count; i++)
           {
               gvr = gvData.Rows[i];

               PdfPCell c1 = new PdfPCell();
               PdfPCell c2 = new PdfPCell();

               for (int j = 0; j < gvData.Rows[i].Cells.Count; j++)
               {
                   c1 = new PdfPCell();
                   c2 = new PdfPCell();
                   c1.AddElement(new Paragraph(gvr.Cells[0].Text));
                   chrt = (Chart)gvr.FindControl("Chart2");
                   img_path = Server.MapPath("Images/img_" + rnd.NextDouble() + ".jpg");
                   chrt.SaveImage(img_path);
                   c2.AddElement(iTextSharp.text.Image.GetInstance(img_path));
                   lstImgs.Add(img_path);
               }
               cells = new PdfPCell[] { c1, c2 };
               tab.Rows.Add(new PdfPRow(cells));
           }
           doc.Add(tab);
           doc.Close();

           foreach (string img in lstImgs)
           {
               if (File.Exists(img))
                   File.Delete(img);
           }

           Response.ClearContent();
           Response.ClearHeaders();
           Response.ContentType = "application/pdf";
           Response.AddHeader("Content-Disposition", "attachment; filename=testpdf.pdf");

           Response.BinaryWrite(output.ToArray());
           Response.End();
           Response.Flush();
           Response.Clear();
       }

   }




Enjoy !!
 
Share this answer
 
v2
Comments
Member 11197134 10-Sep-16 17:47pm    
Thanks a lot sir. This worked for me.
Hi, nice to see your question.

I just created a sample code for your requirement. However I have not created chart inside a gridview. I have just quicky written code for exporting a chart control to pdf file.

I have used iTextSharp library for creating pdf file.


Step 1 : Place the following Chart Control on the web page

ASP.NET
<asp:Chart runat="server" ID="Chart1">
          <Series>
              <asp:Series Name="Series1" XValueMember="col1" YValueMembers="col2">
           </asp:Series>
          </Series>
      <ChartAreas>
           <asp:ChartArea Name="ChartArea1">
           </asp:ChartArea>
      </ChartAreas>
</asp:Chart>



Step 2: Exporting the chart control to pdf on click of a button

C#
protected void btnExportChart_Click(object sender, EventArgs e)
   {
       DataTable dtData = new DataTable();
       dtData.Columns.Add("col1", typeof(decimal));
       dtData.Columns.Add("col2", typeof(decimal));

       dtData.Rows.Add(2, 10);
       dtData.Rows.Add(4, 6);
       dtData.Rows.Add(6, 9);
       dtData.Rows.Add(8, 12);
       dtData.Rows.Add(10, 15);
       dtData.AcceptChanges();

       Chart1.DataSource = dtData;
       Chart1.DataBind();

       string img_path = Server.MapPath("Images/chart1.jpg");

       Chart1.SaveImage(img_path, ChartImageFormat.Jpeg);

       Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
       using (MemoryStream output = new MemoryStream())
       {
           PdfWriter wri = PdfWriter.GetInstance(doc, output);
           doc.Open();

           iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(img_path);
           doc.Add(img);
           doc.Close();

           Response.ClearContent();
           Response.ClearHeaders();
           Response.ContentType = "application/pdf";
           Response.AddHeader("Content-Disposition"," attachment;filename=testpdf.pdf");

           Response.BinaryWrite(output.ToArray());
           Response.End();
           Response.Flush();
           Response.Clear();
       }

   }



Hope this might help you to use this code according to your requirement for gridview too.
Please revert if you need any clarifications.
 
Share this answer
 
Comments
Member 11197134 8-Sep-16 16:02pm    
Yes Sir. Thanks for the reply. But I got this code and tried. Its working fine if i create a chart separatly and print to pdf file. But I have a requirement as i mentioned earlier in my question. my chart is in cell of gridview. I want to print complete gridview to pdf. Pelase help me in that.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width="700px" OnRowDataBound="GridView1_RowDataBound">
<columns>
<asp:BoundField HeaderText="Username" DataField="Username" ItemStyle-Width="120px" />
<asp:TemplateField HeaderText="marks Report">
<itemtemplate>
<div>
<asp:Chart ID="Chart1" runat="server" Width="550px" Height="200px">
<series>
<asp:Series Name="Series1"
LegendText="LEVEL 1" IsValueShownAsLabel="false" ChartArea="ChartArea1"
MarkerBorderColor="#DBDBDB">
<asp:Series Name="Series2"
LegendText="LEVEL 2" IsValueShownAsLabel="false" ChartArea="ChartArea1"
MarkerBorderColor="#DBDBDB" >
<asp:Series Name="Series3"
LegendText="LEVEL 3" IsValueShownAsLabel="false" ChartArea="ChartArea1"
MarkerBorderColor="#DBDBDB">


<chartareas>
<asp:ChartArea Name="ChartArea1">



</div>



This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900