Sometimes, you might need to merge multiple PDF files into one in order to store and review them easier. Likewise, you may also want to split a PDF file into individual files and share them with others separately. For such cases, in this article, I will share 7 ways to merge or split PDF files using Java.

The following topics will be covered:

Add Dependencies

This article uses Spire.PDF for Java API to merge and split PDF files. The API’s jar file can either be downloaded from this website or installed from Maven by adding the following code to your maven-based project’s pom.xml file.

spire-pdf-merge-multiple-pdf.png

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Merge Multiple PDF Files in Java

You can merge two or more PDF files into one using PdfDocumentBase.mergeFiles() method by passing an array of PDFs’ file paths.

The following are the steps to do so:

  • Create a String array with PDFs’ file paths.
  • Merge the PDF files using PdfDocumentBase.mergeFiles(String[] InputFiles) method.
  • Save the merged PDF file using PdfDocumentBase.save(String fileName) method.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfDocumentBase;

public class MergeMultiplePdfsIntoOne {
    public static void main(String []args) {
        //Create a String array with file paths
        String[] files = new String[]{"File1.pdf", "File2.pdf", "File3.pdf"};

        //Merge the PDF files
        PdfDocumentBase pdf = PdfDocument.mergeFiles(files);
        //Save the merged PDF file
        pdf.save("Merge.pdf");
    }
}

Merge Multiple PDF Files using InputStream in Java

In case you want to merge PDF files using InputStream, you can use another overloaded mergeFiles() method by passing an array of inputStreams.

You can refer to the steps below:

  • Load PDF files into FileInputStream objects.
  • Create a InputStream array for the FileInputStream objects.
  • Merge PDF files using PDFDocumentBase.mergeFiles(InputStream[] inputStreams) method.
  • Create a OutputStream object for the merged PDF.
  • Save the merged PDF using PDFDocumentBase.save(OutputStream stream) method.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfDocumentBase;

import java.io.*;

public class MergePdfsUsingInputStreams {
    public static void main(String []args) throws FileNotFoundException {
        //Load the PDF files into FileInputStream objects
        FileInputStream stream1 = new FileInputStream("File1.pdf");
        FileInputStream stream2 = new FileInputStream("File2.pdf");
        FileInputStream stream3 = new FileInputStream("File3.pdf");

        //Create a InputStream array for the FileInputStream objects
        InputStream[] streams = new FileInputStream[]{stream1, stream2, stream3};
        //Merge the PDF files
        PdfDocumentBase pdf = PdfDocument.mergeFiles(streams);

        //Create a OutputStream for the merged PDF
        OutputStream outputStream = new FileOutputStream("Merge.pdf");
        //Save the merged PDF file
        pdf.save(outputStream);
    }
}

Merge Specific Pages of Multiple PDF Files in Java

You can merge a specific page or a range of pages of multiple PDF files using PdfDocument.insertPage(PdfDocument doc, int pageIndex) or PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method.

The following example shows how to merge a range of pages of multiple PDF files:

import com.spire.pdf.PdfDocument;

public class MergeSpecificPagesFromMultiplePdfs {
    public static void main(String []args) {
        //Load PDF files using PdfDocument class
        PdfDocument pdf1 = new PdfDocument("File1.pdf");
        PdfDocument pdf2 = new PdfDocument("File2.pdf");

        //Create a new PDF file
        PdfDocument newPdf = new PdfDocument();
        //Import 1-2 pages of the first PDF to the new PDF
        newPdf.insertPageRange(pdf1, 0, 1);
        //Import 3-4 pages of the second PDF to the new PDF
        newPdf.insertPageRange(pdf2, 2,3);

        //Save the merged PDF
        newPdf.saveToFile("MergePages.pdf");
    }
}

Merge PDF Files of Different Page Sizes into One PDF of the Same Page Size in Java

Sometimes, the PDF files that you want to merge may have different page sizes. Spire.PDF for Java API allows you to merge them into One PDF of the same page size by creating a new PDF file with pages of a desired paper size, then creating templates from the pages in the source PDF files, and later drawing the templates to the new pages of the new PDF file. This process will preserve text, images and all other elements present in the source PDF files.

The following example shows how to merge PDF files with difference page sizes into a single PDF of a standard page size: A4.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.graphics.*;

import java.awt.geom.Point2D;

public class MergePdfsOfDifferentPageSizes {
    public static void main(String []args) {


        //Create a String array with the PDFs' file paths
        String[] files = new String[]{"File1.pdf", "File2.pdf", "File3.pdf"};

        //Create a new PDF file
        PdfDocument newPdf = new PdfDocument();
        //Set page size as A4
        newPdf.getPageSettings().setSize(PdfPageSize.A4);
        //Remove page margins
        newPdf.getPageSettings().setMargins(new PdfMargins(0));

        //Loop through the array
        for( int i = 0; i < files.length -1; i++) {
            //Load the PDF file
            PdfDocument pdf = new PdfDocument(files[i]);
            //Iterate through the pages in the PDF
            for (int j = 0; j < pdf.getPages().getCount(); j++) {
                //Add pages to the new PDF
                PdfPageBase newPage = newPdf.getPages().add();
                //Set text layout as 1 page, if not set the content will not scale to fit page size
                PdfTextLayout layout = new PdfTextLayout();
                layout.setLayout(PdfLayoutType.One_Page);
                //Create templates for the pages in the PDF and draw templates to the pages of the new PDF
                pdf.getPages().get(j).createTemplate().draw(newPage, new Point2D.Float(0, 0), layout);
            }
        }

        //Save the merged PDF
        newPdf.saveToFile("Merge.pdf");
    }
}

If you want to merge the PDF files into a PDF with a custom page size, let’s say 6.5 * 8.5 inches, you can use the following code.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;

public class MergePdfsOfDifferentPageSizes {
    public static void main(String []args) {
        
        //Create a String array with the PDFs' file paths
        String[] files = new String[]{"File1.pdf", "File2.pdf", "File3.pdf"};

        //Create a new PDF file
        PdfDocument newPdf = new PdfDocument();
        //Convert inches to points
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        float width = unitCvtr.convertUnits(6.5f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point);
        float height = unitCvtr.convertUnits(8.5f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point);
        //Specify custom size
        Dimension2D customSize = new Dimension((int)width, (int)height);
        //Set page size as the custom size
        newPdf.getPageSettings().setSize(customSize);
        //Remove page margins
        newPdf.getPageSettings().setMargins(new PdfMargins(0));

        //Loop through the array
        for( int i = 0; i < files.length -1; i++) {
            //Load the PDF file
            PdfDocument pdf = new PdfDocument(files[i]);
            //Iterate through the pages in the PDF
            for (int j = 0; j < pdf.getPages().getCount(); j++) {
                //Add pages to the new PDF
                PdfPageBase newPage = newPdf.getPages().add();
                //Set text layout as 1 page, if not set the content will not scale to fit page size
                PdfTextLayout layout = new PdfTextLayout();
                layout.setLayout(PdfLayoutType.One_Page);
                //Create templates for the pages in the PDF and draw templates to the pages of the new PDF
                pdf.getPages().get(j).createTemplate().draw(newPage, new Point2D.Float(0, 0), layout);
            }
        }

        //Save the merged PDF
        newPdf.saveToFile("Merge.pdf");
    }
}

Split a PDF by Each Page in Java

The PdfDocument.split(String destFilePattern, int startNumber) method is used to split a PDF file into multiple files by each page.

Below is the code to do so:

import com.spire.pdf.PdfDocument;

public class SplitPdfByEachPage {
    public static void main(String []args) {
        //Load a PDF file using PdfDocument class
        PdfDocument doc = new PdfDocument("Sample.pdf");

        //Split every page of the PDF into a separate file
        doc.split("Split-{0}.pdf", 1);
    }
}

merge-split-pdf-file-java-spire-min.png

Split a PDF by Page Ranges in Java

The PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method can also be used to split a PDF into multiple files by page ranges, as shown in the following example.

import com.spire.pdf.PdfDocument;

public class SplitPdfByPageRanges {
    public static void main(String []args) {
        //Load a PDF file using PdfDocument class
        PdfDocument doc = new PdfDocument("Sample.pdf");

        //Create a new PDF file
        PdfDocument newDoc1 = new PdfDocument();
        //Import 1-2 pages of the source PDF to the new PDF
        newDoc1.insertPageRange(doc, 0, 1);
        //Save the PDF file
        newDoc1.saveToFile("Doc1.pdf");

        //Create a new PDF file
        PdfDocument newDoc2 = new PdfDocument();
        //Import 3-5 pages of the source PDF to the new PDF
        newDoc2.insertPageRange(doc, 2, 4);
        //Save the PDF file
        newDoc2.saveToFile("Doc2.pdf");
    }
}

Split a PDF By Bookmarks in Java

It is possible to split a PDF document by sections using bookmarks. This is useful if different sections of a PDF document need to be reviewed by different people. You can refer to the following code to achieve this task.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfBookmarkCollection;

import java.util.*;

public class SplitPdfByBookmarks {
    public static void main(String []args) {
        //Load the PDF file
        PdfDocument pdf = new PdfDocument("Bookmarks.pdf");

        //Get bookmarks
        PdfBookmarkCollection bookmarks = pdf.getBookmarks();

        Map<PdfPageBase, Integer> pages = new HashMap<>();
        Map<String, List<Integer>> splitRange = new HashMap<>();

        //Loop through all the pages and their indexes
        for (int i = 0; i < pdf.getPages().getCount(); i++)
        {
            PdfPageBase page = pdf.getPages().get(i);
            pages.put(page, i);
        }

        //Loop through all the bookmarks and their page ranges
        for (int i = 0; i < bookmarks.getCount(); i++)
        {
            PdfBookmark bookmark = bookmarks.get(i);
            if (bookmark.getDestination() != null)
            {
                PdfPageBase page = bookmark.getDestination().getPage();
                if (pages.containsKey(page))
                {
                    //Bookmark doesn't have any child bookmark
                    if (bookmark.getCount() == 0)
                    {
                        int startIndex = pages.get(page);
                        List<Integer> range = new ArrayList<>();
                        range.add(startIndex);
                        range.add(startIndex);
                        splitRange.put(bookmark.getTitle(), range);
                    }
                    //Bookmark has child bookmark
                    else
                    {
                        int startIndex = pages.get(page);
                        int endIndex = startIndex;
                        List<Integer> range = new ArrayList<>();

                        for(int j = 0; j < bookmark.getCount(); j ++)
                        {
                            PdfBookmark childBookmark = bookmark.get(j);
                            PdfPageBase innerPage = childBookmark.getDestination().getPage();
                            if (pages.containsKey(innerPage))
                            {
                                endIndex = pages.get(innerPage);
                            }
                        }

                        range.add(startIndex);
                        range.add(endIndex);
                        splitRange.put(bookmark.getTitle(), range);
                    }
                }
            }
        }
        
        //Split the PDF file based on the bookmark page range
        Set<String> set = splitRange.keySet();
        for (String title:set) {
            int startIndex = splitRange.get(title).get(0);
            int endIndex = splitRange.get(title).get(1);
            //Create a new PDF file
            PdfDocument doc = new PdfDocument();
            //Extract the pages to the new PDF file
            doc.insertPageRange(pdf, startIndex, endIndex);
            //Save the result file
            doc.saveToFile(title + ".pdf");

            doc.close();
        }
        pdf.close();
    }
}

Conclusion

This article explained how to merge and split PDF files using Java. Besides this, the Spire.PDF for Java API can also be used to perform lots of other PDF manipulations, such as extracting text or images, detecting and reading table data, adding digital signatures/bookmarks/tables/headers/footers/watermarks and so on. You can explore more about it by visiting the documentation if you are interested.

merge-split-pdf-file-java-spire-min.png

Happing coding.

You may also like to read:

Fibonacci series program in Java (With and without recursion)

What are static members in Java? (Explains Static method & field with example)

How to compare Strings in Java?