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

iTextSharp 5.5.13.2显示中文失败求助:已有方案无效或报错

解决iTextSharp 5.5.13.2中文显示问题

问题分析

  • 第一个方案生成空白PDF:MSung-Light为繁体中文字体,且未正确配置依赖库或字体无法被识别,导致中文内容无法渲染。
  • 第二个方案报错:AddToResourceSearch方法在iTextSharp 5.5.13.2版本中已移除,无需手动添加资源搜索路径,只需确保依赖库正确引用即可。

可行解决步骤

1. 确认依赖库引用

确保项目中已引用以下三个dll,版本需与iTextSharp 5.5.13.2匹配:

  • iTextSharp.dll
  • iTextAsian.dll
  • iTextAsianCmaps.dll

可通过NuGet搜索对应包安装,或手动添加本地dll文件到项目引用。

2. 方案一:使用内置简体中文字体(STSong-Light)

直接调用iTextAsian提供的简体中文字体,代码示例:

Document document = new Document(PageSize.A4, 50, 50, 50, 50);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap11.pdf", FileMode.Create));
document.Open();

// 创建支持中文的字体
BaseFont baseFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
iTextSharp.text.Font chineseFont = new iTextSharp.text.Font(baseFont, 12);

// 添加中文内容
document.Add(new Paragraph("全澳甲流确诊病例已破", chineseFont));
document.Close();

3. 方案二:使用系统中文字体(如宋体)

如果运行环境中存在宋体等中文字体,可直接指定字体名称加载,无需依赖iTextAsian:

Document document = new Document(PageSize.A4, 50, 50, 50, 50);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap11.pdf", FileMode.Create));
document.Open();

// 加载系统宋体(中文系统用"宋体",英文系统用"SimSun")
BaseFont baseFont = BaseFont.CreateFont("SimSun", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
iTextSharp.text.Font chineseFont = new iTextSharp.text.Font(baseFont, 12);

document.Add(new Paragraph("全澳甲流确诊病例已破", chineseFont));
document.Close();

4. 修正FontSelector混合中英文方案

若需要同时显示中英文,调整FontSelector的字体配置,确保添加简体中文字体:

FontSelector selector = new FontSelector();
// 添加英文基础字体
selector.AddFont(FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12));
// 添加简体中文字体
selector.AddFont(FontFactory.GetFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED, 12));

Phrase ph = selector.Process("全澳甲流确诊病例已破,新增病例120例");
document.Add(new Paragraph(ph));

注意事项

  • 使用EMBEDDED模式时,需确保字体文件可被iTextSharp访问;使用NOT_EMBEDDED模式时,需保证目标运行环境有对应字体。
  • 不同系统的字体名称可能存在差异,需根据实际环境调整(如中文系统的"宋体"在英文系统中对应"SimSun")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 02:57:30