MergeField whitespaces

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());

@kerner You should use simple mail merge to get the expected output. Please try using the following code:

Document doc = new Document("C:\\Temp\\in.docx");
String[] fieldNames = new String[] { "CoutesyTitle", "FirstName", "LastName" };
String[] fieldValues = new String[] { "Mr.", "James", "Bond" };
doc.getMailMerge().execute(fieldNames, fieldValues);
doc.save("C:\\Temp\\out.docx");

out.docx (5.4 MB)

1 Like