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

Free Support Forum - aspose.com

Highlighting replaced MergeFields


I’m have a Document that I have run through a mailmerge process but in many cases this document will have fields that weren’t merged. I am trying to highlight these unmerged fields(strictly speaking I’m trying to replace them with the Fieldname as a Highlighted text but whenever I try the highlight isn’t applied.

This is what I have right now:
//mainDoc is the Document object that has already gone through the merge process
String[] remainingFields = mainDoc.MailMerge.GetFieldNames();

            DocumentBuilder postProcessBuilder = new DocumentBuilder(mainDoc);
            Shading shd = postProcessBuilder.Font.Shading;
            shd.Texture = TextureIndex.TextureSolid;
            shd.BackgroundPatternColor = System.Drawing.Color.Red;
            shd.ForegroundPatternColor = System.Drawing.Color.Red;
            //I've tried similar with postProcessBuilder.Font.HighlightColor = System.Drawing.Color.Red; but 
            //again, the fields are replaced but not highlighted
            for (int i = 0; i < remainingFields.Length; i++)
                String fieldText = remainingFields[i];
Run thisRun = new Run(mainDoc, fieldText);
Font f = thisRun.Font;
f.HighlightColor = System.Drawing.Color.Red;

I’ve replaced the commented line in my for loop and it worked!.. sort of
While the highlighting and text are right, I’ve lost the rest of my formatting. I ultimately don’t wan’t the end user to have to do additional fixes to the font. Is there a way to match the font of the current cursor position of the DocumentBuilder in the Run I create and then change the HighlightColor property?


Thanks for your inquiry. Please perform the mail merge operation and use the following code example to highlight the unmerged fields. Hope this helps you.

Document doc = new Document(MyDir + "in.docx");
//Perform mail merge...
foreach (Field field in doc.Range.Fields)
    if (field.Type == FieldType.FieldMergeField)
        Node currentNode = field.Start.NextSibling;
        FieldEnd fieldend = field.End;

        while (currentNode != fieldend)
            if (currentNode.NodeType == NodeType.Run)
                ((Run)currentNode).Font.HighlightColor = Color.Red;

            currentNode = currentNode.NextSibling;

        field.End.Font.Color = Color.Red;
        field.Start.Font.Color = Color.Red;

doc.Save(MyDir + "18.9.docx");

Perfect. Thank you :smiley: