1
votes

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)

Popup window


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.

1

1 Answers

1
votes

The behavior described in the question is by design. Updating of fields is a potential security risk - there are some field types that can access external content. Therefore, dynamic content generated outside the Word UI needs user confirmation to update.

I know of only three ways to prevent displaying the prompt

  1. Calculate the values and insert the field result during document generation. The fields will still be updatable, in the normal manner, but won't require updating when the document is opened the first time. (Leave out the code in the second part of the question.)

  2. Use Word Automation Services (requires on-premise SharePoint) to open the document, which will update the fields (as in the second part of the question).

  3. Include a VBA project that performs the field update in an AutoOpen macro. This, of course, means the document type must be macro-enabled (docm) and that macros are allowed to execute on the target installation (also a security risk, of course).