IFieldMergingCallback: how to highlight unmerged field

Hello,


I’m trying to do the following:

Perform mail merge on a word document that contain mustache style merge fields.

Highlight all successfully merged fields with the color yellow while keeping existing formatting.

Highlight all unmerged fields with the color red while keeping the unmerged field visible on the document including existing formatting.

I’m able to successfully highlight the merged field but unsure of how to highlight the unmerged field.

For example:

var doc = new Document(“Input.docx”);
doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.FieldMergingCallback = new HighLightFieldMergingCallback();
doc.MailMerge.Execute(new string[] { “FirstName”, }, new object[] { “John” });
doc.Save(“Output.docx”, SaveFormat.Docx);

Input.docx contains:

{{FirstName}} {{LastName}}

IFieldMergingCallback implementation:

public void FieldMerging(FieldMergingArgs args)
{
if (_builder == null) _builder = new DocumentBuilder(args.Document);

if (args.FieldValue != null)
{
_builder.MoveToMergeField(args.FieldName);
_builder.Font.HighlightColor = Color.Yellow;
_builder.Write(args.FieldValue.ToString());
args.Text = string.Empty;
}
}

Current output:
John {{LastName}}

Would like to do this:
John {{LastName}}

Is this possible?

Thanks,
Minh

i think i figured it out, added this else statement


else
{
var fieldCode = args.Field.GetFieldCode().Trim();
_documentBuilder.MoveToMergeField(args.FieldName);
_documentBuilder.Font.HighlightColor = Color.Red;
_documentBuilder.InsertField(fieldCode);
}

Hi Minh,


It’s great you were able to find what you were looking for. Please let us know any time you have any further queries.

Best regards,