This is my PageLoad
using (FileStream fs = new FileStream(Server.MapPath("PDF\\Test.pdf"), FileMode.Create))
{
using (iTextSharp.text.Document doc = new iTextSharp.text.Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
doc.Add(CreatePDF(DALTreeItemContent.SelectAll()));
doc.Close();
}
fs.Close();
} ;
PdfPTable CreatePDF(DataTable dt)
{
PdfPTable pdfTable = new PdfPTable(dt.Columns.Count);
iTextSharp.text.Font fontNormal = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL);
iTextSharp.text.Font fontBold = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.BOLD);
iTextSharp.text.Font fontBoldBig = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLD);
foreach (DataColumn column in dt.Columns)
{
PdfPCell cell = new PdfPCell();
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.Phrase=new Phrase(column.ColumnName.ToString(), fontBold);
cell.BackgroundColor = new BaseColor(85, 107, 47);
cell.BorderColor = new BaseColor(244, 164, 96);
pdfTable.AddCell(cell);
}
foreach (DataRow row in dt.Rows)
{
foreach (object o in row.ItemArray)
{
object f = "False";
object f1 = "false";
object t = "True";
object t1 = "true";
PdfPCell cell = new PdfPCell();
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
if (o.ToString() == f.ToString() || o.ToString() == f1.ToString())
{
cell.Phrase= new Phrase("No", fontNormal) ;
}
else if (o.ToString() == t.ToString() || o.ToString() == t1.ToString())
{
cell.Phrase= new Phrase("Yes", fontNormal);
}
else
cell.Phrase=new Phrase(o.ToString(), fontNormal);
cell.BorderColor = new BaseColor(244, 164, 96);
pdfTable.AddCell(cell);
}
}
return pdfTable;
}
This function can fix all your alignment problems, I could see what was the problem you were talking about when i looked more into it. Once i did some searching on it, i was able to find a solution. Instead of adding 'New Chunk' to a PDFCell you must set the PDFPCell.phrase. I guess inorder for the phrase to take up the whole area available to it and center the content this is necessary otherwise when you add an element to PDFPCell it is somehow going into composite mode or something or expecting more elements to be added to it.
I found this
link which helped eventually.
Hope it helps. :-)..