Word Merge || .Net

I am using Aspose library for Word merge. In the previous version of the Aspose, if we add white spaces for a field then while merging , it doesn’t considers it as empty but after upgrade to latest version, it is considering the whitespaces as blank and removing those fields if setting is ON.

For my case, I want to prevent whitespaces or empty fields for few fileds but remove it for rest of the fields. I tried to find a setting which can be applied on field level to prevent or remove empty fields but have’nt got any. Is there any way I can acheive this?

@dharmendra.hbti If paragraph contains only whitespaces it is considered as empty and is removed. So for example if you use code like the following:

string[] fieldNames = new string[] { "FirstName", "MidName", "LastName" };
string[] fieldValues = new string[] { "Alexey", " ", "Noskov" };

Document doc = new Document(@"C:\Temp\in.docx");

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
doc.MailMerge.Execute(fieldNames, fieldValues);

doc.Save(@"C:\Temp\out.docx");

Where MidName merge field is placed in a separate paragraph, the paragraph will be removed as empty.

However, you can work this behavior around using IFieldMergingCallback. For example, you can put hidden text at the merge field to make the paragraph to be considered as not empty. For example see the following code:

string[] fieldNames = new string[] { "FirstName", "MidName", "LastName" };
string[] fieldValues = new string[] { "Alexey", " ", "Noskov" };

Document doc = new Document(@"C:\Temp\in.docx");

doc.MailMerge.FieldMergingCallback = new MergeWhitespaceCallback("MidName");
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
doc.MailMerge.Execute(fieldNames, fieldValues);

doc.Save(@"C:\Temp\out.docx");
private class MergeWhitespaceCallback : IFieldMergingCallback
{
    private readonly string[] mRetainParagraphsWithFields;

    public MergeWhitespaceCallback(params string[] retainParagraphsWithFields)
    {
        mRetainParagraphsWithFields = retainParagraphsWithFields;
    }

    public void FieldMerging(FieldMergingArgs args)
    {
        if (!string.IsNullOrEmpty(args.FieldValue.ToString().Trim()))
            return;

        if (!mRetainParagraphsWithFields.Contains(args.FieldName))
            return;

        DocumentBuilder builder = new DocumentBuilder(args.Document);
        builder.MoveTo(args.Field.Start);
        builder.Font.Hidden = true;
        builder.Write("<empty paragraph>");
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

Later, you can remove hidden text if required.