Persian and Arabic
Persian and Arabic are written from right to left, and a letter changes shape depending on its neighbours: at the start, in the middle or at the end of a word, and alone. Some pairs form ligatures. Two things have to happen before such a text can be drawn: the letters have to be put in the right order for the eye (the bidirectional algorithm), and the right shape of each letter has to be chosen from the font (shaping, the font's GSUB tables).
libstb does both inside draw_text, measure and render. You write the text as you would type it, in logical order, and pass it in.
import os
import libstb as stb
os.makedirs("out", exist_ok=True)
font = stb.Font.open("Vazirmatn-Regular.ttf")
# A flat background (the picture is painted over with one color).
page = stb.Image.open("astronaut.png").crop(0, 0, 512, 260).fill((245, 243, 238))
# Write the text as you would type it. The letters join, the ligatures form and the line runs right to left.
page = page.draw_text("سلام دنیا", font, 56, 492, 20, color="#1d3557", align="right")
page = page.draw_text("مرحبا بالعالم", font, 40, 492, 100, color="#e63946", align="right")
# Mixed text keeps each script in its own order.
page = page.draw_text("libstb یعنی کتابخانه 2026", font, 32, 492, 170, color="#2a9d8f", align="right")
page.write("out/persian.png")
print("the font has the letter seen:", "yes" if font.has_glyph("س") else "no")
print("width of the first line:", round(font.measure("سلام دنیا", 56).width))
the font has the letter seen: yes
width of the first line: 131

Mixed text
A line that has Latin words or numbers inside Persian is laid out in the right order too: the Persian runs right to left, the Latin words and the digits keep their own left-to-right order, and the line as a whole reads from the right. The third line of the example is one such line.
Alignment
Right-to-left text is usually aligned to the right edge, so the example draws with the right alignment and x set to the right edge of the text. The default alignment, left, puts x on the left edge of every line, which is what Latin text wants.
The font has to have the letters
A font draws only what it has. A Latin-only font has no Arabic letters, so Persian text in it comes out as empty boxes (the font's .notdef glyph). has_glyph tells you whether a font has a given character, and the sample font Vazirmatn has Persian, Arabic and Latin. The details of how a text becomes glyphs are on the glyphs and shaping page.
API at a glance
| Draw right-to-left text | img.draw_text(text, font, px, x, y, align="right") |
|---|---|
| Measure it | font.measure(text, px) |
| Does the font have a letter | font.has_glyph("س") |