2

I am trying to write some text to a docx file using python-docx. I want to align the text from right to left and I have added a style for that, which is not working.

Here's the code:

from docx.enum.style import WD_STYLE_TYPE

missingwords= Document()
styles = missingwords.styles
style = missingwords.styles.add_style('rtl', WD_STYLE_TYPE.PARAGRAPH)
style.font.rtl = True

paragraph =missingwords.add_paragraph("Hello world",style='rtl')
Rajat
  • 647
  • 3
  • 10
  • 30
  • Have you looked at [this question](https://stackoverflow.com/questions/24031011/python-docx-library-text-align)? – Ollu_ Apr 16 '18 at 15:52
  • Yes, its working with that solution. But i have to add "paragraph.alignment = 0 " after adding every single paragraph. So i was trying to find a better solution to reduce line of codes. – Rajat Apr 16 '18 at 15:59

1 Answers1

3

I haven't gotten around to playing with docx yet (I've mostly used Excel python modules), but based on the documentation here it's looking like you're modifying the wrong property of style. The Font property, per this definition of the rtl property, would only modify an added run (via myparagraph.add_run("Hello World", style = "rtl")).As far as I can tell, the code you're looking for is:

missingwords = Document()
style = missingwords.styles.add_style('rtl', WD_STYLE_TYPE.PARAGRAPH)
style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT

And then you can go ahead and add the paragraph like you were

paragraph = missingwords.add_paragraph("Hello world",style='rtl')

Again, just going off the documentation, so let me know if that works.

Reid Ballard
  • 1,480
  • 14
  • 19