Split PDFs in Java

To split a document, you can use the Document Editor. This example shows splitting a document into two files: “A.pdf” and “B.pdf”.

  1. Create a DocumentEditor object from the original document:

    final PdfDocument document = PdfDocument.open(new FileDataProvider(new File("documentToSplit.pdf")));
    final DocumentEditor documentEditor = document.createDocumentEditor();
  2. Identify which pages should be in document “A” and use removePages to remove the pages that remain:

    // Identify the pages that need to be split.
    final int[] pagesToSplit = new int[] {3, 4, 5};
    documentEditor.RemovePages(pagesToSplit);
  3. Save document “A” to a new location:

    // Save the document to an output file.
    final String filename = "A.pdf";
    documentEditor.saveDocument(new FileDataProvider(new File(filename)));
  4. Using a function such as the one below will make this process simpler:

    void exportSectionOfDocument(String originalDocument, String outputDocument, int[] pagesToExport)
    {
        final PdfDocument document = PdfDocument.open(new FileDataProvider(new File(originalDocument)));
        final DocumentEditor documentEditor = document.createDocumentEditor();
    
        // Search the document for pages that should not be exported and add them to
        // a `pagesToRemove` set.
        final Set<Integer> pagesToRemove = new HashSet<>();
        for (int i = 0; i < document.getPageCount(); i++) {
            if (Arrays.binarySearch(pagesToExport, i) < 0) {
                pagesToRemove.add(i);
            }
        }
        documentEditor.removePages(pagesToRemove);
    
        // Save the new document to the specified output location.
        documentEditor.saveDocument(new FileDataProvider(new File(outputDocument)));
    }
  5. Repeat the steps for document “B”:

    exportSectionOfDocument("documentToSplit.pdf", "B.pdf", new int[] {0, 1, 2});