Hi Joeri,
You could consider creating a merge range that would conditionally end up being removed (using the MailMergeClearOptions.RemoveEmptyRanges
).
For example, let’s say you have this:

Now if you execute the following mail merge process:
var wireTransferSource = new
{
DueDate = DateTime.Today,
Message = "Sample",
Amount = 123.45,
AccountNumber = 1000
};
var document = DocumentModel.Load("input.docx");
document.MailMerge.ClearOptions = MailMergeClearOptions.RemoveEmptyRanges;
document.MailMerge.Execute(wireTransferSource, "WireTransfer");
document.Save("output.docx");
You’ll end up with something like this:

But if you execute that same mail merge process with an empty source, for example:
var wireTransferSource = new
{
DueDate = "",
Message = "",
Amount = "",
AccountNumber = ""
};
Then this “WireTransfer” merge range will be removed because none of the fields was merged inside of it and we specified the usage of MailMergeClearOptions.RemoveEmptyRanges
.
Alternatively, you could have another value in the source that would indicate if the merge range should be removed. Then you could use the FieldMerging
event to remove any field merging for that range when the conditional value indicates that the range needs to be removed.
This will basically result in the same behavior, none of the fields inside the range will be merged and thus the whole range will be removed because of the MailMergeClearOptions.RemoveEmptyRanges
.
var wireTransferSource = new
{
DueDate = DateTime.Today,
Message = "Sample",
Amount = 123.45,
AccountNumber = 1000,
Hidden = true
};
var document = DocumentModel.Load("input.docx");
document.MailMerge.FieldMerging += (sender, e) =>
{
if (e.MergeContext.RangeName != "WireTransfer")
return;
var source = (dynamic)e.MergeContext.Record;
if (source.Hidden)
e.Inline = null;
};
document.MailMerge.ClearOptions = MailMergeClearOptions.RemoveEmptyRanges;
document.MailMerge.Execute(wireTransferSource, "WireTransfer");
document.Save("output.docx");