Merge PDF documents in JAVA

This article demonstrates how to merge PDF documents by using Spire.PDF for Java. We can merge the PDF documents by using the following two method on JAVA applications.

We use three PDF document for example. We load the PDF documents from file and select the first PdfDocument for the purpose of merging the second and third PDF file to it.

import com.spire.pdf.PdfDocument;
public class MergePDF {
    public static void main(String[] args) {
        //Pdf document list
        String[] files = new String[]
                {
                        "C:\\Users\\Administrator\\Desktop\\Sample01.pdf",
                        "C:\\Users\\Administrator\\Desktop\\Sample02.pdf",
                        "C:\\Users\\Administrator\\Desktop\\Sample03.pdf",
                };
        String outputFile = "output/MergeDocument.pdf";

        //Open pdf documents
        PdfDocument[] docs = new PdfDocument[files.length];
        PdfDocument doc = new PdfDocument();
        for (int i = 0; i < files.length; i++) {
            docs[i] = new PdfDocument();
            docs[i].loadFromFile(files[i]);
        }
        //Append document
        docs[0].appendPage(docs[1]);

        //import pages
        for (int i = 0; i < docs[2].getPages().getCount(); i = i + 2) {
            docs[0].insertPage(docs[2], i);
        }

        // Save pdf file.
        docs[0].saveToFile(outputFile);
        doc.close();
    }
}

Merge PDF documents in JAVA

Merge PDF document by stream. Input the three PDF documents by stream and then use mergeFiles(streams)methods to merge the PDF documents into one PDF document.

import com.spire.pdf.*;
import java.io.*;

public class MergePDF {

        public static void main(String[] args) throws Exception {
            String outputFile = "output/mergeFilesByStream.pdf";

            FileInputStream stream1 = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\Sample01.pdf"));
            FileInputStream stream2 = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\Sample02.pdf"));
            FileInputStream stream3 = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\Sample03.pdf"));

            InputStream[] streams = new FileInputStream[]{stream1, stream2, stream3};

            //Merge files by stream
            PdfDocumentBase doc = PdfDocument.mergeFiles(streams);

            //Save the file
            doc.save(outputFile);
            doc.close();

        }
    }

Merge PDF documents in JAVA