[Python] How do I change Heading font face and size in python-docx?

Discussão em 'Python' iniciado por Stack, Junho 22, 2025.

  1. Stack

    Stack Membro Participativo

    I filed this as a python-docx issue: https://github.com/python-openxml/python-docx/issues/805 but was requested to open a discussion here.

    https://python-docx.readthedocs.io/en/latest/user/styles-using.html implies that I should be able to change Heading font styles like this:

    font = doc.styles['Heading 1'].font
    font.name = 'Times New Roman'
    font.size = docx.shared.Pt(16)


    But that doesn't work: the resulting document uses Calibri for all headings. (They're also blue and Heading 1 has an underline, which I also need to eliminate somehow.)

    It also doesn't work to change the font on a specific heading, nor to delete the latent_styles for the headings.

    Here's a test program that tries all three methods, but the Headings 1 and 2 still come out as blue Calibri despite all attempts to change them to Times New Roman:

    import docx

    doc = docx.Document()

    # Deleting heading latent styles seems to do nothing:
    latent_styles = doc.styles.latent_styles
    latent_styles['Heading 1'].delete()
    latent_styles['Heading 2'].delete()

    # Setting the Normal font works:
    font = doc.styles['Normal'].font
    font.name = 'Times New Roman'
    font.size = docx.shared.Pt(12)

    # Setting heading styles doesn't do anything:
    # they all still end up as blue Calibri.
    font = doc.styles['Heading 1'].font
    font.name = 'Times New Roman'
    font.size = docx.shared.Pt(16)

    font = doc.styles['Heading 2'].font
    font.name = 'Times New Roman'
    font.size = docx.shared.Pt(14)

    doc.add_heading("Heading 0", 0)
    doc.add_paragraph('Here is a paragraph of text.')
    doc.add_heading("Heading 1", 1)
    doc.add_paragraph('Here is a paragraph of text.')
    doc.add_heading("Heading 2", 2)
    doc.add_paragraph('Here is a paragraph of text.')

    # It also doesn't work to change the style of a specific heading:
    heading = doc.add_heading("Another Heading 1", 1)
    heading.style.font.name = "Times New Roman"
    doc.add_paragraph('Here is a paragraph of text.')

    doc.save('test.docx')


    Can't change "heading 1" font name using docx mentions this as a bug, and suggests creating a new style as a workaround. A simpler workaround is to create runs inside normal paragraph text, then style those runs. But it seems like it would be better to use standard elements like "Heading 1" if it was possible to style those headings as something other than blue Calibri ... and the documentation implies this is possible.

    Continue reading...

Compartilhe esta Página