我有一个简单的类设置来从数据表创建PDF。我将一个数据表传递给有16行的代码,但是由于某种原因,遍历每个数据行的循环在第9行之后停止,我不知道为什么。整个计数都很好,但它很简单。
这是代码:
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";
}
}
答案 0 :(得分:1)
这个问题是它没有正确设置列定义。我必须创建一些额外的代码,以确保它为该表设置正确的列数并为每一行循环。
我改变了这个:
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));
}
}
对此:
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));
}
}
}
}