Merge Multiple PDFs in MuleSoft
In this article, you will learn how to merge multiple PDFs and send back the merged PDF as a response using MuleSoft and Java.
Join the DZone community and get the full member experience.
Join For FreeSuppose there is a scenario where you have to merge multiple PDFs into one PDF and send the merged PDF as a response back to the source system or store the merged PDF in a file location. In this article, you will learn how to do this. There is no such connector in MuleSoft that you can use to merge the PDFs. You will have to use the Java library org.apache.pdfbox.multipdf to merge the PDFs. It contains all necessary Java libraries for merging multiple PDFs into one.
Implementation
Step 1
Add the dependency as shown below in pom.xml:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.1</version>
</dependency>
Step 2
Create a Java class MergeMultiplePDF
under src/main/java and create two static methods mergeAndStorePDF
and mergePDFs
:
package com.mulesoft.mergePDF;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
public class MergeMultiplePDF {
/*
Merge PDF and store it in a local directory
listPdfFileNames= ["src/main/resources/input/PDF1.pdf", "src/main/resources/input/PDF2.pdf"]
mergedPdfFileName= "src/main/resources/output/mergedPDF.pdf"
*/
public static void mergeAndStorePDF(String[] listPdfFileNames, String mergedPdfFileName) throws IOException {
/* Create and initialize object of PDFMergerUtility */
PDFMergerUtility obj = new PDFMergerUtility();
/* Set Destination File in the PDFMergerUtility Object */
obj.setDestinationFileName(mergedPdfFileName);
/* Iterate through the list of PDF filenames */
for (String file : listPdfFileNames) {
/* Add Each PDF files in the PDFMergerUtility Object */
obj.addSource(new File(file));
}
/* Now the PDFMergerUtility Object has all the PDFs. Use mergeDocuments method to merge the PDFs */
obj.mergeDocuments(null);
/* This will store the merged PDF in the destination path passed as argument */
}
/*
Merge PDFs and return the merged PDF as a byte array
base64PDF= List of base64 encoded PDF strings
Eg. ["PDF1 base64 encoded string", "PDF2 base64 encoded string"]
*/
public static byte[] mergePDFs(String[] base64PDF) throws Exception {
/* Create and initialize ByteArrayOutputStream to return the merged PDF as a byte array */
try (ByteArrayOutputStream destination = new ByteArrayOutputStream()) {
/* Create and initialize object of PDFMergerUtility */
PDFMergerUtility obj = new PDFMergerUtility();
/* Set Destination Stream as the ByteArrayOutputStream object in the PDFMergerUtility Object */
obj.setDestinationStream(destination);
/* Iterate through the list of Base64 encoded PDF strings */
for (String pdf : base64PDF) {
/* Initialize ByteArrayInputStream object and store each PDF as bytes */
ByteArrayInputStream bais = new ByteArrayInputStream(pdf.getBytes());
/* Add each base64 decoded PDF in the PDFMergerUtility Object */
obj.addSource(Base64.getDecoder().wrap(bais));
}
/* Now the PDFMergerUtility Object has all the PDFs. Use mergeDocuments method to merge the PDFs */
obj.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
/* Return the mergedPDF as a byte array using the ByteArrayOutputStream object */
return destination.toByteArray();
} catch (IOException e) {
throw new Exception("Error occurred while merging pdf files", e);
}
}
}
mergeAndStorePDF
- This static method accepts two arguments (listPdfFileNames
andmergedPdfFileName
) and has no return type. Read the comments in the Java class to understand each and every step.mergePDFs
- This static method accepts one argument (base64PDF
) and has the return type as a byte array. This byte array is actually the merged PDF file in byte array format. Read the comments in the Java class to understand each and every step.
Step 3
Drag and drop an SFTP List Connector and add the SFTP credentials in the SFTP config. Add the Directory Path and Filename Pattern as {*.pdf}
. This will retrieve all the PDF files from the path mentioned in the property file.
Step 4
Next, initialize a variable base64PDF
as a blank array []
. This variable will contain all base64 encoded PDF strings. Add a choice component after that to check if the payload is empty (i.e., the SFTP List connector picked up any files or not). If no files are retrieved then just log a message No files found. Otherwise, use a For-Each
component to iterate through all the PDF files retrieved.
Step 5
Next, read each PDF as shown above, encode it, and store it as a base64 encoded string in the variable base64PDF
. Encode the PDF using toBase64()
method of dw::core::Binaries library
as shown below.
Step 6
Next, call the static method mergePDFs
of class MergeMultiplePDF
. Pass the list of base64 encoded PDF strings (stored in the variable base64PDF
) as an argument to the method mergePDFs
. The mergePDFs
method will return the concatenated PDF in byte array format. Encode that byte array to base64 encoded string and store it in a variable.
Now, construct the response payload of MimeType multipart/form-data
. Decode the base64 encoded merged PDF and pass it in the content field. Set the Content-Type
as application/pdf
as shown above.
Step 7
Set the MimeType as application/pdf. This will send the merged PDF as a pdf as a response. You can also store this payload in an SFTP output directory.
Input PDFs
PDF1
PDF2
Output PDF
Merged PDF
The merged PDF will have a total of all the pages that each PDF has.
Conclusion
This is how you can merge multiple PDF files into one PDF and get the merged PDF as a response or store the merged PDF in a file location.
Thanks for reading the article and if you have any questions please feel free to write it down in the comments section.
Opinions expressed by DZone contributors are their own.
Comments