Remove table when region merge fields content is empty?

Hi,

In my word doc I have a table with 1 row of headers and then 1 row defining a region merge field. When the datasource is empty (no data) I want to remove the whole table. How can I achieve this?

thanks in advance for the tips, just beginning to learn about mail merge stuff.

Hi

Thanks for your inquiry. I think, in your case, you can insert bookmark into each table, which can be removed and use this bookmark as identifier. If there is no data, you just remove table, which contains the appropriate bookmark. Code to remove table will look like the following:

Document doc = new Document(@"in.doc");
// Get bookmark
Bookmark bk = doc.Range.Bookmarks["MYREGION_BOOKMARK"];
if (bk != null)
{
    // Get table, where bookmark is located.
    Node table = bk.BookmarkStart.GetAncestor(NodeType.Table);
    if (table != null)
        table.Remove();
}
doc.Save(@"out.doc");

But note, Bookmark should be inside a table, which should be removed.
Hope this helps.
Best regards.

Hi,

You may also want to look at the code from this thread below.

https://forum.aspose.com/t/67539

It will remove any empty regions from a document. It is programmed in .NET though, if it is needed and you are unable to translate to Java we will be glad to assist.

Thanks,

@aske012

That solution doesn’t seem to work as the “tablestart” merge field isn’t present in the document when the visitor does its work.

(I’m doing the accept after processing my merge fields and not doing any removal, etc). Was this a change between versions of Aspose or something I need to do?

Hi there,
Yes that is the correct method in which to call the class. In your case in sounds as if at least one field from your region is being merged and therefore the TableStart and TableEnd markers are being removed automatically. The code above was designed to remove empty regions that were completly unmerged and still had the start and end markers present.
It should be fairly easy to modify the code to achieve what you described above. Could you please attach your document and code here and I will be glad to help you further.
Thanks,

Hi

Thanks for your inquiry. Yes, behavior was changed. Earlier version removed empty regions, but the latest version of Aspose.Words just leave them untouched.
Best regards.

Thanks all, my final code is:

String[] fields = templateDoc.getMailMerge().getFieldNames();
for (String field: fields)
{
    documentBuilder.moveToMergeField(field);
    Node table = documentBuilder.getCurrentParagraph().getAncestor(NodeType.TABLE);
    if (table != null)
    {
        try
        {
            table.remove();
        }
        catch (java.lang.IllegalStateException e)
        {
            // ignoring this exception
            LOGGER.info(e.getMessage());
        }
    }
}