Free Support Forum -

Default value for mail merge field

Hi everybody,

I have a pretty simple question for which I seem to be unable to find a simple answer: is there a way to perform a mail merge operation using Aspose.Words for Java specifying a default value for all those fields which, at the and of the merge, will be null or empty?


Hi Matteo,

Thanks for your inquiry. If you would like to insert default values if mergefields are merged with empty or null data, in this case you can use MergeField event handler. Please see the following code:
Document doc = new Document(“C:\Temp\in.docx”);

doc.getMailMerge().setFieldMergingCallback(new HandleMergeField());
new String[] { “a”, “b”, “c” },
new String[] { “first line”, “”, “third line” });“C:\Temp\out.docx”);

private static class HandleMergeField implements IFieldMergingCallback {
public void fieldMerging(FieldMergingArgs e) throws Exception {
if (e.getFieldValue().toString() == “”) {
DocumentBuilder builder = new DocumentBuilder(e.getDocument());
builder.write(“Default Value”);
<font color="RED"><b>public</b></font> <font color="RED"><b>void</b></font> imageFieldMerging<font color="BLUE"><b>(</b></font>ImageFieldMergingArgs e<font color="BLUE"><b>)</b></font> <font color="RED"><b>throws</b></font> Exception <font color="BLUE"><b>{</b></font>
    <font color="GREEN"><i>// Do nothing.


I hope, this helps.

Best regards,