I have docx document with some placeholders. Now I should replace them with other content and save new docx document. I started with docx4j and found this method:
You can use VariableReplace
to achieve this which may not have existed at the time of the other answers.
This does not do a find/replace per se but works on placeholders eg ${myField}
java.util.HashMap mappings = new java.util.HashMap();
VariablePrepare.prepare(wordMLPackage);//see notes
mappings.put("myField", "foo");
wordMLPackage.getMainDocumentPart().variableReplace(mappings);
Note that you do not pass ${myField}
as the field name; rather pass the unescaped field name myField
- This is rather inflexible in that as it currently stands your placeholders must be of the format ${xyz}
whereas if you could pass in anything then you could use it for any find/replace. The ability to use this also exists for C# people in docx4j.NET
See here for more info on VariableReplace
or here for VariablePrepare