Search code examples
docx4j

docx4j: Use docx template and replace value of MergeField variable


So I'm trying to use docx4j. I made a simple template, use that and replace th value programmatically.

Here's my docx template.

My Name is «myName»
I’m «myAge» years old.
My address is «myAddress»

When I click toggle field codes it looks like this.

My Name is {MERGEFIELD myName \* MERGEFORMAT}
I’m {MERGEFIELD myAge \* MERGEFORMAT} years old.
My address is {MERGEFIELD myAddress \* MERGEFORMAT}

I do not know the use of MERGEFIELD but I tried to use it simply because that's what the post in the internet currently use.

Here's my code.

def config = grailsApplication.config.template.invoiceSample as Map
def String templateFileName = "${grailsApplication.config.template.dir}/${config.doc.templateFileName}"
WordprocessingMLPackage template = WordprocessingMLPackage.load(new File(templateFileName));

Map<DataFieldName, String> map = new HashMap<DataFieldName, String>();
map.put(new DataFieldName("@myName"),"Jean");
map.put(new DataFieldName("@myAge"),"30");  
map.put(new DataFieldName("@myAddress"),"Sampaloc");  

org.docx4j.model.fields.merge.MailMerger.setMERGEFIELDInOutput(MailMerger.OutputField.KEEP_MERGEFIELD);
org.docx4j.model.fields.merge.MailMerger.performMerge(template, map, false);

template.save(new File("C:/temp/OUT_SIMPLE.docx") );

However, It doesn't replace the value in the output file. Could you tell me what is wrong with my code?


Solution

  • I found out that this problem is just easy to fix.

    Basically this line affects the output.

    MailMerger.setMERGEFIELDInOutput(MailMerger.OutputField.KEEP_MERGEFIELD);

    Based on my observation, these options do the following:

    • MailMerger.OutputField.KEEP_MERGEFIELD - replace the field with value but you need to click toggle field codes to reveal it.
    • MailMerger.OutputField.REMOVED - the codes will be gone but most importantly the value will be replaced without the need to click toggle field codes
    • MailMerger.OutputField.AS_FORMTEXT_REGULAR - I honestly don't know what it does, it just shows {FORMTEXT} in the word.
    • MailMerger.OutputField.DEFAULT - does the same thing with REMOVED.

    Please feel free to update my answer if you think i've said something wrong.