Krishan Dutt Sharma

Web Developer

Export Data To PDF From DataTable

In SQL Server, first we create one table, tbl_EmpDetails.
  1. CREATE TABLE [dbo].[tbl_EmpDetails](    
  2.     [EmpID] [int] IDENTITY(1,1) NOT NULL,    
  3.     [EmpName] [varchar](100) NOT  NULL,    
  4.     [EmpAddress] [nvarchar](100) NOT NULL,    
  5.     [Mobile] [varchar](20) NOT NULL,    
  6.     [EmailID] [nvarchar](50) NOT NULL,    
  7.     [DOB] [varchar](50) NOT NULL,    
  8.  CONSTRAINT [PK_tbl_EmpDetails] PRIMARY KEY CLUSTERED     
  9. (    
  10.     [EmpID] ASC    
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,   
  12. ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  13. ON [PRIMARY]    
  14.     
  15. GO   
Insert Employee details in Table.
  1. INSERT INTO tbl_EmpDetails Values('Anil','Mumbai',1233456789,'anil@gmail.com','1989-10-10')  
  2. INSERT INTO tbl_EmpDetails Values('Suresh','Mumbai',1233456789,'suresh@gmail.com','1989-10-10')  
  3. INSERT INTO tbl_EmpDetails Values('Ramesh','Mumbai',1233456789,'Ramesh@gmail.com','1989-10-10')  
Now, we create ASP.Net Web Application.
 
Export Data To PDF From DataTable
 
Add below namespace,
  1. using System.Text;  
  2. using System.Data.SqlClient;  
  3. using iTextSharp.text;  
  4. using iTextSharp.text.pdf;  
  5. using iTextSharp.text.html.simpleparser;  
  6. using System.Data;  
  7. using System.Configuration;  
  8. using System.IO;  
On page load we bind grid as below code .
  1. public partial class EmployeeList : System.Web.UI.Page  
  2. {  
  3.     protected void Page_Load(object sender, EventArgs e)  
  4.     {  
  5.         BindGrid();  
  6.     }
  7. }
In BindGrid function we get data from database and store value in session.
  1. protected void BindGrid() {  
  2.     DataTable dt = new DataTable();  
  3.     string queryString = "select * from tbl_EmpDetails";  
  4.     string conn = ConfigurationManager.ConnectionStrings["TestConnectionString"].ToString();  
  5.     var table = new DataTable();  
  6.     using(SqlConnection sql = new SqlConnection(conn)) {  
  7.         SqlCommand command = new SqlCommand(queryString, sql);  
  8.         sql.Open();  
  9.         SqlDataAdapter da = new SqlDataAdapter(command);  
  10.         da.Fill(table);  
  11.         sql.Close();  
  12.         da.Dispose();  
  13.     }  
  14.     dt = table;  
  15.     GridView1.DataSource = dt;  
  16.     GridView1.DataBind();  
  17.     Session["Data"] = dt;  
  18. }  
Now run program, you will have the below output.
 
Export Data To PDF From DataTable
 
Export to PDF Button Click Code, 
  1. protected void ExportPDf_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         string Err = string.Empty;  
  4.         DataTable dt = (DataTable) Session["Data"];  
  5.         Document pdfDocument = new Document();  
  6.         StringBuilder sb = new StringBuilder();  
  7.         //pdfDocument Content in HTml Format  
  8.         if (dt.Rows.Count > 0) {  
  9.             sb.Append("<html>< head ><title></title></head><body>");  
  10.             string strActualRecords = string.Empty;  
  11.             strActualRecords = "<table style=\"width:100%;font-size: 9pt; font-family: verdana; \" border=\"1\" cellspacing=\"0\" cellpadding=\"0\">";  
  12.             strActualRecords += "<tr><td style=\"width: 5%;white-space: nowrap;\">EMPID</td><td style=\"width: 5%;\">EmpName</td><td style=\"width: 5%;\">EmpAddress</td>" + "<td style=\"width: 5%;\">Mobile</td>" + "<td style=\"width: 5%;\">EmailID</td>" + "< td style =\"width: 5%;\">DOB</td></tr>";  
  13.             for (int i = 0; i < dt.Rows.Count; i++) {  
  14.                 strActualRecords += "<tr>";  
  15.                 strActualRecords += "<td style=\"width: 5%;\">" + dt.Rows[i]["EMPID"].ToString() + "</td>" + "<td style=\"width: 5%;\">" + dt.Rows[i]["EmpName"].ToString() + "</td>" + "<td style=\"width: 5%;\">" + dt.Rows[i]["EmpAddress"].ToString() + "</td>" + "<td style=\"width: 5%;\">" + dt.Rows[i]["Mobile"].ToString() + "</td>" + "<td style=\"width: 5%;\">" + dt.Rows[i]["EmailID"].ToString() + "</td>" + "<td style=\"width: 5%;\">" + dt.Rows[i]["DOB"].ToString() + "</td>";  
  16.                 strActualRecords += "</tr>";  
  17.             }  
  18.             strActualRecords += "</table>";  
  19.             sb.Append(strActualRecords);  
  20.             sb.Append("</body></html>");  
  21.         }  
  22.         string pdffilename = DateTime.Now.Ticks.ToString() + ".pdf";  
  23.         PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream);  
  24.         pdfDocument.Open();  
  25.         String htmlText = sb.ToString();  
  26.         StringReader str = new StringReader(htmlText);  
  27.         HTMLWorker htmlworker = new HTMLWorker(pdfDocument);  
  28.         htmlworker.Parse(str);  
  29.         pdfWriter.CloseStream = false;  
  30.         pdfDocument.Close();  
  31.         //Download Pdf  
  32.         Response.Buffer = true;  
  33.         Response.ContentType = "application/pdf";  
  34.         Response.AppendHeader("Content-Disposition""attachment; filename=" + pdffilename);  
  35.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  36.         Response.Write(pdfDocument);  
  37.         Response.Flush();  
  38.         Response.End();  
  39.     } catch (Exception ex) {  
  40.         throw ex;  
  41.     }  
  42. }  
Code Description
 
DataTable dt = (DataTable)Session["Data"];
 
In this line we assign Session stored value to Datatable.
 
Then create StringBuilder object and append value of datatable dt using For loops.
 
Below code is used to read, write Content in pdf and download PDF content.
 
Export Data To PDF From DataTable
 
Output
 
Export Data To PDF From DataTable