Can't change “heading 1” font name using docx

2019-07-18 19:22发布

I am using the following script :

header = self.document.add_paragraph(style='Heading 1')
header.style.font.name = 'Arial'
header.style.font.size = Pt(16)
header.add_run('Header One')

The result is that "Header One" get 'Calibri'.

1条回答
叛逆
2楼-- · 2019-07-18 19:38

This is a legitimate bug even with python-docx version 0.8.5. If you were to change the font name of the style 'Normal', it works (as shown in the examples on the python-docx manuals), but this does not work for the 'Heading 1' style.

One workaround is to create a new heading style that takes Heading 1 as a base style and then modify the new style's font name & size:

from docx.enum.style import WD_STYLE_TYPE

styles = self.document.styles
new_heading_style = styles.add_style('New Heading', WD_STYLE_TYPE.PARAGRAPH)
new_heading_style.base_style = styles['Heading 1']
font = new_heading_style.font
font.name = 'Arial'
font.size = Pt(16)
self.document.add_paragraph('Header One', style='New Heading')
查看更多
登录 后发表回答