Extracting Arabic and other right-to-left text from PDFs

Updated · Tested with pypdf 7.2.0, PyMuPDF 2.2, pdfplumber 0.11.11, python-bidi 0.6.12, Poppler 25.03, Tesseract 5.5.0

In short

Arabic text in a PDF is often stored back to front, like Hebrew, and can be put right with the python-bidi package. Its second problem is harder: the joined letters lam-alef are often extracted in the wrong order, which silently changes words. For text people will rely on, draw the page as an image and read it with OCR.

Arabic text in a PDF has the problem Hebrew has, lines stored back to front, and a second one of its own: Arabic letters join, and joined letters are where extractors make mistakes. The examples use arabic-extract.pdf, a short document with labels, a number, and one sentence with an English name in it.

Problem one: the order

Like Hebrew, Arabic is read from right to left, and many PDFs store each line in the order it is drawn, from left to right. A tool that returns the line as stored gives it reversed. The title of the sample is مستخرج شركة; pdfplumber returns it as ةكرش جرختسم.

The repair is the same as for Hebrew: run each line through the Unicode bidirectional algorithm with the python-bidi package. Why Hebrew text comes out backwards explains why this works.

Python
import pdfplumber
from bidi.algorithm import get_display

with pdfplumber.open("arabic-extract.pdf") as pdf:
    lines = pdf.pages[0].extract_text().split("\n")

print(get_display(lines[0]))
Output
مستخرج شركة

Problem two: joined letters

When the letter lam (ل) is followed by alef (ا), Arabic writes the two as one joined shape: لا. A PDF stores that as a single shape, with a note that it stands for two letters, lam then alef.

A tool that reverses a line to fix its order must not reverse the two letters inside that shape. Several do. The sample has a heading, ملاحظات ("notes"), which contains the pair. This is what each tool returned for it:

ToolResultCorrect?
pypdfملاحظاتYes
PyMuPDFمالحظاتNo: alef and lam swapped
pdftotextمالحظاتNo: alef and lam swapped
pdfplumber, then python-bidiمالحظاتNo: alef and lam swapped

The wrong version looks almost right, which is the danger. In the sentence of the sample, the word for "and three", وثلاثة, came out of pdftotext as وثالثة, which is a different real word. No spell-checker will flag it.

You cannot repair it afterwards by swapping the pair back, either. Alef followed by lam is the Arabic word "the", one of the most common letter pairs in the language, so you cannot tell a swapped pair from a correct one.

pypdf got the heading right, but in the sentence that mixes Arabic with an English name and a year, it put the pieces in the wrong order. Of the tools we tried, none returned the whole page correctly from the text stored in the file.

The dependable route: read the page as a picture

OCR does not use the stored text at all. It looks at the page as a person does, so the order in the file and the way shapes are recorded cannot mislead it. Draw the page as an image and read it with Tesseract's Arabic model:

Shell
sudo apt-get install tesseract-ocr tesseract-ocr-ara
pip install pymupdf pytesseract pillow
Python
import io
import unicodedata

import pymupdf
import pytesseract
from PIL import Image

with pymupdf.open("arabic-extract.pdf") as doc:
    image = Image.open(io.BytesIO(doc[0].get_pixmap(dpi=300).tobytes("png")))

text = pytesseract.image_to_string(image, lang="ara+eng")
clean = "".join(ch for ch in text if unicodedata.category(ch) != "Cf")
for line in clean.split("\n"):
    if line.strip():
        print(line)
Output
اسم الشركة هاربور لين للخدمات اللوجستية
رقم الشركة 51-482913-6
الحالة نشطة
تاريخ التسجيل 14 مارس 2019
رأس المال 1,250.50
ملاحظات
الشركة مملوكة لشركة dio Harbor Holdings Ltd عام 2019. للشركة مديران وثلاثة رهون, اثنان منها
aoe 3
نشطان.

The heading and "and three" are right, and every line is in reading order. It is not perfect: the large title at the top is missing, one Arabic word in the sentence was read as the Latin letters dio, and a stray line appeared. OCR trades one kind of mistake for another. The difference is that its mistakes are visible, nonsense you can catch, while a swapped pair of letters is a quiet change of meaning.

The line that strips characters of category Cf removes the invisible direction marks Tesseract puts around left-to-right runs.

Which to use

Your needUse
Searching, where a few wrong words do not matterpypdf for the text
Names, amounts and anything a person will rely onOCR, then check
Numbers and dates onlyEither: digits are not affected by letter joining

Whichever you choose, test it on a line that contains لا before you trust it with a folder of files.

Presentation forms

Some older PDFs store Arabic not as ordinary letters but as "presentation forms": separate characters for each shape a letter can take, and a single character, U+FEFB, for the joined لا. Text like that looks right and will not match a search. Normalise it:

Python
import unicodedata

print([hex(ord(c)) for c in unicodedata.normalize("NFKC", "ﻻ")])
Output
['0x644', '0x627']

One character in, lam and alef out.

Arabic and 100sands

100sands reads Arabic PDFs that contain text and returns each line in reading order, with no parameter to set and no bidi step afterwards. Numbers and English names stay in place, with one case to check: an amount followed by an English word, such as 1,234.56 USD, can come back as USD 1,234.56. Presentation forms come back as ordinary letters. For arabic-extract.pdf, the response has this shape:

JSON
{
  "pages": 1,
  "text": "مستخرج شركة\n...\nالشركة مملوكة لشركة Harbor Holdings Ltd منذ عام 2019. للشركة مديران وثلاثة رهون، اثنان منها\n..."
}

It does not do OCR. Scans and images are refused, so for the OCR route described above, use Tesseract with its Arabic data. As with any tool, test it on a line of your own that contains لا before you trust it with a folder of files.

Questions

Why is Arabic text from a PDF reversed or wrong?

Two reasons. The file often stores each line in drawing order, left to right, so it comes out back to front. And joined letters such as lam-alef are stored as one shape, which many tools turn back into two letters in the wrong order.

Which Python library extracts Arabic from PDFs correctly?

In our test none returned a whole page correctly. pypdf kept the joined lam-alef right but misordered a sentence with an English name. PyMuPDF, pdftotext, and pdfplumber with python-bidi swapped the two letters.

Is OCR better than text extraction for Arabic PDFs?

For accuracy on names and words, often yes. OCR reads the page as a person sees it, so the way the file stores text cannot mislead it. It makes its own mistakes, but they are usually visible ones.

Try it on your own documents

A free plan every month, no credit card. See the PDF to text API.

Start free