In this template ifcondtioncheck.docx (12.4 KB)
I have 2 merge fields one is FirstName and other is in if condition hideContent. In the output file abc.docx (20.5 KB) toggle the field codes in my machine by pressing ALT+F9. This is not the expected output. we need the like this expected output.docx (25.0 KB)
. The code is
internal class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
/// <summary>
/// This is called when merge field is actually merged with data in the document.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
DocumentBuilder builder = new(args.Document);
builder.MoveToMergeField(args.DocumentFieldName);
string value = Convert.ToString(args.FieldValue) ?? string.Empty;
builder.InsertHtml(value, true);
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing
}
}
Thanks @alexey.noskov this solution works. but In our requirement in values array html data can also come. for example
string[] keys = new string[] { "FirstName", "hideContent" };
string[] values = new string[] { "< b >Gurpreet Singh< /b >", "false" };
it can be div tag or p tag etc.
so to handle that we have use the
templateDocument.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();
internal class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
/// <summary>
/// This is called when merge field is actually merged with data in the document.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
DocumentBuilder builder = new(args.Document);
builder.MoveToMergeField(args.DocumentFieldName);
string value = Convert.ToString(args.FieldValue) ?? string.Empty;
builder.InsertHtml(value, true);
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing
}
}
@CTGurpreet1 It is perfect that you managed to resolve the issue.
Alternatively, you can unlink only certain types of field in your document, IF fields, for example:
// Unlink (replace with actual content) IF field in the document.
templateDocument.Range.Fields.Where(f => f.Type == FieldType.FieldIf).ToList()
.ForEach(f => f.Unlink());