无法更改“标题 1"使用 docx 的字体名称 [英] Can't change "heading 1" font name using docx

查看:34
本文介绍了无法更改“标题 1"使用 docx 的字体名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下脚本:

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

结果是Header One"得到Calibri".

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

推荐答案

即使使用 python-docx 0.8.5 版,这也是一个合法的错误.如果您要更改Normal"样式的字体名称,它会起作用(如 python-docx 手册中的示例所示),但这不适用于Heading 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.

一种解决方法是创建一个新的标题样式,将标题 1 作为基本样式,然后修改新样式的字体名称 &尺寸:

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

这篇关于无法更改“标题 1"使用 docx 的字体名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆