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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:57:32