Search code examples
pythonpython-3.xlayoutpython-docx

Trouble with layout on python docx


With the help of stack overflow, I built this code :

from docx import Document

names = ["names1, names2, names3, names4"]
names = ' '.join(names)
dates = ["October 25 2021"]
dates = str(dates)
client = ['client']
client = str(client)

document = Document('filename.docx')

paragraphs = document.paragraphs


paragraph = paragraphs[0].insert_paragraph_before()

paragraph.add_run("       ")
run = paragraph.add_run("To")
run.italic = True
paragraph.add_run("    " + names + "         ")
run = paragraph.add_run("Date")
run.italic = True
paragraph.add_run("  " + dates + "       ")

paragraph.add_run("                                                        ")
paragraph.add_run("Doc 1")
paragraph.add_run("                                                           ")
paragraph.add_run("                                                           ")
run = paragraph.add_run("From")
run.italic = True
paragraph.add_run("    " + names + "         ")
run = paragraph.add_run("Ref")
run.italic = True
paragraph.add_run("  " + client)
paragraphs[0].insert_paragraph_before("                                                                                     ")


document.save('new.docx')

And I obtained that :

output

But I would like something like that :

outputdesired

But I cannot managed to do this layout. I add espaces and so on but it isn't following at all so I must missing something.

Any ideas ?


Solution

  • You have two choices, one is using tab-stops and the other is using a table.

    You might want to experiment briefly in the Word UI to see how each of those two are done. Then the job is just how to recreate that procedure in python-docx.

    Using the tab-stop method (which would be my first choice), you need four tab-stops. The text would be like "tab, "To", tab, "name, name, ...", tab, "Date", tab, "October...". The first tabstop is a right-tab, aligning the end of "to" at maybe .75" or whatever, then a left-aligned tabstop to align the names, right-aligned for "Date" and left-aligned for the date itself.

    Using a table, you just have two rows of four cells each and left and right align the cells accordingly and adjust the cell widths to suit. I'm not sure how you turn off the cell borders in python-docx off the top of my head but I expect it is a table style choice.

    One advantage of the table approach is that a list of names that won't fit on one line will wrap. On the tab approach it will just screw up the formatting if the names run too long.