John Paul Hayes John Paul Hayes - 1 year ago 49
Python Question

Is there a way of changing a word documents font using python-docx?

I'm looking for a pythonic way of changing an entire documents' font to Arial (10pt) as the current document has a mixture of a couple of fonts.

Is this possible?

Thanks in advance!

Answer Source

There are a couple different ways to approach this because it's a more complex problem than it might first appear.

The "apparent" font, or perhaps more precisely the "effective" font for a text item in Word is calculated from the style hierarchy much the same way CSS works for HTML.

The final level in the style hierarchy, which overrides all the higher levels, is directly applied formatting at the Run level. So if you set a particular run to have Arial 10pt, it will appear that way no matter what.

Above that level you have paragraph default formatting, character style, paragraph style, inherited style (base style of applied style) and document default, probably not in exactly that order. So you can see my point about complexity. All these things would need to be realigned to do it "properly" (which definitely has merits for later editability).

But if you want a brute force approach, just apply an explicit font to each run in the document. Perhaps a bit better would be to actually remove explicit font settings on each run, and let the style or document default rule the effective font.

Iterating the runs looks something like this aircode:

document = Document('my-document.docx')
for paragraph in document.paragraphs:
    for run in paragraph.runs:
        font = run.font
         # ---do font-related things---

for table in document.tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    font = run.font
                    # ---do font-related things---

Probably want to make that prettier by extracting a few functions, but that's the gist.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download