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
相关产品推荐
相关产品推荐

