Question about mergefields

I have another issue with a bunch of documents which include Word Mailmerge fields and I need to update in bulk for use in a different system. For example the documents include lots of fields like:

{MERGEFIELD NameAndAddress}

Is there any way in your product to convert each merge field into just plain Text and give it a new formatting? So i.e. the Mergefield above would become just “[NameAndAddress]” as a plain text and format it in Red underline font?

I tried find/replace method but it didn’t work.

Any advice or code example would be very helpful.

Hi
Thank you for your interest in Aspose products.

In order to achive what you want, you can get the field names from the MaiMerge object. You need to create an array with the new values to replace the MergeFields. Finally you can run a custom method to change the format of the merge fields the way you need.

I added some code that will guide you to work with.

var doc = DocumentGet(); // Read the document you need.
var fieldNames = doc.MailMerge.GetFieldNames();
var valueList = DynamicListGet(fieldNames); // Function to get an array with new values to replace the MergeFields.
ApplyingFormat(doc); // Function to apply format to the text.
doc.MailMerge.Execute(fieldNames, valueList);
doc.Save("Template_Output.docx");

private string[] DynamicListGet(string[] source)
{
    // You can change the way to generate the values here, we are just using [ ] on the MergeField name.
    string[] result = new string[source.Length];
    for (int i = 0; i < result.Length; i++)
    {
        result[i] = $"[{source[i]}]";
    }
    return result;
}

private void ApplyingFormat(Document doc)
{
    foreach (Field field in doc.Range.Fields)
    {
        if (field.Type.Equals(Aspose.Words.Fields.FieldType.FieldMergeField))
        {
            Node currentNode = field.Start;
            bool isContinue = true;
            while (currentNode != null && isContinue)
            {
                if (currentNode.NodeType.Equals(NodeType.FieldEnd))
                {
                    FieldEnd end = (FieldEnd)currentNode;
                    if (end == field.End)
                        isContinue = false;
                }

                if (currentNode.NodeType.Equals(NodeType.Run))
                {
                    // Specify Font formatting here
                    Run run = ((Run)currentNode);
                    run.Font.Color = Color.Red;
                    run.Font.Underline = Underline.Single;
                }

                Node nextNode = currentNode.NextPreOrder(currentNode.Document);
                currentNode = nextNode;
            }
        }
    }
}        

Basically the code is separated in 2 main functions, one that get the new values to write and another to get the new format to write them with.

Please let me know if you would like to know something else.
Best regards.