Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add page number using python-docx

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()?

like image 694
max_max_mir Avatar asked Jun 19 '19 01:06

max_max_mir


People also ask

How do you add a header to a docx in python?

>>> document = Document() >>> section = document. sections[0] >>> header = section. header >>> header <docx. section.

Does python-docx work with Doc?

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).


1 Answers

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")
like image 123
max_max_mir Avatar answered Sep 16 '22 22:09

max_max_mir