||
在python docx中实现word插入页码
主要使用的是页脚功能。
另外,用到了docx的oxml命令。
#https://baijiahao.baidu.com/s?id=1665454009794833226&wfr=spider&for=pc #https://stackoverflow.com/questions/50776715/setting-pgnumtype-property-in-python-docx-is-without-effect import docx from docx.oxml import OxmlElement from docx.oxml.ns import qn from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.shared import RGBColor from docx.shared import Inches, Pt def AddFooterNumber(run): fldChar1 = OxmlElement('w:fldChar') # creates a new element fldChar1.set(qn('w:fldCharType'), 'begin') # sets attribute on element instrText = OxmlElement('w:instrText') instrText.set(qn('xml:space'), 'preserve') # sets attribute on element instrText.text = 'Page' fldChar2 = OxmlElement('w:fldChar') fldChar2.set(qn('w:fldCharType'), 'separate') t = OxmlElement('w:t') t.text = "Seq" fldChar2.append(t) fldChar4 = OxmlElement('w:fldChar') fldChar4.set(qn('w:fldCharType'), 'end') r_element = run._r r_element.append(fldChar1) r_element.append(instrText) r_element.append(fldChar2) r_element.append(fldChar4) def InsertPageNumber(Doc): footer = Doc.sections[0].footer # 获取第一个节的页脚 footer.is_linked_to_previous = True #编号续前一节 paragraph = footer.paragraphs[0] # 获取页脚的第一个段落 paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER#页脚居中对齐 run_footer=paragraph.add_run() # 添加页脚内容 AddFooterNumber(run_footer) font = run_footer.font font.name = 'Times New Roman'#新罗马字体 font.size = Pt(10)#10号字体 font.bold = True#加粗 #EndDef if __name__=='__main__': Doc = docx.Document() InsertPageNumber(Doc) Doc.save('test.docx') # 保存文档 |
将上述代码保存在test.py中
在cmd环境,用 python test.py 运行
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-12-23 18:42
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社