We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Handling of "whitespace" characters in merge data

Hi,
I’m working on replacing existing mail merges with Aspose.
The way the templates are laid out means that I have to use options to remove unused fields and empty paragraphs. That’s all three of MailMergeCleanupOptions:RemoveEmptyParagraphs MailMergeCleanupOptions.RemoveUnusedFields, MailMergeCleanupOptions.RemoveContainingFields.
So far so good.

However:
The data sources are text files. And some of them contain deliberate white space characters in the data. For example: a field containing a formfeed (ASCII 12) character so that we’re inserting a page break whereever we want a page break in the final document. Or a field containing a (single) tab character to make sure the merge field is not empty so that Word does not see the line as “blank space” and does not remove that line. (the effect being to have an apparently blank line in the output so the layout looks nice)

When Word is removing “blank lines” in connection with mail merge it never removes lines where there is such data in the merge fields. All formatting characters in the data will make it into the final document.

Not so with Aspose.
Aspose removes “blank space” no matter if it was caused by empty merge fields or was part of data.

There is a relatively easy workaround: I have to load the text files into a dataset anyway before I can merge them, so I can replace the characters I know might be in there with some other “coded” character strings before I do the mail merge. And after the mail merge, replace the “coded” strings with the original characters.
Job done.

My question, really, is only this: Is there a smarter way of achieving the same thing? Something that Aspose can do automatically?

Thanks :slight_smile:

@KarinMX You can achieve what you need by implementing IFieldMergingCallback. For example see the following code:

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

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
doc.MailMerge.FieldMergingCallback = new FieldMergingCallback();
doc.MailMerge.Execute(new string[] { "test1", "test2" }, new string[] { ControlChar.Tab, ControlChar.PageBreak });

doc.Save(@"C:\Temp\out.docx");
private class FieldMergingCallback : IFieldMergingCallback
{
    public void FieldMerging(FieldMergingArgs args)
    {
        string fieldValue = (string)args.FieldValue;
        if (!string.IsNullOrEmpty(fieldValue) && string.IsNullOrEmpty(fieldValue.Trim()))
        {
            DocumentBuilder builder = new DocumentBuilder((Document)args.Field.End.Document);
            builder.MoveToMergeField(args.FieldName, true, true);
            builder.Write(fieldValue);
        }
    }

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