Search code examples
pythonpython-docx

How to properly indent with python-docx?


Indentation seems pretty straightforward, and terminal prints back the proper indentation, but the same indentation is not reflected in my saved Word docx.
Am I doing something wrong here?

from docx import Document
from docx.shared import Inches
    
worddoc = Document()
paragraph = worddoc.add_paragraph('Left Indent Test')
paragraph.left_indent = Inches(.25)
print(paragraph.left_indent.inches)
    
worddoc.save('left_indent.docx')

Solution

  • This turns out to be a documentation error.

    If you use the new API it works:

    paragraph.paragraph_format.left_indent = Inches(0.25)
    

    The left_indent property was moved to the paragraph_format "sub-object" a couple releases back as the ParagraphFormat class is used by both the Paragraph and ParagraphStyle objects.

    If you'll file a bug report in the python-docx issue tracker on GitHub we'll get the documentation updated next time we're in there.