I am trying to add a page number in the footer of a word doc using python-docx. So far, I haven't been able to find how to do so. This question address how to find a page number (or how you cannot). This one talks about creating a template and adding page numbers there. Is there a way to add page numbers on a document I created using doc = Document()?
>>> document = Document() >>> section = document. sections[0] >>> header = section. header >>> header <docx. section.
Win32com → work with MS Word .doc files Despite the ease of use, the python-docx module cannot take in the aging . doc extension, and believe it or not, . doc file is still the go-to word processor for lots of stakeholders (despite the . docx being around for over a decade).
Thanks to Syafiqur__ and scanny, I came up with a solution to add page numbers.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With