Wednesday, May 12, 2010

Creating PDF from DataTable

I have Written a function to create a pdf file from datatable.
The dll can be downloaded from here
You will have to add two name sapces

using iTextSharp.text;
using iTextSharp.text.pdf;


private void ExportDataToPDFTable(DataTable dt, string filename)
{
Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 42, 35);
try
{
string pdfFilePath = Server.MapPath(".") + "/" + filename;
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));
doc.Open();

Font font8 = FontFactory.GetFont("ARIAL", 7);
Font fontHeader = FontFactory.GetFont("ARIAL", 7, 3);
if (dt != null)
{
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
foreach (DataColumn dc in dt.Columns)
{
PdfPCell PdfPCell = null;
PdfPCell = new PdfPCell(new Phrase(new Chunk(dc.Caption, fontHeader)));
PdfTable.AddCell(PdfPCell);
}
for (int rows = 0; rows <>
{
for (int column = 0; column <>
{
PdfPCell p = null;
if(dt.Columns[column].DataType==typeof(Int64)) //if it is number then format
{
string price = "";
try
{
price = String.Format("{0:#,###}",Int64.Parse(dt.Rows[rows][column].ToString()));
}
catch
{

}
p = new PdfPCell(new Phrase(new Chunk(price, font8)));
}
else
{
//String.Format("{0:#,###}",
p = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
}
PdfTable.AddCell(p);
}
}
doc.Add(PdfTable);
}
}
catch (DocumentException docEx)
{

}
catch (IOException ioEx)
{

}
catch (Exception ex)
{

}
finally
{
//Close document and writer
doc.Close();

}
}