By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,040 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

How to export a GridView Data to PDF

P: 17
Language: ASP.net
Platform: Visual Studio 2010 with ASP.net
Technology: Used in ASP.net
Level: Beginner

Note:
You have to download the itextsharp.dll file and add as a reference to your project.You can download the iTextsharp.dll from the
below link.
http://sourceforge.net/projects/itextsharp/

Introduction

1. Add a gridview into a aspx file
2. Add a button into a aspx file and give the name as "btnExportToPDF"
3. Add a code into a aspx file

Expand|Select|Wrap|Line Numbers
  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
  2.     <Columns>
  3.     <asp:BoundField DataField="State" HeaderText="State" />
  4.     <asp:BoundField DataField="City" HeaderText="City" />
  5.     </Columns>
  6.     </asp:GridView>
  7. <asp:Button ID="btnExportToPDF" runat="server" Text="ExportToPDF" 
  8.         onclick="btnExportToPDF_Click" />
4. Write a code in aspx.cs file
Expand|Select|Wrap|Line Numbers
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.             DataTable dtRecords = new DataTable();
  4.             dtRecords.Columns.Add("State", typeof(string));
  5.             dtRecords.Columns.Add("City", typeof(string));
  6.             DataRow dr = dtRecords.NewRow();
  7.             dr["State"] = "Maharashtra";
  8.             dr["City"] = "Nagpur";
  9.             dtRecords.Rows.Add(dr);
  10.  
  11.  
  12.             GridView1.DataSource = dtRecords;
  13.             GridView1.DataBind();
  14. }
  15. protected void btnExportToPDF_Click(object sender, EventArgs e)
  16. {
  17.            int noOfColumns = 0, noOfRows = 0;       
  18.             DataTable tbl = null;    
  19.             if (GridView1.AutoGenerateColumns)        
  20.             {          
  21.                 tbl = GridView1.DataSource as DataTable;
  22.                 // Gets the DataSource of the GridView Control.        
  23.                 noOfColumns = tbl.Columns.Count;        
  24.                 noOfRows = tbl.Rows.Count;       
  25.             }       
  26.             else       
  27.             {           
  28.                 noOfColumns = GridView1.Columns.Count;      
  29.                 noOfRows = GridView1.Rows.Count;  
  30.             }       
  31.             float HeaderTextSize = 8;      
  32.             float ReportNameSize = 10;     
  33.             float ReportTextSize = 8;     
  34.             float ApplicationNameSize = 7;   
  35.             // Creates a PDF document     
  36.             Document document = null;     
  37.             if (LandScape == true)        
  38.             {            
  39.                 // Sets the document to A4 size and rotates it so that the 
  40.                 //orientation of the page is
  41.                 document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
  42.             }       
  43.             else     
  44.             {          
  45.                 document = new Document(PageSize.A4, 0, 0, 15, 5);       
  46.             }        
  47.             // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.  
  48.             iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);    
  49.             // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.    
  50.             mainTable.HeaderRows = 4;      
  51.             // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.   
  52.             iTextSharp.text.pdf.PdfPTable headerTable = new   iTextSharp.text.pdf.PdfPTable(2);      
  53.             // Creates a phrase to hold the application name at the left hand side of the header.  
  54.             Phrase phApplicationName = new Phrase("Sample Application", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));  
  55.             // Creates a PdfPCell which accepts a phrase as a parameter.   
  56.             PdfPCell clApplicationName = new PdfPCell(phApplicationName);   
  57.             // Sets the border of the cell to zero.     
  58.             clApplicationName.Border = PdfPCell.NO_BORDER;   
  59.             // Sets the Horizontal Alignment of the PdfPCell to left.  
  60.             clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;  
  61.             // Creates a phrase to show the current date at the right hand side of the header.   
  62.             Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));   
  63.             // Creates a PdfPCell which accepts the date phrase as a parameter. 
  64.             PdfPCell clDate = new PdfPCell(phDate);     
  65.             // Sets the Horizontal Alignment of the PdfPCell to right. 
  66.             clDate.HorizontalAlignment = Element.ALIGN_RIGHT;  
  67.             // Sets the border of the cell to zero.      
  68.             clDate.Border = PdfPCell.NO_BORDER;      
  69.             // Adds the cell which holds the application name to the headerTable.    
  70.             headerTable.AddCell(clApplicationName);       
  71.             // Adds the cell which holds the date to the headerTable. 
  72.             headerTable.AddCell(clDate);       
  73.             // Sets the border of the headerTable to zero.   
  74.             headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;  
  75.             // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable. 
  76.             PdfPCell cellHeader = new PdfPCell(headerTable);    
  77.             cellHeader.Border = PdfPCell.NO_BORDER;     
  78.             // Sets the column span of the header cell to noOfColumns.    
  79.             cellHeader.Colspan = noOfColumns;      
  80.             // Adds the above header cell to the table.      
  81.             mainTable.AddCell(cellHeader);       
  82.             // Creates a phrase which holds the file name.     
  83.             Phrase phHeader = new Phrase("Sample Export", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));  
  84.             PdfPCell clHeader = new PdfPCell(phHeader);    
  85.             clHeader.Colspan = noOfColumns;    
  86.             clHeader.Border = PdfPCell.NO_BORDER;    
  87.             clHeader.HorizontalAlignment = Element.ALIGN_CENTER;     
  88.             mainTable.AddCell(clHeader);      
  89.             // Creates a phrase for a new line.    
  90.             Phrase phSpace = new Phrase("\n");    
  91.             PdfPCell clSpace = new PdfPCell(phSpace);     
  92.             clSpace.Border = PdfPCell.NO_BORDER;    
  93.             clSpace.Colspan = noOfColumns;     
  94.             mainTable.AddCell(clSpace);    
  95.             // Sets the gridview column names as table headers.  
  96.             for (int i = 0; i < noOfColumns; i++)   
  97.             {          
  98.                 Phrase ph = null;     
  99.                 if (GridView1.AutoGenerateColumns)    
  100.                 {             
  101.                     ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)); 
  102.                 }           
  103.                 else        
  104.                 {            
  105.                     ph = new Phrase(GridView1.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
  106.                 }           
  107.                 mainTable.AddCell(ph);     
  108.             }        // Reads the gridview rows and adds them to the mainTable    
  109.             for (int rowNo = 0; rowNo < noOfRows; rowNo++)      
  110.             {           
  111.                 for (int columnNo = 0; columnNo < noOfColumns; columnNo++)    
  112.                 {               
  113.                     if (GridView1.AutoGenerateColumns)           
  114.                     {                    
  115.                         string s = GridView1.Rows[rowNo].Cells[columnNo].Text.Trim();    
  116.                         Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)); 
  117.                         mainTable.AddCell(ph);       
  118.                     }              
  119.                     else        
  120.                     {           
  121.                         if (GridView1.Columns[columnNo] is TemplateField)     
  122.                         {                     
  123.                             DataBoundLiteralControl lc = GridView1.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl; 
  124.                             string s = lc.Text.Trim();   
  125.                             Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));  
  126.                             mainTable.AddCell(ph);    
  127.                         }                 
  128.                         else               
  129.                         {                   
  130.                             string s = GridView1.Rows[rowNo].Cells[columnNo].Text.Trim(); 
  131.                             Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)); 
  132.                             mainTable.AddCell(ph);                  
  133.                         }                                   
  134.                     }        
  135.                 }                       
  136.                 // Tells the mainTable to complete the row even if any cell is left incomplete.    
  137.                 mainTable.CompleteRow();     
  138.             }       
  139.             // Gets the instance of the document created and writes it to the output stream of the Response object.  
  140.             PdfWriter.GetInstance(document, Response.OutputStream);  
  141.             // Creates a footer for the PDF document.   
  142.             HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true); 
  143.             pdfFooter.Alignment = Element.ALIGN_CENTER;    
  144.             pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;  
  145.             // Sets the document footer to pdfFooter.  
  146.            // document.Footer = pdfFooter;        
  147.             // Opens the document.       
  148.             document.Open();       
  149.             // Adds the mainTable to the document.      
  150.             document.Add(mainTable);       
  151.             // Closes the document.       
  152.             document.Close();    
  153.             Response.ContentType = "application/pdf"; 
  154.             Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf"); 
  155.             Response.End();
  156.  
  157.         }
  158.  
  159.  
  160.  
  161.         public bool LandScape { get; set; }
  162.  
  163. }
  164.  
  165.  public override void VerifyRenderingInServerForm(Control control)
  166. {
  167.  
  168. }
Summary:
Run the application click on button, it will ask to save or open a file, if you save it will be saved into your disk
or if you click on open it directely open the PDF file.


References

License

Bytes

About the Author

Vivek M. kapile
ITC Infotech Developer
India,Bangalore
May 10 '11 #1
Share this Article
Share on Google+