'Aspose Word Merge

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?



Solution 1:[1]

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.

Solution 2:[2]

Assuming you're actually executing a mailmerge (not just overwriting mergefields), you should be able to control most, if not all, of that via mailmerge field coding in the mailmerge main document. On PCs, you can use the mergefield \b and/or \f switches to suppress a space before or after an empty mergefield. For example, suppose you have:

«Title» «FirstName» «SecondName» «LastName»

but «SecondName» is sometimes empty and you don’t want that to leave two spaces in the output. To deal with that:

  1. select the «SecondName» field and press Shift-F9 so that you get {MERGEFIELD SecondName};
  2. edit the field code so that you end up with-
    • {MERGEFIELD SecondName \b " "} or
    • {MERGEFIELD SecondName \f " "}

depending on whether the space to be suppressed is following or before the mergefield;

  1. delete, as appropriate, the corresponding space following or before the mergefield;
  2. position the cursor anywhere in this field and press F9 to update it.

Note 1: the \b and \f switches don't work on Macs or in conjunction with other switches. In such cases you need to use and IF test instead, coded along the lines of-

  • {IF{MERGEFIELD SecondName}<> "" " {MERGEFIELD SecondName}"} or
  • {IF{MERGEFIELD SecondName}<> "" "{MERGEFIELD SecondName} "}

Even so, you can use the \b and \f switches to express other mergefields that do have switches of their own. For example, suppose you have four fields ‘Product’, ‘Supplier’, ‘Quantity’ and ‘UnitPrice’, and you don’t want to output the ‘Product’, ‘Quantity’ or ‘UnitPrice’ fields if the ‘Supplier’ field is empty. In that case, you might use a field coded along the lines of:

{MERGEFIELD "Supplier" \b "{MERGEFIELD Product}?" \f "?{MERGEFIELD Quantity \# 0}?{MERGEFIELD UnitPrice \# "$0.00"}¶
"}

Note 2: The field brace pairs (i.e. '{ }') for the above example are all created in the document itself, via Ctrl-F9 (Cmd-F9 on a Mac or, if you’re using a laptop, you might need to use Ctrl-Fn-F9); you can't simply type them or copy & paste them from this message. Nor is it practical to add them via any of the standard Word dialogues. Likewise, the chevrons (i.e. '« »') are part of the actual mergefields - which you can insert from the 'Insert Merge Field' dropdown (i.e. you can't type or copy & paste them from this message, either). The spaces represented in the field constructions are all required. Instead of the ?, ? and ¶ symbols, you should use real tabs and line/paragraph breaks, respectively.

For more Mailmerge Tips & Tricks, see: https://www.msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexey Noskov
Solution 2