Search code examples
pythonpython-docx

centering text with python docx


I need to center a small head of text that is embedded in a table.

traditionally you would center text using the following code

from docx.enum.text import WD_ALIGN_PARAGRAPH

paragraph = document.add_paragraph("text here")
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

however because I also need to change font and size I need to add that text to an add_run() function. and that means that the above code no longer works, it doesn't even give an error it just dose nothing.

my current code is

from docx.enum.text import WD_ALIGN_PARAGRAPH
...
paragraph = row.cells[idx].add_paragraph().add_run("text here")
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER    #this line dose not work

Another thing that is restricting me from getting the result needed is the fact that paragraph = document.add_paragraph() will actually add a line to the table which will throw off the dimentions of the table meaning the following code will not be satisfactory:

paragraph = document.add_paragraph()
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
paragraph.add_run("text here")

I would need it to be done in one line as to avoid an extra line being added to the table.

So in summery how do I center a line of text that has been embedded in an add_run() function in the same line with python docx?


Solution

  • Edited to demo centering text in tables

    from docx import Document
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    
    document = Document('demo.docx')
    
    for table in document.tables:
        for row in table.rows:
            for cell in row.cells:
                for para in cell.paragraphs:
                    para.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    para.add_run("text here")
    
    document.save('demo.docx')