pythonpython-pptx

Change text direction in python-pptx


I'm using the python‑pptx library to generate PowerPoint presentations on a Linux environment (Python 3.10). I need to add text to the slides, but it must display from right to left (RTL). I have tried the following approaches:

Setting RTL on font runs:
I attempted to set the RTL property with:

run.font.rtl = True

However, this does not change the text direction as expected.

Prepending a Unicode Right-to-Left mark:
I added the Unicode control character \u200F to the beginning of the text, e.g.

text_frame.text = "\u200F" + "lalala"

Unfortunately, the text still appears in LTR order.

Adjusting paragraph alignment:
I set the paragraph alignment to right using:

p.alignment = 2

Yet, this only changes the alignment, not the underlying RTL behavior.

I have also experimented with directly modifying the underlying XML within the PPTX file, but I haven’t been able to achieve consistent results.

Has anyone encountered this issue with RTL text in python‑pptx? What are the recommended workarounds (including any XML editing techniques) to force a presentation generated with python‑pptx to display text in proper RTL format?

Thank you in advance for your help!


Solution

  • Microsoft Office provides bidirectional writing only when a language which needs this is listed under Office authoring languages and proofing. See Change the language Office uses in its menus and proofing tools.

    The property rtl for right-to-left writing is a paragraph-property, not a character-property. Not clear why Python pptx programmers thought it is the latter.

    So, for me, having hebrew listed under Office authoring languages and proofing, the following works and produces the result shown.

    from pptx import Presentation
    from pptx.util import Inches, Pt
    
    prs = Presentation()
    blank_slide_layout = prs.slide_layouts[6]
    slide = prs.slides.add_slide(blank_slide_layout)
    
    left = top = Inches(1)
    width = Inches(7)
    height = Inches(3)
    txBox = slide.shapes.add_textbox(left, top, width, height)
    tf = txBox.text_frame
    
    p = tf.paragraphs[0]
    p.text = "Hello, world"
    p.font.size = Pt(40)
    
    p = tf.add_paragraph()
    p.text = "שלום, עולם"
    p.font.size = Pt(40)
    p._pPr.set('algn', 'r')
    p._pPr.set('rtl', '1')
    
    p = tf.add_paragraph()
    p.text = "Hello, world again"
    p.font.size = Pt(40)
    
    p = tf.add_paragraph()
    p.text = "Lorem ipsum semit dolor..."
    p.font.size = Pt(40)
    p._pPr.set('algn', 'r')
    p._pPr.set('rtl', '1')
    
    prs.save('test.pptx')
    

    enter image description here

    Note: It is bidirectional writing, thus property rtl changes writing direction. Do not expect it turns the glyphs of the letters. Thus Lorem ipsum semit dolor... will not appear like so: enter image description here