python-docx does not apply font size when changing text direction to RTL

79 views Asked by At

I want to change the direction to RTL since I write in Kurdish which uses Arabic numerals. but whenever I apply run.font.rtl = True, it will cancel the font size run.font.size = Pt(20)

How can I fix that issue?

for paragraph in doc.paragraphs:
    if '{text}' in paragraph.text:
        paragraph.text = paragraph.text.replace('{text}', text[i].strip())
        for run in paragraph.runs:
            run.font.size = Pt(20)
            run.font.name = 'Arial'
            run.font.rtl = True
1

There are 1 answers

0
Hama Sabah On BEST ANSWER

Here is the solution I found, just add this method inside your code and pass it your run and other requirement parameters.

def fix_cs_formatting_runs( run_to_fix ,user_cs_font_size, user_cs_font_name, user_is_bold ):  #cs: complex script, ex, arabic
    rpr = run_to_fix.element.get_or_add_rPr()
    rFonts = rpr.get_or_add_rFonts()
    rpr.get_or_add_sz()
    szCs = OxmlElement('w:szCs') # size
    sz= OxmlElement('w:sz') # size
    rpr.append(szCs)
    rpr.append(sz)
    lang = OxmlElement('w:lang') #language
    rpr.append(lang)
    if user_is_bold:
        bCs = OxmlElement('w:bCs') #bold the complex language
        rpr.append(bCs)
        bCs.set(qn('w:val'), "True")
        b = OxmlElement('w:b')  # bold the english
        rpr.append(b)
        b.set(qn('w:val'), "True")
    sz.set(qn('w:val'), str(int(user_cs_font_size * 2)))
    szCs.set(qn('w:val'), str(int(user_cs_font_size * 2)))
    lang.set(qn('w:bidi'), 'ar-SA')
    rFonts.set(qn('w:cs'), user_cs_font_name)
    rFonts.set(qn('w:ascii'), user_cs_font_name) #you can change the font for the other language
    rFonts.set(qn('w:hAnsi'), user_cs_font_name) #you can change the font for the other language

Example:

for paragraph in doc.paragraphs:
    if '{text}' in paragraph.text:
        paragraph.text = paragraph.text.replace('{text}', text[i].strip())
        for run in paragraph.runs:
            fix_cs_formatting_runs(run,20,"Arial",False)
            font = run.font
            font.name = 'Arial'
            font.cs_size = Pt(20)
            font.rtl = True