DEV Community

György Gulyás
György Gulyás

Posted on Originally published at sahifa.dev

Why Arabic breaks in your PDF (and how to fix it)

You build an invoice, an account statement or a certificate. It looks perfect in the browser. Then you generate the PDF and the Arabic text looks like this:

  • the letters don't join: ف ا ت و ر ة instead of فاتورة;
  • the words come out in reverse order;
  • you get ???? or empty boxes;
  • an IBAN or an order number in the middle of a sentence jumps to the wrong side.

This is one of the most asked PDF questions on Stack Overflow; the dompdf question alone has been viewed almost 19,000 times. All four symptoms come from two steps that browsers do and most PDF libraries skip, so once you know the two steps, the fix is a choice between three approaches.

Arabic needs two things most PDF libraries don't do

Writing Latin text into a PDF is simple: take each character, find its glyph in the font, draw it, move right. Arabic needs two extra steps.

1. Shaping

An Arabic letter has up to four forms, depending on its position in the word: isolated, initial, medial and final. ه looks different in هو, فهم and وجه. The text you store (U+0647) is always the same code point; picking the right form, and the ligatures such as لا, is the job of a text shaper such as HarfBuzz.

Libraries that write glyphs one by one without a shaper draw every letter in its isolated form. Hence ف ا ت و ر ة.

2. Bidirectional reordering

Arabic runs right to left, but numbers, Latin words, email addresses and IBANs inside it run left to right. The Unicode Bidirectional Algorithm (UAX #9) decides the visual order of every run. Without it, words appear reversed, punctuation lands on the wrong side, and SA03 8000 0000 6080 1016 7519 gets scrambled.

Browsers do both steps: shaping with HarfBuzz, and the bidi algorithm. That's why your HTML looks right in Chrome. Many PDF libraries do neither, or only one of them.

How the popular libraries behave

Library Arabic glyphs Shaping Bidi Typical fix
dompdf (PHP) with a font like DejaVu Sans no no pre-shape with ar-php, or switch
mPDF (PHP) yes yes, if the font's OTL is on yes 'mode' => 'utf-8', font with useOTL => 0xFF, dir="rtl"
TCPDF (PHP) yes (aealarabiya) yes basic $pdf->setRTL(true)
jsPDF (JS) after embedding a TTF basic limited embed Amiri, align: 'right', keep lines simple
pdfmake (JS) after embedding a TTF no no reverse words by hand, or switch
ReportLab (Python) with a TTF no no arabic_reshaper + python-bidi
iText (Java/.NET) with a TTF with pdfCalligraph with RUN_DIRECTION_RTL commercial add-on for full support
Headless Chrome (Puppeteer, Playwright) if the font is installed yes yes install Arabic fonts in the container

The more of the text layout a library does itself, the more work Arabic becomes. A browser engine already does all of it.

Fix 1: keep your library and patch it

If you're deep into one library and your documents are simple (short Arabic lines, few numbers), the patches work.

PHP / dompdf, reshaping before rendering:

$arabic = new \ArPHP\I18N\Arabic();
$html = preg_replace_callback('/[\x{0600}-\x{06FF}\s]+/u',
    fn ($m) => $arabic->utf8Glyphs($m[0]), $html);
Enter fullscreen mode Exit fullscreen mode

Python / ReportLab:

import arabic_reshaper
from bidi.algorithm import get_display

text = get_display(arabic_reshaper.reshape("مرحبا بالعالم"))
c.setFont("Amiri", 14)
c.drawRightString(550, 750, text)
Enter fullscreen mode Exit fullscreen mode

These break down with mixed Arabic and English in one line, with wrapping (you have to reshape after line breaking), and with tables.

Fix 2: render with a browser engine

Build the document as HTML, then print it with Chromium. You get the same shaping and bidi as the browser, plus modern CSS for layout.

import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'load' });
await page.evaluate(() => document.fonts.ready);
const pdf = await page.pdf({ format: 'A4', printBackground: true });
await browser.close();
Enter fullscreen mode Exit fullscreen mode

The step people miss is the fonts in the container. A slim Linux image has no Arabic font, so Chromium draws empty boxes. On Debian or Ubuntu:

RUN apt-get update && apt-get install -y --no-install-recommends \
      fonts-noto-core fonts-hosny-amiri \
 && fc-cache -f && rm -rf /var/lib/apt/lists/*
Enter fullscreen mode Exit fullscreen mode

fonts-noto-core includes Noto Naskh Arabic and Noto Sans Arabic. fonts-hosny-amiri adds Amiri, a classic Naskh style that looks good on printed invoices.

The HTML that makes Arabic documents look right

Whichever engine you use, these details decide whether tables, amounts and account numbers come out in the right place:

<html dir="rtl" lang="ar">
<head>
  <meta charset="utf-8">
  <style>
    body  { font-family: 'Noto Naskh Arabic', 'Amiri', serif; }
    .num  { font-variant-numeric: tabular-nums; }
    @page { size: A4; margin: 15mm; }
  </style>
</head>
<body>
  <h1>فاتورة ضريبية مبسطة</h1>
  <p>رقم الحساب: <bdi dir="ltr">SA03 8000 0000 6080 1016 7519</bdi></p>
  <p>البريد: <bdi dir="ltr">billing@example.sa</bdi></p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • dir="rtl" on <html>, not only on paragraphs. Tables, lists, flexbox and grid then mirror automatically.
  • <bdi> around left-to-right runs: IBANs, emails, SKUs, order numbers. It isolates them from the surrounding Arabic, so they keep their own order.
  • tabular-nums for amount columns, so the digits line up.
  • One language per element in bilingual documents. <td lang="ar">…</td><td lang="en">…</td> is much more predictable than both languages in one sentence.

One more thing to know if you extract text from the PDF later, for search or for automated tests. When we ran five Saudi document types through Chromium and read the PDFs back, the image was always right, but the text layer stored the Arabic runs in visual order, and in a heavily vowelled line (بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيم) the last letter was missing from the extracted text although it was on the page. So test the rendered page as an image, and don't expect pdftotext to give you back your original string.

Fix 3: let a service do it

If you'd rather not run Chromium and maintain fonts yourself, a hosted HTML-to-PDF API does the same thing. In Saudi Arabia you may also need the documents to stay in the Kingdom, especially for fintech and personal data.

Disclosure: I'm affiliated with Sahifa, an HTML-to-PDF API that runs Chromium with Arabic fonts in Jeddah. There are ready-to-run examples in five languages on GitHub, and it is on RapidAPI with a free plan of 50 requests a month.

curl https://api.sahifa.dev/v3/convert/pdf \
  --user "api:$SAHIFA_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{"source": "<html dir=\"rtl\" lang=\"ar\"><body><h1>فاتورة</h1></body></html>"}' \
  --output invoice.pdf
Enter fullscreen mode Exit fullscreen mode

If you have an Arabic PDF case that still breaks, share it in the comments. I'm collecting edge cases.

Top comments (0)