python - 使用 python-docx 添加页码
问题描述
我正在尝试使用 python-docx 在 word doc 的页脚中添加页码。到目前为止,我还没有找到如何做到这一点。这个问题解决了如何找到页码(或者你怎么不能)。这个谈论创建一个模板并在那里添加页码。有没有办法在我使用 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 - RSS 提要只用 Python 抓取今天
- sas - SAS:proc hpbin 函数
- python - 使用python仅解析字符串中的特定字符
- java - 将二维数组转换为具有节点和边的图
- python - Discord.py: How to wait for new message in channel and use its content for another embed
- java - 打开失败:android Q 中的 EACCES (Permission denied) 和 Targeting android 11
- php - json图像上传测试并从android恢复图像
- apache-flink - Apacheflink 的 DataStream API 如何支持事件的批处理
- javascript - 有没有办法避免这段代码中的嵌套循环?
- flutter - 如何在 SingleChildScrollView 内的列内居中小部件