I am trying to replace text or merge field from word document. I found out that I could use docx4j for this purpose.
String docxFile = "C:/Users/admin/Desktop/HelloWorld.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(new java.io.File(docxFile));
HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("Hello", "salutation");
//mappings.put("salutation", "myLastname");
//mappings.put("Salutation", "myFirstName");
//mappings.put("myLastName", "Salutation");
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
// Approach 2 (original)
// unmarshallFromTemplate requires string input
String xml = XmlUtils.marshaltoString(documentPart.getJaxbElement(),
true);
// Do it...
Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);
// Inject result into docx
documentPart.setJaxbElement((Document) obj);
wordMLPackage.save(new java.io.File(
"C:/Users/admin/Desktop/OUT_SIMPLE.docx"));
I've read the documentation for docx4j and some other related post such as Docx4j - How to replace placeholder with value. However,I can't seem to understand the documentation and posts properly to solve this problem.
What I need is to replace the salutation merge field in the word docx with my own salutation. Please help!