Merge PDF Files in Java (Code Example Tutorial)
Tags: tutorial, programming, dotnetcore, csharp
Published: 2023-03-30 08:21:36

In this article, we will learn to merge multiple PDF files into a single PDF using the Java program. Merging PDF files is almost impossible to achieve in Java by using its native libraries. Therefore, we need a third-party library to achieve these tasks.

There are multiple libraries available that can be used for this purpose. However, each comes up with pros and cons. Therefore, we need to be very careful in selecting the library. Choosing the wrong library cannot only cause performance issues, but It can also affect the security of the project.

I have found [IronPDF](https://ironpdf.com/java/) for Java ideal when dealing with pdf documents. IronPDF is free for development, easy to use, secure, provides high performance and accuracy. We will use IronPDF throughout our article. Before going further let's explore a little bit about IronPDF.
##IronPDF:

[Iron Software](https://ironsoftware.com/) developed and maintains the Java package [IronPDF](https://ironpdf.com/java/), emphasizing precision, speed, and usability. It offers a broad range of features, including creating, reading, and manipulating PDF files. It is also free for development. It has almost every feature you might consider when working with a PDF file.
##Create a New Java Project:

We need to create a new Java Project for the demonstration. You can use existing projects if required. I am using IntelliJ IDE, you can use any. Please note that steps for creating a new project may differ from IDE to IDE or version to version.

Open IntelliJ IDE as shown below.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1hjd7n4bhrtlb4xxdz4.png)
Click on New Project Button, and a new window will appear as shown below.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikx8xidckzs2f3hl7wic.png)
Specify Project Name, Location, Build System, and JDK. Click on Create Button to create the project.
##Install IronPDF:
We need to install IronPDF in our project to use its methods. Open your pom.xml file and add the following maven dependencies.

```
<dependencies>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>2023.3.2</version>
</dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>2.0.5</version>
    </dependency>
</dependencies>
```
Save the POM.xml file. Build and reload the maven repository. It will automatically download and add references to our project.

Add the following import in the java program.

```
import com.ironsoftware.ironpdf.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
```
These imports will be used in different examples demonstrated below. Note that, some imports may be unnecessary for some examples.
##Merge Two PDF Source Files:

I have the following two tests PDFs which I will use as source pdf files.

PDF File 1:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3i3j71cjd7p3frgvgdz0.png)
PDF File 2:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1tv6e6qnjs2b4pcx9kdr.png)
I will merge the above two PDF files into a single pdf document using the following code sample.

```
PdfDocument PdfDoc1 = PdfDocument.fromFile(Paths.get("PdfFile_1.pdf"));
 PdfDocument PdfDoc2 = PdfDocument.fromFile(Paths.get("PdfFile_2.pdf"));
 PdfDocument mergedPDF = PdfDocument.merge(PdfDoc1, PdfDoc2);
 mergedPDF.saveAs(Paths.get("New_Merged_PDF.pdf"));
```
We have loaded the PDF File from our device and initialized the PDF Document instance. After loading both the pdf, we used the merge() method to merge two pdf files into a single pdf file.

##Output:
The merged pdf file generated by our program is as:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kxixcznrz2m19y6z840v.png)
##Java Merge PDF files into Single PDF:
In the above example, we have merged two pdf documents, similarly, we can merge multiple pdf documents by initializing the pdf document object and passing it in the merge method. Assume that, we are working in a scenario, where we don't know the exact number of pdfs, and their name. We need to make this process dynamic.

Let's write a program, which will loop through folders and merge multiple PDFs into a single PDF document.

```
File folder = new File("D:\\Tutorial Project\\MergePDF\\PDF_Files");
        File[] listOfFiles = folder.listFiles();
        List<PdfDocument> pdfs = new ArrayList<>();
        for (File file : listOfFiles) {
            if (file.isFile()) {
                pdfs.add(PdfDocument.fromFile(file.toPath()));
            }
        }
        PdfDocument mergedPDF = PdfDocument.merge(pdfs);
        mergedPDF.saveAs(Paths.get("New_Merged_PDF.pdf"));
        }
```
In the above code, we have gotten all the files from the Specified folder using java.io. We have created a List of PDFDocument types. In the for loop, we have looped through each pdf file and added them to the list after initializing the pdf document object.

In the end, we have to call the merge() method to merge pdf documents.
###Output:

In the folder, we have four pdf files each consisting of a single page. Our Program has merged all the pdf files and created a new document. The final merged pdf file is as:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25e0up24b20p826oass0.png)
It can be observed that the pdf data of all the pdf documents are accurate. Similarly, In our real application, we can take a folder or file path from the user by providing browse functionality and merge the provided pdf accordingly.

##Merge multiple URLs into a Pdf Document:
We can also merge the content of multiple URLs into a single pdf file. Consider the following code sample:

```
PdfDocument PdfDoc1 = PdfDocument.renderUrlAsPdf("https://www.adobe.com/acrobat/about-adobe-pdf.html");
        PdfDocument PdfDoc2 = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
        PdfDocument mergedPDF = PdfDocument.merge(PdfDoc1, PdfDoc2);
        mergedPDF.saveAs(Paths.get("New_Merged_PDF.pdf"));
```
In the above code, we have used the renderUrlAsPdf() method to create a pdf from the URL, later on, we passed the pdfs to merge method for merging pdf files.
##Add Header and Footer:

We can also add a header, footer, Watermark, background, and forecolor to our newly generated pdf. In this example, we will just add a header and footer to remain in the scope of the article.

```
PdfDocument PdfDoc1 = PdfDocument.renderUrlAsPdf("https://www.lipsum.com/");
        PdfDocument PdfDoc2 = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
        PdfDocument mergedPDF = PdfDocument.merge(PdfDoc1, PdfDoc2);
        // header
        HeaderFooterOptions options = new HeaderFooterOptions();
        options.setFirstPageNumber(1);
        TextHeaderFooter textHeader = new TextHeaderFooter();
        textHeader.setDrawDividerLine(true);
        textHeader.setCenterText("My New Merge PDF");
        textHeader.setFont(FontTypes.getHelvetica());
        textHeader.setFontSize(12);
        mergedPDF.addTextHeader(textHeader, options);

        // Footer
        TextHeaderFooter textFooter = new TextHeaderFooter();
        textFooter.setDrawDividerLine(true);
        textFooter.setFont(FontTypes.getArial());
        textFooter.setFontSize(10);
        textFooter.setLeftText("{date} {time}");
        textFooter.setRightText("{page} of {total-pages}");
        mergedPDF.addTextFooter(textFooter, options);
// Save
        mergedPDF.saveAs(Paths.get("New_Merged_PDF.pdf"));
```
This code sample demonstrates how IronPDF enables us to specify headers and footers for PDF files that are generated from HTML text or loaded from a file system.

We can define the text that should appear in the left, right, or center portion of a PDF document's header or footer by using the TextHeaderFooter class. As demonstrated above, using IronPDF's built-in templating tags (like "date," "time," and "page"), We can rapidly piece together headers and footers. IronPDF offers users the freedom to genuinely incorporate any kind and quantity of text at these locations, so users are not required to use these tags exclusively.

###Output:

The Header and footer have been added to our pdf document as shown below.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gu66jlsz0vxvyg3t1oyf.png)
##Summary:

In the above examples, we have [merged multiple pdf documents into a single pdf file](https://ironpdf.com/java/how-to/java-merge-pdf-tutorial/). Moreover, we have also added a Header, Footer, and Page Number to our newly merged pdf. We have also merged the URL into a single pdf by using the renderUrlAsPdf() method. We have achieved the task with the least amount of code and effort while achieving the highest level of performance and accuracy. IronPDF has more than [50 features](https://ironpdf.com/java/blog/using-ironpdf-for-java/), including the ability to create, view, and manipulate PDF files. It is not just a pdf merger library. Additionally, it offers us the ability to add bookmarks, insert headers and footers, and page numbers, merge PDF files, add digital signatures and passwords, and make, and fill out PDF forms. There are still more helpful features, but I won't enumerate them all here. For more information, kindly refer to their [formal documentation](https://ironpdf.com/java/docs/).

It is totally free for research, but we must buy a [license](https://ironpdf.com/java/licensing/) to use it in production. Moreover, a [30-day free trial](https://ironpdf.com/java/#trial-license) is available. We can investigate it and test it in a real-world setting during the trial time.

I have kept this article simple and clear. I hope you have understood it. Please feel free to ask any questions in the comment box.