I have two MailMerge tables, of which one can be empty.
I use
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);
to not render the table at all, if it is empty.
The problem is, the table gets removed, even if not empy.
Template docx:
table-test.docx (66.2 KB)
Result files:
table-test-no-cleanup-two-datasets.pdf (57.9 KB)
table-test-with-cleanup-two-datasets.pdf (57.6 KB)
table-test-with-cleanup-one-datasets.pdf (57.6 KB)
table-test-no-cleanup-one-datasets.pdf (57.8 KB)
Note that “table-test-with-cleanup-two-datasets” contains only one table.
My MailMerge input:
"kontoinhaber-table": [
{
"person.lastName": "bb-last",
"person.firstName": "bb-first",
"person.domicileAddress.zipCode": "bb-zip",
"person.domicileAddress.countryName": "bb-country"
}
],
"drittsicherungsgeber-table": [
{
"person.lastName": "cc-last",
"person.firstName": "cc-first",
"person.domicileAddress.zipCode": "cc-zip",
"person.domicileAddress.countryName": "cc-country"
}
]
I use the following code to generate PDFs:
private void insertMultiTables(Document doc, Map<String, List<Map<String, String>>> tables) throws Exception {
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);
long overload = getTableOverload(doc);
long tableCount = getTableCount(doc);
long mailMergeRunCount = 0;
for (Map.Entry<String, List<Map<String, String>>> tableEntry : tables.entrySet()) {
String tableName = tableEntry.getKey();
List<Map<String, String>> tableValues = tableEntry.getValue();
Collection<String> columns = getTableColumns(tableValues);
DataTable dataTable = new DataTable(tableName);
columns.forEach(e -> dataTable.getColumns().add(e));
for (Map<String, String> listEntry : tableValues) {
dataTable.getRows().add(listEntry.values().toArray());
}
for (int i = 0; i < overload; i++) {
log.debug("Running Mail Merge for table '{}'", tableName);
doc.getMailMerge().executeWithRegions(dataTable);
mailMergeRunCount++;
}
}
// trigger cleanup
// TODO: could be optimized to run only as often as 'totalTableCount' - 'totalMailMergeRunCount'.
for (int i = 0; i < tableCount; i++) {
doc.getMailMerge().executeWithRegions(new DataTable());
mailMergeRunCount++;
}
doc.getMailMerge().deleteFields();
}