1
votes

I am generating a word document from a template using python-docx and I need to update some fields that are embedded in the cover, header and footer sections of the document.

I have searched everywhere and I didn't find any topic explaining how to update fields in MS Word with python-docx. Is it not implemented yet?

Fields I am referring to are the ones located in Advanced Document Properties/Custom.

Fields configured in Advanced Document Properties menu

Adding the fields to the document

Example of fields in the document

2
Can you provide an example?Kasper
Sure, I attach some screenshots: ibb.co/phW44HT ibb.co/8bBDCrx ibb.co/StWb1jXDaniel Serrano
Welcome to SO. Can you add those images into your question using image tool as well as additional information on what you tried. Please refer to How to askVepth
Thank you and sorry for my bad explanation, it is my very first post hereDaniel Serrano

2 Answers

1
votes

Solution 1

user:1902513 or scanny has yet implemented the custom_properties attribute in the main repository of python-docx -- and probably not in the near future as he said no developers are active to modify the repository.

My suggestion is to reinstall the module but from different respository copy made by user:652546 or renejsum; here.

>> source of solution <<

Usage sample is as in this script.

1
votes

Solution 2

You may change the text of respective custom properties by browsing for its keyword.

Example:

from re import compile # regex module to emulate keyword search by pattern 


keyword = re.compile(r'\s*Creator: (?P<creator_name>\w+)\s*')
word_replacement = 'Daniel Serrano'


for _p in doc.paragraphs: # doc = docx.Document(...) 

    found_word = keyword.match(_p.text)

    if found_word: 

        for _r in _p.runs: 
            _r.text = _r.text.replace(
                found_word.group('creator_name'), 
                word_replacement
            )

It is better to avoid set change on _p.text itself although doable as it may reformat the run (ie. bold, italic, underline dropped).