Mohamed Hamdy
Mohamed Hamdy

Reputation: 147

How to enable Arabic support in reportlab.pdfgen using drawString()?

I have qr code in PIL Image and some Arabic text and trying to put the qr Image on a pdf file. I'm using reportlab.pdfgen's canvas.

After a lot of searching I found arabic_reshaper, someone's project that didn't work, and after reading the source code of textobject.py I found that I need to install pyfribidi, installed it, and used drawString(x,y,"مربحا",RTL) nothing happens.

I'm using arabic_reshaper as described in the repository, and the RTL from pyfribidi

import arabic_reshaper

reshaped = arabic_reshaper.reshape(exam_name)
c.drawString(x - 100, y - 20, reshaped, direction=RTL)

The result is always the same, as you can see on the right the English strings appear normally, the Arabic ones appear as black pixels :

a busy cat

If you have any other recommendations for another library that will be also appreciated.

Upvotes: 2

Views: 2427

Answers (1)

Mohamed Hamdy
Mohamed Hamdy

Reputation: 147

Thanks to some developers who noted that the problem is caused by the font I was able to fix it.

First I downloaded an Arabic TTF font, and as I'm using linux I placed it in '/usr/share/fonts' then I did the following:

import reportlab
import arabic_reshaper
from bidi.algorithm import get_display
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
// BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

reportlab.rl_config.TTFSearchPath.append(str(settings.BASE_DIR))
pdfmetrics.registerFont(TTFont('Arabic', '/usr/share/fonts/tradbdo.TTF'))

ar = arabic_reshaper.reshape(u'العربية')
ar = get_display(ar)
canvas.setFont('Arabic', 32)
canvas.drawString(x - 100, y, ar)

and now everything is working just fine.

Read this answer carefully.

Upvotes: 6

Related Questions