Arabic & RTL

How pdfpeek decides an Arabic page reads right column first

A PDF has no reading order, only text placed on a page. On a two-column Arabic page the right column comes first, and an extractor that reads left first gets the columns in the wrong order. In Pdfpeek, the order comes from two decisions, and both are in the code.

Each block gets a direction

Stage 1 counts the strong-direction characters in each block with Python’s unicodedata.bidirectional(). Arabic letters are AL, Hebrew R, Latin L. Digits and punctuation don’t vote.

A block is RTL when more than 30% of its strong characters are right-to-left. With a bar that low, an Arabic sentence with a couple of English names in it still counts as Arabic. نشرت الورقة على Zenodo و GitHub comes out rtl.

The page follows its blocks

Stage 3 calls a page RTL when more than half its blocks are. Then the XY-cut runs: it looks for a horizontal gap to split the page at, then a vertical one, and recurses into each part. On an RTL page, a vertical split puts the right half first. Where no gap is left, blocks sort top to bottom, and right to left within a row.

Fed two Arabic columns whose blocks don’t line up across the page, it returns the right column top to bottom, then the left. The same layout in English comes out left column first. If the blocks do line up in rows, the horizontal cut wins and it reads row by row, right block first.

Where it still goes wrong

The direction belongs to the page, not to a region of it. On a page with three English paragraphs and an Arabic passage in two columns, the page votes LTR, and the passage’s left column comes out first. Checked on v0.1.0: عمود يسار (left column) comes out before عمود يمين (right column).