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

C#使用Spire.PDF生成含列表内容PDF时仅显示最后一行问题

问题原因

生成的PDF仅显示最后一行,是两个逻辑错误导致的:

  • 你在for循环里反复覆写str变量,循环执行完成后,str里存储的本来就只有最后一条记录的拼接内容,你之前填充了所有行数据的outPutList根本没被用到
  • 初始化PdfList对象时,你传入的构造参数是单个字符串str,而非存储了全量数据的outPutList集合,PdfList从一开始拿到的内容就只有最后一行,自然不可能渲染出完整列表。
修正代码
// 组装全量列表数据
int arrayLength = obj.records.Count;
List<string> outPutList = new List<string>();
for (int i = 0; i < arrayLength; i++)
{
    // 不建议用大量手动空格对齐,用制表符或者后续用表格排版适配性更好
    string lineStr = $"{obj.records[i].datetime}\t{obj.records[i].userName}\t{obj.records[i].inTime}\t{obj.records[i].outTime}";
    outPutList.Add(lineStr);
    Console.WriteLine(lineStr);
}

// PDF生成逻辑
Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4);
float y = 30;

PdfBrush brush = PdfBrushes.Black;
// 注意:如果内容包含中文,要替换为微软雅黑、宋体这类支持中文的字体,否则会出现乱码
PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new System.Drawing.Font("Impact", 18f, FontStyle.Regular), true);
PdfTrueTypeFont contentFont = new PdfTrueTypeFont(new System.Drawing.Font("Arial", 12f, FontStyle.Regular), true);
PdfStringFormat centerFormat = new PdfStringFormat(PdfTextAlignment.Center);

// 绘制标题
page.Canvas.DrawString("Rapport", titleFont, brush, page.Canvas.ClientSize.Width / 2, y, centerFormat);
y += titleFont.MeasureString("Rapport", centerFormat).Height + 5;

// 核心修正:传入完整的outPutList集合,而非单个str变量
PdfList recordList = new PdfList(outPutList);
recordList.Font = contentFont;
PdfLayoutResult result = recordList.Draw(page, 10, y);

doc.SaveToFile("List.pdf"); 
doc.Close();
System.Diagnostics.Process.Start("List.pdf");
优化提示
  • 靠手动加空格、制表符对齐字段的方式兼容性很差,不同字体、不同PDF查看器下很容易出现列错位。如果需要规整的多列展示效果,直接用PdfTable组件做表格排版,每列绑定对应字段,对齐效果稳定,还能自定义边框、表头样式。
  • 当列表内容长度超过单页A4可展示高度时,PdfList会自动触发分页,不需要手动计算坐标新增页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 10:01:08