[转载]python docx 插入页码
2022-7-25 17:00
阅读:4839
在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 运行
转载本文请联系原作者获取授权,同时请注明本文来自姚程科学网博客。
链接地址:https://wap.sciencenet.cn/blog-531760-1348719.html?mobile=1
收藏
当前推荐数:0
推荐到博客首页
网友评论0 条评论