Free Support Forum -

IFieldMergingCallback: how to highlight unmerged field


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.Font.HighlightColor = Color.Yellow;
args.Text = string.Empty;

Current output:
John {{LastName}}

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

Is this possible?


i think i figured it out, added this else statement

var fieldCode = args.Field.GetFieldCode().Trim();
_documentBuilder.Font.HighlightColor = Color.Red;

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,