Reputation: 1213
I have a simple class setup to create a PDF from a datatable. I am passing a datatable into the code which has 16 rows but the loop which runs through each datarow stops after row 9 for some reason and I can't tell why. The count is fine throughout but it simple stops.
This is the code:
public class CreatePDF
{
static public string GetPDF(DataTable dt)
{
Document document = new Document();
Random rnd = new Random();
String randomnumber = Convert.ToString(rnd.Next(300));
string FileName = "PDF" + randomnumber + ".pdf";
String FilePath = "C:\\TFS\\Portal\\Uploads\\" + FileName;
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.Create));
document.Open();
iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);
iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(dt.Columns.Count);
iTextSharp.text.pdf.PdfPRow Row = null;
float[] widths = new float[] { 4f, 4f, 4f, 4f };
//table.SetWidths(widths);
table.WidthPercentage = 100;
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Products"));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, font5));
}
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), font5));
table.AddCell(new Phrase(r[1].ToString(), font5));
table.AddCell(new Phrase(r[2].ToString(), font5));
table.AddCell(new Phrase(r[3].ToString(), font5));
}
}
document.Add(table);
document.Close();
if (!File.Exists(FilePath))
throw new FileNotFoundException(
string.Format("Final PDF file '{0}' was not found on disk.",
FilePath));
var fi = new FileInfo(FilePath);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition",
String.Format("attachment; filename=\"{0}\"",
FileName));
HttpContext.Current.Response.AddHeader("Content-Length", fi.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(fi.FullName);
return "a";
}
}
Upvotes: 0
Views: 2279
Reputation: 1213
This issue was that it was not setting up the column definition properly. I had to create some additional code to make sure it sets up the correct amount of columns for that table and loops through for each row.
I changed this:
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), font5));
table.AddCell(new Phrase(r[1].ToString(), font5));
table.AddCell(new Phrase(r[2].ToString(), font5));
table.AddCell(new Phrase(r[3].ToString(), font5));
}
}
To this:
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
int index = -1;
foreach (DataColumn dc in dt.Columns)
{
index++;
if (index != dt.Rows.Count)
{
table.AddCell(new Phrase(r[index].ToString(), font5));
}
}
}
}
Upvotes: 1