Skip to content

Changing Heading font doesn't work #805

@akkana

Description

@akkana

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.

Github won't let me attach a .py file, so here's my sample standalone program that tries all three methods, but all of the headings come out as blue Calibri despite all attempts to change them to Times New Roman.

#!/usr/bin/env python3

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('/tmp/test.docx')

The document produced:
test.docx

https://stackoverflow.com/questions/37220754/cant-change-heading-1-font-name-using-docx mentions this as a known bug, but the only issues I found here were 390 which seems to be dismissed as an Asian font issue, and 366, I'm not sure if that's the same problem or not.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions