I have the folling template:
test-white-spaces.docx (6.2 MB)
I am using \f
as documented here Field codes: MergeField field to insert conditional white spaces.
Essentially, we want to have the MergeFields separated by one whitespace but only if they are present.
I use the following code to export a PDF from the Word template:
@Override
public byte[] writeFile(Document document, String fileExtension) throws IOException {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
SaveOptions saveOptions = SaveOptions.createSaveOptions(SaveFormat.fromName(fileExtension.toUpperCase()));
if(saveOptions instanceof PdfSaveOptions pdfSaveOptions){
pdfSaveOptions.setPreserveFormFields(true);
pdfSaveOptions.setUpdateFields(true);
pdfSaveOptions.setRenderChoiceFormFieldBorder(false);
pdfSaveOptions.setEmbedFullFonts(true);
}
document.getFieldOptions().setFieldUpdateCultureSource(FieldUpdateCultureSource.FIELD_CODE);
document.save(outputStream, saveOptions);
return outputStream.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I do not run a MailMerge after filling in the MergeFields, but I have tried the folloing without any better result:
doc.getMailMerge().executeWithRegions(new DataTable());