Sunday, April 11, 2010

Export to pdf using iTextSharp in asp.net

sesReportingDataSetTableAdapters.ed_GetHeadcountDataTableAdapter ta = new ed_GetHeadcountDataTableAdapter();
sesReportingDataSet.ed_GetHeadcountDataDataTable dt = ta.GetHeadcountData();

//setting table properties
PdfPTable table = new PdfPTable(6);
table.TotalWidth = 700f;
float[] widths = new float[] { .8f, 1.5f,.5f,1f,1.5f,.7f };
table.SetWidths(widths);
PdfPCell cell = new PdfPCell(new Phrase("Headcount Data driven Report"));
cell.Colspan = 6;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
cell.Border = 0;
cell.HorizontalAlignment = 1;
table.AddCell(cell);

//adding column headers
table.AddCell(new PdfPCell(new Phrase("Term Descr")));
table.AddCell(new PdfPCell(new Phrase("Career Descr")));
table.AddCell(new PdfPCell(new Phrase("RegistrationDayNbr")));
table.AddCell(new PdfPCell(new Phrase("RegistrationDate")));
table.AddCell(new PdfPCell(new Phrase("PopulationCategory")));
table.AddCell(new PdfPCell(new Phrase("Headcount")));

Paragraph p = new Paragraph();

//adding rows in the table
for (int i = 0; i < dt.Rows.Count; i++)
{
PdfPCell cell1 = new PdfPCell(new Phrase(dt.Rows[i]["termDescr"].ToString()));
table.AddCell(cell1);

PdfPCell cell2 = new PdfPCell(new Phrase(dt.Rows[i]["careerDescr"].ToString()));
table.AddCell(cell2);

PdfPCell cell3 = new PdfPCell(new Phrase(dt.Rows[i]["registrationDayNbr"].ToString()));
table.AddCell(cell3);

table.AddCell(Convert.ToDateTime(dt.Rows[i]["registrationDate"].ToString()).ToShortDateString());
table.AddCell(dt.Rows[i]["populationCategory"].ToString());
table.AddCell(dt.Rows[i]["headcount"].ToString());
}

this.Response.ContentType = "application/pdf";

Document doc = new Document(PageSize.LETTER);

PdfWriter writer = PdfWriter.GetInstance(doc, this.Response.OutputStream);

try
{
doc.Open();
doc.Add(table);
doc.Add((iTextSharp.text.Image.GetInstance(originalData)));
}
finally
{
doc.Close();
writer.Flush();
writer.Close();

}

No comments:

Post a Comment