First you should add the reference to iTextSharp.dll
Then the following method will create a PDF document and the document contains a table with the supplied data.
using
iTextSharp;
using
iTextSharp.text;
using
iTextSharp.text.pdf;
private void create_pdf(DataTable
dt, string fname)
{
fname = GenarateFilename(fname, ".pdf");
fullfilename = fname;
Document
pdfdoc = new Document(iTextSharp.text.PageSize.A3, 10.0F, 10.0F, 10.0F, 10.0F);
PdfWriter
pw = PdfWriter.GetInstance(pdfdoc, new FileStream(fname,
FileMode.Create));
pdfdoc.Open();
iTextSharp.text.pdf.PdfPTable table = new
PdfPTable(dt.Columns.Count);
table.TotalWidth = PageSize.A3.Width;
table.WidthPercentage = 100;
table.SpacingBefore = 20f;
table.SpacingAfter = 30f;
//table.HorizontalAlignment
= Element.ALIGN_CENTER;
table.DefaultCell.Border =
iTextSharp.text.Rectangle.LEFT_BORDER |
iTextSharp.text.Rectangle.RIGHT_BORDER |
iTextSharp.text.Rectangle.TOP_BORDER |
iTextSharp.text.Rectangle.BOTTOM_BORDER;
iTextSharp.text.BaseColor CLR = new
iTextSharp.text.BaseColor(105, 56, 40);
iTextSharp.text.Font colfont = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA.ToString(),
9, 1, CLR);
foreach
(DataColumn dc in
dt.Columns)
{
PdfPCell
cell = new PdfPCell();
cell.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER | iTextSharp.text.Rectangle.TOP_BORDER | iTextSharp.text.Rectangle.BOTTOM_BORDER;
cell.BorderWidth = 1f;
Chunk
chunkcols = new Chunk(dc.ToString().ToUpperInvariant(),
colfont);
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.BorderColor = new BaseColor(222,
189, 140);
cell.BackgroundColor = new BaseColor(210,
165, 112);
cell.AddElement(chunkcols);
table.AddCell(cell);
}
Chunk
chunkrows;
iTextSharp.text.BaseColor color__1 = new
iTextSharp.text.BaseColor(105, 56, 40);
iTextSharp.text.Font
rowfont = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA.ToString(), 7, color__1);
foreach
(DataRow dr in
dt.Rows)
{
for
(int M = 0; M < dt.Columns.Count; M++)
{
PdfPCell
cell1 = new PdfPCell();
cell1.Border =
iTextSharp.text.Rectangle.LEFT_BORDER |
iTextSharp.text.Rectangle.RIGHT_BORDER |
iTextSharp.text.Rectangle.TOP_BORDER |
iTextSharp.text.Rectangle.BOTTOM_BORDER;
//cell1.Phrase
= new Phrase(dr[M].ToString());
chunkrows = new Chunk(dr[M].ToString(),
rowfont);
cell1.HorizontalAlignment =
(int)cellalignments(dr[M].GetType().BaseType.ToString(),
"P.D.F."); //iTextSharp.text.pdf.PdfPCell.ALIGN_RIGHT;// Element.ALIGN_RIGHT;
//Convert.ToInt32(cellalignments(dr[M].GetType().BaseType.ToString(),
"P.D.F."));//Element.ALIGN_LEFT;
cell1.BorderColor = new BaseColor(222,
189, 140);
cell1.AddElement(chunkrows);
table.AddCell(cell1);
cell1 = null;
}
}
pdfdoc.Add(table);
pdfdoc.Close();
}