This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using iTextSharp.text; | |
using iTextSharp.text.pdf; | |
using System.IO; | |
public partial class pdftable : System.Web.UI.Page | |
{ | |
protected void Page_Load(object sender, EventArgs e) | |
{ | |
} | |
protected void Button1_Click(object sender, EventArgs e) | |
{ | |
DataTable dt = new DataTable(); | |
dt.Columns.Add("Column1"); | |
dt.Columns.Add("Column2"); | |
dt.Columns.Add("Column3"); | |
dt.Rows.Add("row1", "row1", "row1"); | |
dt.Rows.Add("row2", "row2", "row2"); | |
dt.Rows.Add("row3", "row3", "row3"); | |
ExportToPdf(dt); | |
} | |
public void ExportToPdf(DataTable ExDataTable) | |
{ | |
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10); | |
try | |
{ | |
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream); | |
pdfDoc.Open(); | |
Font fnt = FontFactory.GetFont("Times New Roman", 12); | |
DataTable dt = ExDataTable; | |
if (dt != null) | |
{ | |
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count); | |
PdfPCell PdfPCell = null; | |
for (int rows = 0; rows < dt.Rows.Count; rows++) | |
{ | |
if (rows == 0) | |
{ | |
for (int column = 0; column < dt.Columns.Count; column++) | |
{ | |
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].ColumnName.ToString(), fnt))); | |
PdfTable.AddCell(PdfPCell); | |
} | |
} | |
for (int column = 0; column < dt.Columns.Count; column++) | |
{ | |
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), fnt))); | |
PdfTable.AddCell(PdfPCell); | |
} | |
} | |
pdfDoc.Add(PdfTable); | |
} | |
pdfDoc.Close(); | |
Response.ContentType = "application/pdf"; | |
//Set default file Name as current datetime | |
Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + ".pdf"); | |
System.Web.HttpContext.Current.Response.Write(pdfDoc); | |
Response.Flush(); | |
Response.End(); | |
} | |
catch (Exception ex) | |
{ | |
} | |
} | |
} |