My requirement is to replace a specific content control in the document with an HTML text using docx4j. I would like to see the replaced text to retain the formatting on the final document.
I wrote some code where I am able to identify the tag/content control to be replaced but I am not able to find any logic to replace the HTML text there. Any help would be greatly appreciated. Pls see my code below
Also, please let me know if am doing anything wrong. my final goal to have a template with multiple content controls at various places along with static text. While generating the document, all content controls should be replaced with respective html text(this could as long as a paragraph).
htmlText: <p>This is <strong>sample</strong> HTML <u>text</u>.
// Find specific content control element
try{
org.docx4j.wml.Document wmlDocumentEl = mainDocumentPart.getJaxbElement();
org.docx4j.wml.Body body = wmlDocumentEl.getBody();
List<Object> blockLevelElements = body.getEGBlockLevelElts();
int indexToReplace = -1;
for (int i = 0; i < blockLevelElements.size(); i++) {
Object o = blockLevelElements.get(i);
if (o instanceof SdtBlock) {
SdtBlock sdtBlock = (SdtBlock) o;
Tag tag = sdtBlock.getSdtPr().getTag();
if (tag != null && tag.getVal().equals(tagName)) {
indexToReplace = i;
break;
}
}
}
// Replace identified element with HTML text
if (indexToReplace != -1) {
blockLevelElements.remove(indexToReplace);
// Here we need logic to replace the identified tag with HTML text.
} else {
throw new RuntimeException("Content control with tag '" + tagName + "' not found.");
}
}
catch(Exception ex) {
oLog.error("Failed to replace Content Controls"+ ex);
}
You don’t need to reinvent the wheel. See generally https://opendope.org/approach_our.html and https://github.com/plutext/docx4j/blob/VERSION_11_5_0/docx4j-samples-docx4j/src/main/java/org/docx4j/samples/ContentControlBindingExtensions.java
As per https://github.com/plutext/docx4j/blob/VERSION_11_5_0/docx4j-core/src/main/resources/org/docx4j/model/datastorage/bind.xslt#L332 if your w:sdtPr/w:tag contains ‘od:ContentType=application/xhtml+xml’ it will use ImportXHTML (if present) to convert the bound content.
But if you do want to reinvent the wheel, in your code, follow this example: https://github.com/plutext/docx4j-ImportXHTML/blob/VERSION_11_4_10/docx4j-ImportXHTML-samples/src/main/java/org/docx4j/samples/ConvertInXHTMLFragment.java