Home > Blockchain >  Can't print specific character using FPDF in python
Can't print specific character using FPDF in python

Time:03-22

I am trying to print this word in Arabic

الله

I tried many fonts but still, the FPDF is printing it as box (tofu box, is what it is called I guess)

from fpdf import FPDF
import arabic_reshaper

pdf = FPDF('P', 'mm', "A4")
pdf.add_page()
pdf.add_font('dejavu', "", "DejaVuSansCondensed.ttf", uni=True)
pdf.set_font('dejavu', '', 10)
pdf.multi_cell(69, 5, arabic_reshaper.reshape("الله"), "", ln=1)
pdf.output("mypdf.pdf")

If I dont use arabic reshaper the result is enter image description here which is not the correct word as entered.

Result is this boxenter image description here

CodePudding user response:

I think the solution is something like this:

from fpdf import FPDF
from arabic_reshaper import reshape
from bidi.algorithm import get_display
from warnings import filterwarnings

pdf = FPDF()

pdf.add_page()
pdf.add_font("NotoSansArabic", style="", fname="NotoSansArabic-Regular.ttf", uni=True)
pdf.set_font('NotoSansArabic', '', 10)
original_text = 'الله'

reshaped_text = reshape(original_text)
bidi_text = get_display(reshaped_text)

pdf.write(8, original_text)
pdf.ln(8)

pdf.write(8, reshaped_text)
pdf.ln(8)

pdf.write(8, bidi_text)
pdf.ln(8)

filterwarnings('ignore')
pdf.output('mypdf.pdf')
filterwarnings('default')

I could not get it to work with the font you provided, but the Google font used here can be downloaded for free. It appears some part of 'الله' is causing the issue, because something like 'مرحبا' does work in Deja Vu Sans Condensed.

The filterwarnings("ignore") is there because the pdf.output generates warnings which seem not to affect the result, but you may wish to look into them instead of just ignoring them:

[..]\site-packages\fpdf\ttfonts.py:670: UserWarning: cmap value too big/small: -65241
  warnings.warn("cmap value too big/small: %s" % cm)

However, the script now appears to do what you want, also showing the initial look and the reshaped look before fixing the direction.

Your question is different, but I found the solution here: Problem writing a mix of English and Arabic text in PDF using Python pyFPDF. The warning occurred with Deja Vu as well, so it's not caused by the specific font.

  • Related