Merge PDF Files in Java

It’s possible to use the Document Editor to merge multiple documents together to create one large document.

To do this, you can take one of the documents as a base for the Document Editor and insert the second:

// Insert the second document before the original and export to the temporary file.
File file = File.createTempFile("documentEditorOutput", ".pdf");
DocumentEditor documentEditor = documentToEdit.getDocumentEditor();
File secondDocument = new File("secondDocument.pdf");
documentEditor.importDocument(0, DocumentEditor.IndexPosition.BeforeIndex, new FileDataProvider(secondDocument));
documentEditor.saveDocument(new FileDataProvider(file));

Chaining Edits Together

Document edits can be chained to perform multiple synchronous operations to create a single document. For example:

// Insert the second document before the original and duplicate the first page.
File file = File.createTempFile("documentEditorOutput", ".pdf");
DocumentEditor documentEditor = documentToEdit.createDocumentEditor();
File secondDocument = new File("secondDocument.pdf");
documentEditor.importDocument(0, DocumentEditor.IndexPosition.BeforeIndex, new FileDataProvider(secondDocument));
Set<Integer> pages = new HashSet<>();
pages.add(0);
documentEditor.duplicatePages(pages);
documentEditor.saveDocument(new FileDataProvider(file));