You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iTextSharp第二页单元格无法渲染问题求助

问题排查与修复方案

核心错误分析

你的代码存在三个关键问题,直接导致单元格(表格)无法渲染:

  • 未将表格添加到文档:创建了PdfPTable和单元格,但从未调用document.Add(table)将表格写入PDF文档。
  • 变量名不匹配:创建的图片变量是image1,但后续调用SetAbsolutePosition时用了未定义的image,会引发运行时异常,中断后续代码执行。
  • 大小写错误:C#是大小写敏感语言,document.close()应为document.Close(),错误写法会导致编译失败,文档无法正确保存内容。

修复后的完整代码示例

float dpi = 100f;
float widthInches = (3900f * 1.1f) / dpi;
float heightInches = (2775f * 1.1f) / dpi;

// 放大Rectangle尺寸10%
float width = widthInches * 1.1f * 72f;
float height = heightInches * 1.1f * 72f;

var rect = new iTextSharp.text.Rectangle(width, height);
iTextSharp.text.Document document = new iTextSharp.text.Document(rect, 10f, 10f, 10f, 0f);
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(dest, System.IO.FileMode.Create));
document.Open();

// ... 第一页内容省略 ...

document.NewPage();
// 修正变量名,使用定义好的image1
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(model.CaraB["1"]);
image1.SetAbsolutePosition(0, 0);
image1.ScaleToFit(3400, 2400);
document.Add(image1);

PdfPTable table = new PdfPTable(2);
// 可选:设置表格宽度适配页面,避免超出边界
table.WidthPercentage = 100;

// 创建表头单元格
PdfPCell header1 = new PdfPCell(new iTextSharp.text.Phrase(new iTextSharp.text.Chunk("Logros", iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.BOLD))));
PdfPCell header2 = new PdfPCell(new iTextSharp.text.Phrase(new iTextSharp.text.Chunk("Horas", iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.BOLD))));

// 添加表头到表格
table.AddCell(header1);
table.AddCell(header2);

// 创建数据单元格
PdfPCell cell1 = new PdfPCell(new iTextSharp.text.Phrase(new iTextSharp.text.Chunk("Unlogro", iTextSharp.text.FontFactory.GetFont("Arial", 10))));
PdfPCell cell2 = new PdfPCell(new iTextSharp.text.Phrase(new iTextSharp.text.Chunk("12", iTextSharp.text.FontFactory.GetFont("Arial", 10))));
table.AddCell(cell1);
table.AddCell(cell2);

// 关键步骤:将表格添加到文档
document.Add(table);

// 修正大小写,正确关闭文档
document.Close();

额外优化建议

  • 设置表格WidthPercentage = 100,确保表格适配页面宽度,避免内容被截断。
  • 给单元格添加内边距(如header1.Padding = 5;),提升表格可读性。
  • 检查图片缩放尺寸,避免图片覆盖表格内容。

内容的提问来源于stack exchange,提问作者PontiacGTX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 14:12:57