I am working on a Python program that needs to add caption texts in MS Word to Figures and Tables (with numbering). After adding the field however, the field does not appear in my Word-document until I update the field (it's just an empty space in my document, until I update the field, then it jumps to e.g. '2').
This is my code for adding the field:
def add_caption_number(self, field_code):
""" Add a caption number for the field
:argument
field_code: [string] the type of field e.g. 'Figure', 'Table'...
"""
# Set the pointer to the last paragraph (e.g. the 'Figure ' caption text)
run = self.last_paragraph.add_run()
r = run._r
# Add a Figure Number field xml element
fldChar = OxmlElement("w:fldChar")
fldChar.set(qn("w:fldCharType"), "begin")
r.append(fldChar)
instrText = OxmlElement("w:instrText")
instrText.text = " SEQ %s \* ARABIC" % field_code
r.append(instrText)
fldChar = OxmlElement("w:fldChar")
fldChar.set(qn("w:fldCharType"), "end")
r.append(fldChar)
self.last_paragraph
is the last paragraph that has been added and field_code
is to select whether to add a Figure or a Table caption number.
I have found an example for updating the fields, but this opens the following window upon opening the document:
def update_fields(save_path):
""" Automatically updates the fields when opening the word document """
namespace = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
doc = DocxTemplate(save_path)
element_updatefields = lxml.etree.SubElement(
doc.settings.element, f"{namespace}updateFields"
)
element_updatefields.set(f"{namespace}val", "true")
doc.save(save_path)
Is there a way to do this without the popup window and without adding macros to the Word document? This needs to work on MacOS and Windows btw.