Search code examples
python-2.7python-docx

Python-docx set the text direction RTL


I am trying to create a docunent with RTL (Right-To-Left) text direction

def printExam():

  #get the exam questions 

  rows = db(db.exam_questions.exam == request.vars.exam).select()

  # create the documnet
  document = Document()
  document.add_heading(u"أختبار", 0)

  #for row in rows:
  row = rows[0] 
  run = document.add_paragraph().add_run(str(row.question.questionText).decode( "utf-8" ))
  font = run.font
  font.rtl = True

I got the following exception:

Traceback (most recent call last):
  File "C:\Users\web2py-src\gluon\restricted.py", line 227, in restricted
    exec ccode in environment
  File "C:/Users/web2py-src/applications/draft/controllers/question.py", line 96, in <module>
  File "C:\Users\web2py-src\gluon\globals.py", line 417, in <lambda>
    self._caller = lambda f: f()
  File "C:/Users/web2py-src/applications/draft/controllers/question.py", line 68, in printExam
    font.rtl = True
AttributeError: 'Font' object attribute 'rtl' is read-only

Solution

  • No custom style has been defined on your paragraph so a default latent style is applied and this kind of style is read-only because it has no real definition in the document.

    Apply a custom style on your run or your paragraph and you will be able to customize it. For a run, you have to create character style (WD_STYLE_TYPE.CHARACTER).

    # create the document and the custom style
    document = Document()
    mystyle = document.styles.add_style('mystyle', WD_STYLE_TYPE.CHARACTER)
    ...
    ...
    # apply the custom on the run
    run.style = mystyle
    font = run.font
    font.rtl = True