首页 > 解决方案 > 使用 python-docx 添加页码

问题描述

我正在尝试使用 python-docx 在 word doc 的页脚中添加页码。到目前为止,我还没有找到如何做到这一点。这个问题解决了如何找到页码(或者你怎么不能)。这个谈论创建一个模板并在那里添加页码。有没有办法在我使用 doc = Document() 创建的文档上添加页码?

标签: pythonms-wordpython-docx

解决方案


感谢 Syafiqur__ 和 scanny,我想出了一个添加页码的解决方案。

def create_element(name):
    return OxmlElement(name)

def create_attribute(element, name, value):
    element.set(ns.qn(name), value)


def add_page_number(run):
    fldChar1 = create_element('w:fldChar')
    create_attribute(fldChar1, 'w:fldCharType', 'begin')

    instrText = create_element('w:instrText')
    create_attribute(instrText, 'xml:space', 'preserve')
    instrText.text = "PAGE"

    fldChar2 = create_element('w:fldChar')
    create_attribute(fldChar2, 'w:fldCharType', 'end')

    run._r.append(fldChar1)
    run._r.append(instrText)
    run._r.append(fldChar2)

doc = Document()
add_page_number(doc.sections[0].footer.paragraphs[0].add_run())
doc.save("your_doc.docx")

推荐阅读