We have the following two documents:
And
I merge both documents to one PDF file.
The result looks like this:
As you can see, the content of the second document is inside of the shape of the first document.
I use the following code to merge documents:
public Document mergeDocuments(List<Document> documents) {
Document result = null;
DocumentBuilder builder = null;
for(Document document : documents){
if(result == null){
result = document;
builder = new DocumentBuilder(result);
}
else {
builder.moveToDocumentEnd();
builder.insertBreak(BreakType.PAGE_BREAK);
// document.getFirstSection().getPageSetup().setRestartPageNumbering(false);
// builder.getDocument().getFirstSection().getPageSetup().setRestartPageNumbering(true);
builder.insertDocument(document, ImportFormatMode.KEEP_DIFFERENT_STYLES, getImportFormatOptions());
}
}
return result;
}
And then save it to PDF with the following code:
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);
}
document.getFieldOptions().setFieldUpdateCultureSource(FieldUpdateCultureSource.FIELD_CODE);
document.save(outputStream, saveOptions);
return outputStream.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Attached the input and output file(s):
template-1.docx (20.3 KB)
template-2.docx (17.8 KB)
merged-result.pdf (31.9 KB)