我正在尝试使用 python-docx 在 word 文档的页脚中添加页码。到目前为止,我还没有找到如何做到这一点。 This问题地址如何找到页码(或如何不能)。 This一个谈论创建模板并在那里添加页码。有没有办法在我使用 doc = Document() 创建的文档上添加页码?
最佳答案
感谢 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")
关于python - 使用 python-docx 添加页码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56658872/