I have an application that uses docx to put pictures in a table. Everything works fine except that the table goes from the left margin to the right margin.
If I manually create a table in Word, I can right click the table to get to "Table Properties". Then under the "Table" tab, in "Size", I can click the "Preferred width" check box and set the width to any size you want. Since the Paragraph is set to center, the table is centered between the margins but does not extend to the margins.
I can't seem find a similar mechanism in docx. Is there one? Or is there another way to accomplish the same thing?
Try setting each cell to the desired width for the column it is in.
Interpretation of values like "table-width" and "column-width" varies between clients (e.g. Microsoft Word, Open Office, Google Docs) and setting the cell width seems to be the lowest common denominator. You just have to loop through the table and set all of them. This other SO answer gives some example code: https://stackoverflow.com/a/43053996/1902513
On the centering, I'm not sure what you're doing there that works (by hand) in Word. You mention "... the Paragraph ..." but each cell can have one or more paragraphs, so I'm not sure which one you're centering (also, a table cannot be embedded in a paragraph). I suspect you're actually centering the table, which probably uses the same toolbar button.
I think this is what you want in python-docx
:
from docx.enum.table import WD_TABLE_ALIGNMENT
table.alignment = WD_TABLE_ALIGNMENT.CENTER