docx4j

Editing MS Word "Document Info" field in Sdt Content by docx4j


I have a template of a docx document and using docx4j I would like to change the content of Sdt Content. The Sdt Block contains the title of the document from the MS Word "Document Info" field, which is displayed in the header and on the first page. Unfortunately, when I try to change the <w:t> value in <w:sdtContent> in the XML header file, the value does not update in the generated document. Editing other <w:t> elements without Sdt Block works fine for me.

I would like to ask how can I update the text in Std Content which contains "Document Info" field? How are these header and first page fields with title related to each other in the source files (they always display the same values)?


Solution

  • Such an SDT will look something like:

    <w:sdt>
      <w:sdtPr>
        <w:alias w:val="Title"/>
        <w:dataBinding w:prefixMappings="xmlns:ns0='http://purl.org/dc/elements/1.1/' xmlns:ns1='http://schemas.openxmlformats.org/package/2006/metadata/core-properties' " w:xpath="/ns1:coreProperties[1]/ns0:title[1]" w:storeItemID="{6C3C8BC8-F283-45AE-878A-BAB7291924A1}"/>
        <w:text/>
      </w:sdtPr>
      <w:sdtContent>
        <w:p>
          <w:r>
            <w:t>My title</w:t>
          </w:r>
        </w:p>
      </w:sdtContent>
    </w:sdt>
    

    Notice the databinding element; with attribute w:xpath="/ns1:coreProperties[1]/ns0:title[1]"

    Word will attempt to update the contents of any SDT which has a databinding element, from its corresponding store (given by w:storeItemID). (That is, updating the text as you describe only works if there is no databinding element)

    In this case, it updates this SDT using what it finds in /docProps/core.xml, which looks something like:

    <cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" >
      <dc:title>My title</dc:title>
    

    For clues on how to work with that part using docx4j, see https://github.com/plutext/docx4j/blob/VERSION_11_4_8/docx4j-samples-docx4j/src/main/java/org/docx4j/samples/DocProps.java