C# – Export to PDF from GridView

asp.netcgridviewitext

I have done the export to PDF from gridview using iTextSharp. Since the gridview columns are more the columns in PDF is not aligned and it is so small. I tried writing styles in both codebehind and .aspx page. But the size is not changing.

.aspx Page

 <asp:GridView ID="grdResult" runat="server" AutoGenerateColumns="true" Width="100%"
      CellPadding="3" CellSpacing="3" Font-Size="10pt">
      <HeaderStyle Font-Bold="true" Width="250px" />
 </asp:GridView>

.cs Page

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=MARGEmployees.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
grdResult.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(grdResult);
frm.RenderControl(hw);
grdResult.HeaderRow.Style.Add("width", "15%");
grdResult.HeaderRow.Style.Add("font-size", "10px");
grdResult.Style.Add("font-family", "Tahoma");
grdResult.Style.Add("font-size", "8px");
StringReader sr = new StringReader(sw.ToString());
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();

Please help me on this

Best Answer

Try to change your pdf doc size in code behind.

// Try any one of these

Document pdfDoc = new Document(PageSize.A3, 7f, 7f, 7f, 0f);
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
Document pdfDoc = new Document(PageSize.A1, 7f, 7f, 7f, 0f);

Since the size of the pdf doc is set the columns are compressed. If you change the size it wil work.