Search code examples
pythonpython-docx

Is it possible to align a paragraph vertically and horizontally in python-docx?


I know you can align a paragraph horizontally with WD_ALIGN_PARAGRAPH, I just wanted to know if it is possible to do something like in Word: "Layout > Align > Align Middle" to vertically center text on a document in python-docx.


Solution

  • There currently exists no way to do this in the library. HOWEVER, I found out that by aligning text in an existing document, then opening it with python-docx, you can simply edit the text and it will retain its formatting.

    enter image description here

    from docx import document
    
    document = Document('template.docx')
    # This just grabs the first paragraph, code assumes you've already applied formatting.
    document.paragraphs[0].text = "Example Text"
    document.save('output.docx')