Sujal
Sujal

Reputation: 671

How to replace text/Merge field in Ms word with docx4j

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!

Upvotes: 3

Views: 8956

Answers (1)

guest
guest

Reputation: 31

Please try out this code snippet :

public static void main(String[] args) throws Exception {

    String docxFile = "template.docx";

    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(docxFile));

    List<Map<DataFieldName, String>> data = new ArrayList<Map<DataFieldName, String>>();

    Map<DataFieldName, String> item = new HashMap<DataFieldName, String>();
    item.put(new DataFieldName("@name"), "myFirstname");
    item.put(new DataFieldName("@lastname"), "myLastname");
    data.add(item);

    org.docx4j.model.fields.merge.MailMerger.setMERGEFIELDInOutput(OutputField.KEEP_MERGEFIELD);

    org.docx4j.model.fields.merge.MailMerger.performMerge(wordMLPackage, item, true);

    wordMLPackage.save(new java.io.File("OUT.docx"));

}

Upvotes: 3

Related Questions