I'm trying to export a gridview table in c# to a PDF file. I have searched other solutions, and it appears that everyone is trying to fill the table from an SQL database first. This step is unnecessary, as I have already filled the table via active directory and soforth. Currently my code works, however it's plain black and white and looks rather dull.
Here is my current code (using iTextSharp):
protected void ExportToPDF()
{
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);
grdvList.AllowPaging = false;
// grdvList.DataBind();
grdvList.RenderBeginTag(hw);
grdvList.HeaderRow.RenderControl(hw);
foreach (GridViewRow row in grdvList.Rows)
{
row.RenderControl(hw);
}
grdvList.FooterRow.RenderControl(hw);
grdvList.RenderEndTag(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();
}
And my gridview:
<asp:GridView ID="grdvList" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Name" datafield="Name" ReadOnly="True" >
<ItemStyle Width="17.5%" />
</asp:BoundField>
<asp:BoundField HeaderText="Phone Ext" datafield="Phone Ext" ReadOnly="True" >
<ItemStyle Width="11.5%" />
</asp:BoundField>
<asp:BoundField HeaderText="Mobile" datafield="Mobile" ReadOnly="True" >
<ItemStyle Width="16%" />
</asp:BoundField>
<asp:BoundField HeaderText="Email" datafield="Email" ReadOnly="True" >
<ItemStyle Width="47.5%" />
</asp:BoundField>
<asp:BoundField HeaderText="Department" DataField="Department" ReadOnly="True" >
<ItemStyle Width="17.5%" />
</asp:BoundField>
</Columns>
<alternatingrowstyle backcolor="#D6D6D6" />
</asp:GridView>
I'd like to add a border for all table cells, making every second row with a grey background. It's working great on my webpage, but I need it to work in my PDF document as well. Can anyone help?