【发布时间】:2014-02-19 16:29:40
【问题描述】:
我有一个简单的类设置来从数据表创建 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";
}
}
【问题讨论】:
-
当您通过调试器运行它时,dt.Rows.Count 是否等于 16?
-
是的,但我刚刚发现了问题,将在下面添加。
标签: c# asp.net pdf itextsharp