Author: Saddam Shaikh
In this blog, we will learn how to read multiple PDF documents and merge them into a single password-protected PDF document by leveraging Java code implemented using the Apache PDFBox library.
What is PDF?
PDF stands for “Portable Document Format,” which can be shared and printed without modification.
What is Apache PDFBox?
Apache PDFBox is an open-source Java tool/library for working with PDF documents. It is used to perform the following actions:
- Create a new PDF document
- Manipulate existing PDF document
- Extract text from PDF document
Follow the steps below to merge multiple PDF documents into a single password-protected PDF document:
- Create a new package ‘com.learning.mulesoft’ under src/main/java and create a Java class ‘FileOperations’ under this package.

- Add the Apache PDFBox dependency in pom.xml.
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.28</version></dependency>
- Write a Java method (mergePDF) to merge multiple PDF documents into a single PDF document using the Apache PDFBox library. (mergePDF method takes an array of PDF file’s absolute path that needs to be merged and final merge PDF file name.) Refer to the snapshot below for the Java code.

- Write a Java method (protectPDF) to protect the PDF file with a password using Apache PDFBox. (protectPDF method takes a PDF absolute path that needs to be password-protected and password value).
Refer to the snapshot below for the Java code.

- Create a Mule flow using the Java module to achieve PDF merge and password protection functionality.
Refer to the snapshots below to understand the flow in detail.




Let’s test the application in Postman.
- Once an application is deployed, call the Mule application endpoint to merge the “pdf-1.pdf” & “pdf-2.pdf” documents and create a single password-protected file.



- If a success response is received from the Mule application, check the directory to verify whether a merged PDF has been created or not.

- Try to open the merged PDF; it should prompt us to provide the password.

4. If we enter the incorrect password, then we will receive an error.

5. If we provide the correct password, then the PDF will open.

Hope you enjoy reading this blog!
References:
- https://www.geeksforgeeks.org/merging-pdfs-using-java/
- https://www.geeksforgeeks.org/encrypt-pdf-using-java/