How to add color while adding value of merge field

I have used datset for add value in table, so How to add color while adding value of merge field using java

@kalpeshAspose1997 You can achieve this using IFieldMergingCallback. Please see our documentation to learn how to apply custom formatting during mail merge:
https://docs.aspose.com/words/java/how-to-apply-custom-formatting-during-mail-merge/

hello @alexey.noskov ,
ref link not useful : How to Apply Custom Formatting during Mail Merge|Aspose.Words for Java

Following Java code not working, I want to add color value for DataTable object value, can you pls check let me know what’s changes are required, ‘test text1’ should be print with red color, let me know if any query

Document doc = new Document("testTemplate.docx");
DataSet mainDataSet = new DataSet();
DataTable testDetails = new DataTable("testDetails");
DocumentBuilder builder = new DocumentBuilder(doc);
Font font = builder.getFont();
font.setColor(Color.RED);
testDetails.getRows().add("test text",builder.write("test text1");
mainDataSet.getTables().add(testDetails);
doc.getMailMerge().setFieldMergingCallback(new CustomFieldMergingCallback());
doc.getMailMerge().executeWithRegions(mainDataSet);
doc.save("out.docx");

@kalpeshAspose1997 You did not follow the instructions in the provided article. Your code should looks like this:

Document doc = new Document("C:\\Temp\\in.docx");

// Prepare dummy data source
DataTable testDetails = new DataTable("testDetails");
testDetails.getColumns().add("fieldName");
testDetails.getRows().add("test text");

doc.getMailMerge().setFieldMergingCallback(new CustomFieldMergingCallback());
doc.getMailMerge().executeWithRegions(testDetails);
doc.save("C:\\Temp\\out.docx");
private static class CustomFieldMergingCallback implements IFieldMergingCallback
{
    @Override
    public void fieldMerging(FieldMergingArgs args) throws Exception {
        // Condition just for demonstration purposes
        if(args.getFieldName().equals("fieldName")) {
            DocumentBuilder builder = new DocumentBuilder(args.getDocument());
            builder.moveToField(args.getField(), true);
            builder.getFont().setColor(Color.RED);
            builder.write(args.getFieldValue().toString());
            args.setFieldValue("");
        }
    }

    @Override
    public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception {
        // Do nothing
    }
}

in.docx (12.8 KB)
out.docx (10.1 KB)

1 Like

@alexey.noskov I want to add different color for same fields (I have used table so add different color for each row)

@kalpeshAspose1997 Could you please attach your template and expected output document. The provided code is just a simple example, you can modify it according to your needs.

Hello @alexey.noskov , How to add different color for same fields ( using java I will add in loop), like I have attach expecting output file
out (3).docx (12.6 KB)

@kalpeshAspose1997 The approach is exactly the same as suggested earlier. For example see the following code:

builder.getFont().setColor(Color.RED);
builder.writeln("test text");
builder.getFont().setColor(Color.BLUE);
builder.writeln("test text");
builder.getFont().setColor(Color.YELLOW);
builder.writeln("test text");
1 Like

Hello @alexey.noskov , Is there any way to fetch the merge fields from document and values of that merge fields and base on that I can set color on merge field

NodeCollection mergeFields = document.getChildNodes(NodeType.FIELD_START, true);
DocumentBuilder builder = new DocumentBuilder(document);
// Iterate over the merge fields and print their names
for (FieldStart fieldStart : (Iterable<FieldStart>)mergeFields)
{
    if (fieldStart.getFieldType() == FieldType.FIELD_MERGE_FIELD)
    {
        String fieldName = fieldStart.getField().getResult();
        System.out.println("Merge field name: " + fieldName);

        String withoutLastCharacter = fieldName.substring(1, fieldName.length() - 1);
        if (withoutLastCharacter == "testType")
        {
            Font font = builder.getFont();
            font.setBold(true);
            if (fieldStart.getFieldData().equals("TestCyan"))
            {
                font.setColor(Color.CYAN);
                builder.write("test cyan");
            }

            System.out.println("Merge data: " + fieldStart.getFieldData());
        }
    }
}

@kalpeshAspose1997 You can use the following code to change color of a particular merge field:

Document doc = new Document("C:\\Temp\\in.docx");

for (Field f : doc.getRange().getFields())
{
    // Process merge fields only.
    if (f.getType() == FieldType.FIELD_MERGE_FIELD)
    {
        FieldMergeField mf = (FieldMergeField)f;

        // Change font color of whole merge field
        if (mf.getFieldName().equals("test"))
        {
            Inline current = mf.getStart();
            while (current != mf.getEnd())
            {
                current.getFont().setColor(Color.CYAN);
                current = (Inline)current.getNextSibling();
            }
            mf.getEnd().getFont().setColor(Color.CYAN);
        }
    }
}

doc.save("C:\\Temp\\out.docx");

Hi @alexey.noskov i have check not all the fields are fetch using " document.getRange().getFields() " this line so is there any limitation for that?

What we actually expect refer following code, let me know required changes

for (Field f : document.getRange().getFields())
{
    // Process merge fields only.
    if (f.getType() == FieldType.FIELD_MERGE_FIELD)
    {
        FieldMergeField mf = (FieldMergeField)f;
        String mergefiledValue = mf.getDisplayResult().toString(); // getDisplayResult() not work
                                                                   // Change font color of whole merge field
        if (mf.getFieldName().equals("testType"))
        {
            if (mergefiledValue.equals("CYAN"))
            {
                Inline current = mf.getStart();
                while (current != mf.getEnd())
                {
                    current.getFont().setColor(Color.CYAN);
                    current = (Inline)current.getNextSibling();
                }
                mf.getEnd().getFont().setColor(Color.CYAN);
            }
            if (mergefiledValue.equals("RED"))
            {
                Inline current = mf.getStart();
                while (current != mf.getEnd())
                {
                    current.getFont().setColor(Color.RED);
                    current = (Inline)current.getNextSibling();
                }
                mf.getEnd().getFont().setColor(Color.RED);
            }
        }
    }
}

@kalpeshAspose1997 There is no limitations. document.getRange().getFields() returns all the fields in the document. The problem on your side might occur because you are using Aspose.Words in evaluation mode and your document is truncated due to the evaluation version limitations.

FieldMergeField.getDisplayResult() returns text between FieldSeparator and FieldEnd, it does nto return the actual value of the merge field from the data source. Please see our documentation to learn more about fields in MS Word documents:
https://docs.aspose.com/words/java/introduction-to-fields/

The actual value of the merge field is available only upon execution mail merge, when the merge field is replaced with data.

how to fetch only specific table mergeFields with mergeField value?

@kalpeshAspose1997 You can get fields from the particular table using table.getRange().getFields(), i.e. the same way as you do for whole document.
As I have mentioned the actual values of the merge fields are available only upon execution mail merge, when the merge fields are replaced with data. however, you can get the actual value directly from your data source by field name.