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?
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:
Please feel free to update my answer if you think i've said something wrong.