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

使用iTextSharp提取PDF阿拉伯语文本出现乱码问题求助

解决iTextSharp提取阿拉伯语PDF文本乱码/字符顺序错乱问题

你的问题核心是阿拉伯语作为**从右到左(RTL)**书写系统,自带变音符号(Tashkeel)和连写字形,而SimpleTextExtractionStrategy仅按PDF底层的字符绘制顺序提取,完全不处理RTL文本的逻辑阅读顺序,也不会自动组合变音符号与基础字符,导致字符拆分、顺序颠倒。

解决方案

替换提取策略并添加阿拉伯语文本修复逻辑,以下是修改后的完整代码:

private static string ReadPdfFile(string fileName)
{
    StringBuilder text = new StringBuilder();

    if (File.Exists(fileName))
    {
        using (PdfReader pdfReader = new PdfReader(fileName))
        {
            // 使用LocationTextExtractionStrategy,按页面文本位置排序,更适配RTL语言
            ITextExtractionStrategy strategy = new LocationTextExtractionStrategy();
            string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, 1, strategy);
            
            // 修复阿拉伯语的变音符号组合与RTL顺序
            currentText = FixArabicText(currentText);
            
            text.Append(currentText);
        }
    }

    return text.ToString();
}

private static string FixArabicText(string input)
{
    if (string.IsNullOrEmpty(input))
        return input;

    // 组合变音符号与对应基础字符,避免符号单独拆分
    StringBuilder sb = new StringBuilder();
    TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(input);
    while (enumerator.MoveNext())
    {
        sb.Append(enumerator.GetTextElement());
    }

    // 反转字符数组修正RTL顺序:PDF中RTL文本是从左到右绘制,提取后顺序反向
    char[] charArray = sb.ToString().ToCharArray();
    Array.Reverse(charArray);
    
    // 调整标点位置,避免反转后标点跑到文本开头
    int lastPunctuationIndex = -1;
    for (int i = charArray.Length - 1; i >= 0; i--)
    {
        if (char.IsPunctuation(charArray[i]))
        {
            lastPunctuationIndex = i;
            break;
        }
    }
    if (lastPunctuationIndex != -1 && lastPunctuationIndex != charArray.Length - 1)
    {
        char punctuation = charArray[lastPunctuationIndex];
        Array.Copy(charArray, lastPunctuationIndex + 1, charArray, lastPunctuationIndex, charArray.Length - lastPunctuationIndex - 1);
        charArray[charArray.Length - 1] = punctuation;
    }

    return new string(charArray);
}

关键说明

  1. LocationTextExtractionStrategy:相比SimpleTextExtractionStrategy,它会按文本在页面上的物理位置排序提取,更符合人类阅读顺序。
  2. FixArabicText方法:
    • 用StringInfo.GetTextElementEnumerator处理变音符号,确保符号和对应基础字符绑定,不会被拆分。
    • 反转字符数组修正RTL文本的顺序,因为PDF底层绘制RTL文本时是从左到右写入,提取后的字符顺序是反向的。
    • 调整标点位置,保证阿拉伯语标点符号出现在文本末尾(符合书写习惯)。

额外注意事项

  • 确认PDF中的阿拉伯语是可提取的矢量文本,如果是图片格式的文本,需要搭配OCR工具处理。
  • 尽量使用最新稳定版的iTextSharp,旧版本对RTL语言的支持存在缺陷。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:55:21