Search code examples
c#pdfitextextractarabic

extract arabic from pdf to string c#


ok i know this question is repeated too many times. but until now i didn't find a solution. I'm using iTextSharp to extract from a pdf. for english it works good, but for Arabic it always shows "???????" in the console and "Ó å æ á É" in the .txt this is my code

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


        if (File.Exists(fileName))
        {
            PdfReader pdfReader = new PdfReader(fileName);
            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
            string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, 1, strategy);
            //currentText = Encoding.UTF8.GetString(UTF8Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
            text.Append(currentText);
        }

        return text.ToString();
    }

update:

the problem is solved by using the UTF8 for the output file now i have 2 more problems

it shows "ا ﻟ ﺘ ﻘ ﺪ ﻳ ﻢ ﺗ ﻢ" instead of "تم التقديم" so:

  1. i need to remove the spaces between letters.

  2. the words' order is inverted.


Solution

  • Try the following code to convert your "Ó å æ á É" to "س ه و ل ة"

    public static string Arabic1256ToUtf8(string data)
    {
        var latin = Encoding.GetEncoding("ISO-8859-1");
        var bytes = latin.GetBytes(data); // get the bytes for your ANSI string
    
        var arabic = Encoding.GetEncoding("Windows-1256"); // decode it using the correct encoding
        return arabic.GetString(bytes);
    }