我最近开始使用 itextsharp
并一直使用它在 asp.net 中使用 Web 服务创建 PDF 报告。我在网络服务中的代码如下所示。我的问题是,它不显示前 3 列数据。
我认为问题出在 dt.Rows
中。
string[] strFile = Directory.GetFiles(strUploadPath);
Array.ForEach(Directory.GetFiles(strUploadPath), File.Delete);
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(strUploadPath + "/" + strFilename, FileMode.Create));
document.Open();
Font font5 = FontFactory.GetFont(FontFactory.HELVETICA, 5);
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[] { 4f, 4f, 4f, 4f, 4f, 4f };
table.SetWidths(widths);
table.WidthPercentage = 200;
PdfPCell cell = new PdfPCell(new Phrase());
int j = 1;
foreach (DataColumn c in dt.Columns)
{
if (j <= (dt.Columns.Count))
{
//table.AddCell(new Phrase(c.ToString(),font5));
//table.AddCell(new Phrase(j.ToString(),font5));
table.AddCell(new Phrase(c.ColumnName, font5));
}
j++;
}
int k = 1;
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(k.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));
table.AddCell(new Phrase(r[4].ToString(), font5));
table.AddCell(new Phrase(r[5].ToString(), font5));
// table.AddCell(new Phrase(r[6].ToString(), font5));
// table.AddCell(new Phrase(r[7].ToString(), font5));
}
k++;
}
document.Add(table);
document.CloseDocument();
document.Close();
return strFilename;
}
else
{
return null;
}
最佳答案
OP 的代码包含这一行:
table.WidthPercentage = 200;
这会导致表格的宽度是页面减去页边距的两倍 (200%)。因此,它是部分隐藏的。
使用 WidthPercentage
属性设置表格宽度时,通常不应将其设置在 100 以上。
正如 OP 同时确认的那样,适当的更改会使代码正常工作。
关于c# - iTextSharp 不显示所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39615079/