如何在 python-docx 中设置字体间距或如何向 w:rPr 添加元素?
//
python-docx
中没有对此设置的 API 支持。
添加
<w:spacing>
元素将起作用(如果 Word 就是这么做的),但是子元素出现的顺序通常在 WordprocessingML 中很重要(XML 架构 .docx 文件遵循)。如果您没有在 w:spacing
子元素中以正确的顺序获取 w:rPr
元素,或者在已经存在的情况下添加一个,则会触发修复错误。
所以你需要这样的东西:
def run_set_spacing(run, value: int):
"""Set the font spacing for `run` to `value` in twips.
A twip is a "twentieth of an imperial point", so 1/1440 in.
"""
def get_or_add_spacing(rPr):
# --- check if `w:spacing` child already exists ---
spacings = rPr.xpath("./w:spacing")
# --- return that if so ---
if spacings:
return spacings[0]
# --- otherwise create one ---
spacing = OxmlElement("w:spacing")
rPr.insert_element_before(
spacing,
*(
"w:w",
"w:kern",
"w:position",
"w:sz",
"w:szCs",
"w:highlight",
"w:u",
"w:effect",
"w:bdr",
"w:shd",
"w:fitText",
"w:vertAlign",
"w:rtl",
"w:cs",
"w:em",
"w:lang",
"w:eastAsianLayout",
"w:specVanish",
"w:oMath",
),
)
return spacing
rPr = run._r.get_or_add_rPr()
spacing = get_or_add_spacing(rPr)
spacing.set("val", str(value))
然后您可以为每次需要该设置的运行调用此方法,如下所示:
run_set_spacing(run, 200)
我尝试了scanny的答案,但没有成功。但输出文档 XML
试试这个
from docx.oxml.ns import qn
spacing.set(qn('w:val'), str(value))
这就是我在新文档中设置“普通”文本间距的方法。 当然这个答案利用了旧的回复
# create a new Document
doc = Document()
style = doc.styles['Normal']
spacing = OxmlElement("w:spacing")
spacing.set(qn('w:val'), str("-12"))
style.font._element.rPr.insert_element_before(
spacing,
*("w:w", "w:kern", "w:position", "w:sz", "w:szCs", "w:highlight", "w:u", "w:effect", "w:bdr", "w:shd",
"w:fitText", "w:vertAlign", "w:rtl", "w:cs", "w:em", "w:lang", "w:eastAsianLayout", "w:specVanish", "w:oMath",
),
)