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

♀尐吖头ヾ 提交于 2019-12-23 17:53:05

问题


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:


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')


来源:https://stackoverflow.com/questions/37220754/cant-change-heading-1-font-name-using-docx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!