We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Conditional Logic on Fields and sentences

Hi I am evaluating Aspose for a project that I am working on. I have been going through the documentation and the forums. It seems that you can have conditional logic on a merged field but I am not quite sure how to do it.

For example
I need to put some logic on a opening sentence of the report. The logic is based on fields pulled from some pojos.

Something like

if (p.problemType == ‘Radio’)

<> I am sorry that you are having a problem with your radio.

else (p.problemType == 'Elbow)

<> where does it hurt on your elbow?

from there I need to put conditional logic on a field in the sentence. If someone could point me in the right direction it would be greatly appreciated!!



Hi Cam,

Thanks for your inquiry.

There are two possible techniques to insert conditional content into your document.

Firstly you can use an IF field in your document and insert the appropriate data into the conditional part using a mergefield. Please see the code below and Conditional Template 1.docx for an example.

Document doc = new Document("Conditional Template 1.docx");<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

doc.getMailMerge().execute(new String[] { "Type" }, new Object[] { "Radio" });

doc.save("Conditional Template Out 1.docx");

You can also also use handler to provide your own logic when merging fields. In this case using Conditional Template 2.docx and the handler below, the appropriate message is merged into the document based off which value is passed to the mail merge engine.

Document doc2 = new Document("Conditional Template 2.docx");

doc2.getMailMerge().setFieldMergingCallback(new HandleFieldMerging());

doc2.getMailMerge().execute(new String[] { "Message" }, new Object[] { "Radio" });

doc2.save("Conditional Template Out 2.docx");

public static class HandleFieldMerging implements IFieldMergingCallback


public void fieldMerging(FieldMergingArgs args) throws Exception





args.setText("I am sorry you are having trouble with your radio");



public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception


// Do Nothing



Each method has it's advantages, also note that the first method will leave the IF field in your document even after merging. You can use the code from here to convert such fields to static text.

If I can help you with anything else, please feel free to ask.