DEV Community

Gia
Gia

Posted on

How to Merge Multiple PDFs into One in Java

When you need to print multiple PDF files constantly, merging them into one file is a great way to simplify the printing process and save time. In addition, merging PDF files with related content also helps us store and manage documents more easily. Next, I will show you how to merge multiple PDF files into one using a PDF library in Java.

Step 1: Tools

In this tutorial, we will use the following libraries and programs.

This is a totally independent Java PDF library, which doesn’t require Adobe Acrobat or other software installed on system. But this is a free version product and only supports merging PDF files within 10 pages. If you want to merge more pages, you can choose Spire.PDF for Java and apply a 30-days free license.

Step 2: Import JAR file to your project

  • Download Free Spire.PDF for Java and unzip it.
  • Create a new project in IntelliJ IDEA and open it.
  • Click “File”- “Project Structure” - “Modules” - “Dependencies” in turn.
  • Choose the “JARs or Directories” under the right green plus, and find the “Spire.Pdf.jar” in the lib folder of the downloaded file.

Step 3: Sample Code

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfDocumentBase;

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

        //Get the paths of the PDFs to be merged
        String[] files = new String[] {
                "C:\\Users\\Administrator\\Desktop\\Sample1.pdf",
                "C:\\Users\\Administrator\\Desktop\\Sample2.pdf",
                "C:\\Users\\Administrator\\Desktop\\Sample3.pdf"};

        //Merge these files
        PdfDocumentBase doc = PdfDocument.mergeFiles(files);

        //Save the result file
        doc.save("C:\\Users\\Administrator\\Desktop\\MergeFiles.pdf", FileFormat.PDF);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code, we can call PdfDocument.mergeFiles() method to merge pdf files. This method also accepts an array of InputStream as the parameter.
Image description

Top comments (0)