7

I am using python docx library to manipulate a word document. However I can't find how to align a line to the center in the documents page of that library. I can't find by google either.

    from docx import Document
    document = Document()
    p = document.add_paragraph('A plain paragraph having some ')
    p.add_run('bold').bold = True
    p.add_run(' and some ')
    p.add_run('italic.').italic = True

How can I align the text in docx?

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
Levent Altunöz
  • 273
  • 1
  • 3
  • 10

2 Answers2

14

With the new version of python-docx 0.7 https://github.com/python-openxml/python-docx/commit/158f2121bcd2c58b258dec1b83f8fef15316de19 Add feature #51: Paragraph.alignment (read/write) Now it is possible to align a paragraph as here: http://python-docx.readthedocs.org/en/latest/dev/analysis/features/par-alignment.html

 paragraph = document.add_paragraph("This is a text")
 paragraph.alignment = 0 # for left, 1 for center, 2 right, 3 justify ....

edit from comments

actually it is 0 for left, 1 for center, 2 for right

edit 2 from comments

You shouldn't hard code magic numbers like this. Use WD_ALIGN_PARAGRAPH.CENTER to get the correct value for centering, etc. To do this use the following import

from docx.enum.text import WD_ALIGN_PARAGRAPH 
barshopen
  • 1,190
  • 2
  • 15
  • 28
Levent Altunöz
  • 273
  • 1
  • 3
  • 10
  • 3
    actually it is 0 for left, 1 for center, 2 for right – blissini Mar 28 '15 at 16:10
  • 5
    You shouldn't hard code magic numbers like this. Use `WD_ALIGN_PARAGRAPH.CENTER` to get the correct value for centering, etc. To do this use the following import: `from docx.enum.text import WD_ALIGN_PARAGRAPH` – André C. Andersen Nov 01 '15 at 17:18
  • 1
    Is there a way to add the alignment to a specific `run` part of the paragraph rather than the paragraph as a whole? – tanmay_garg Feb 01 '22 at 19:21
3
p = document.add_paragraph('A plain paragraph having some ',style='BodyText', breakbefore=False, jc='left')# @param string jc: Paragraph alignment, possible values:left, center, right, both (justified), ...

for reference see this reference at def paragraph read the documentation

sundar nataraj
  • 8,524
  • 2
  • 34
  • 46