3.1 自定义字符间距-无效参考

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Pt

# 调整pt设置字间距
def SetParagraphCharSpaceByPt(run, pt=1):
    '''
    通过修改word源码方式, 添加w:spacing标签
    直接通过调整pt来设置字符间距
    '''
    # 获取或创建<w:rPr>元素
    rPr = run._element.find(qn('w:rPr'))
    if rPr is None:
        rPr = OxmlElement('w:rPr')
        run._element.insert(0, rPr)

    # 创建<w:spacing>元素
    spaceChar = OxmlElement('w:spacing')
    spaceChar.set(qn('w:val'), str(-20))

    # 添加<w:spacing>到<w:rPr>
    rPr.append(spaceChar)

def AddParagraph(doc, text):
    p = doc.add_paragraph()
    run = p.add_run(text)
    return p, run

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))
    spacing.set(qn('w:val'), str(value))

if __name__ == '__main__':
    doc = Document()

    # 段落字段样式
    p1 = doc.add_paragraph('')
    run = p1.add_run('这是段落1:\n')
    # p, run = AddParagraph(doc, text='这是一个段落')
    run_set_spacing(run, 1000)
    # SetParagraphCharSpaceByPt(run=run, pt=200)
    doc.save('./办公自动化/files/word_test.docx')