使用iTextSharp生成PDF时阿拉伯文显示异常(字符不连写)求助
解决iTextSharp阿拉伯文无法连写的问题
问题根源
iTextSharp(尤其是旧版本)的基础文本组件(如Phrase)不会自动处理阿拉伯文的复杂字形变换(连写、字符形态切换),即便设置了RTL方向,也仅调整文本排列顺序,不会处理字符连写逻辑。
解决方案
改用ColumnText绘制文本,配合ArabicLigaturizer处理连写规则,同时确保字体正确加载。修改后的完整代码如下:
using iTextSharp.text; using iTextSharp.text.pdf; using System; using System.IO; using System.Windows.Forms; namespace Test_PDf { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { using (SaveFileDialog Sfd = new SaveFileDialog() { Filter = "PDF file|*.pdf", ValidateNames = true }) { if (Sfd.ShowDialog() == DialogResult.OK) { using (var doc = new iTextSharp.text.Document(PageSize.A4.Rotate())) { var writer = PdfWriter.GetInstance(doc, new FileStream(Sfd.FileName, FileMode.Create)); doc.Open(); // 加载支持阿拉伯文的Arial字体,注意路径大小写匹配 BaseFont bf = BaseFont.CreateFont("C:/Windows/Fonts/arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(bf, 12); // 用内置工具处理阿拉伯文连写,将单个字符转换为连写形态 var ligaturizer = new ArabicLigaturizer(); string processedText = ligaturizer.Process(Txt_1.Text); // 使用ColumnText实现RTL方向的文本布局,确保连写生效 ColumnText columnText = new ColumnText(writer.DirectContent); columnText.SetSimpleColumn(36, 36, doc.PageSize.Width - 36, doc.PageSize.Height - 36); columnText.RunDirection = PdfWriter.RUN_DIRECTION_RTL; columnText.AddElement(new Phrase(processedText, font)); columnText.Go(); doc.Close(); } } } } } }
关键说明
ArabicLigaturizer:iTextSharp内置类,专门处理阿拉伯文的连写规则,将独立字符转换为符合书写规范的连写字形。ColumnText:相比直接调用doc.Add(phrase),ColumnText能更好适配RTL方向与复杂脚本的布局逻辑,确保文本按正确形态渲染。- 版本兼容:如果你的iTextSharp版本过旧,可能缺少
ArabicLigaturizer,建议升级到5.5.13及以上版本,该版本对复杂脚本支持更完善。 - 字体路径:确保字体文件名与系统实际路径一致,部分系统中Arial字体文件名为
arial.ttf(小写),需注意大小写匹配。
内容的提问来源于stack exchange,提问作者ibrahem rmadan
相关产品推荐
相关产品推荐

