Updating Document Control field resets the format

I am using aspose word 20.11 jdk17 to update the content control tag in the header but its resetting the font.
Do I need to do anything more?
content control issue.zip (35.8 KB)
Appreciate the help.

Thanks
Mahesh

@mp2,

The following Java code can be used to update the text of content control in header of Word document while preserving the existing font formatting:

Document doc = new Document("C:\\temp\\content control issue\\Testing Header Fonts.docx");

// Get the target content control. Or you can get it by Title or Tag properties
HeaderFooter primaryHeader = doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY);
StructuredDocumentTag contentControl = (StructuredDocumentTag) primaryHeader.getChildNodes(NodeType.STRUCTURED_DOCUMENT_TAG, true).get(0);

// Get the first Run of text you want to keep formatting of
Run firstRun = (Run) contentControl.getChildNodes(NodeType.RUN, true).get(0);

// Remove all other nodes
if (firstRun != null)
    for (Node node : (Iterable<Node>) contentControl.getChildNodes(NodeType.ANY, true))
        if (node != firstRun)
            node.remove();

// Update the text of first Run
firstRun.setText(" sample header ");

doc.save("C:\\Temp\\content control issue\\awjava-21.1.docx");

thanks for your prompt reply…

I have different content control tags all over my document i.e. both in headers, footers & body. I am currently updating the tags as shown in the attachment. In this scenario, how can I know the tag is in header and update accordingly?

content control issue.zip (37.1 KB)

@mp2,

You can use Node.getAncestor method to determine whether a content control is inside Header/Footer or Body Story in Word document:

Document doc = new Document("C:\\temp\\Testing Header Fonts.docx");

for (StructuredDocumentTag sdt : (Iterable<StructuredDocumentTag>)
        doc.getChildNodes(NodeType.STRUCTURED_DOCUMENT_TAG, true)) {
    HeaderFooter headerFooter = (HeaderFooter) sdt.getAncestor(NodeType.HEADER_FOOTER);
    if (headerFooter != null) {
        System.out.println(sdt.getTitle() + " <- It is inside header or footer");
    } else {
        Body body = (Body) sdt.getAncestor(NodeType.BODY);
        if (body != null) {
            System.out.println(sdt.getTitle() + " <- It is inside Body");
        }
    }
}

awesome…thank you