Merge A number of PDFs in MuleSoft – DZone – Uplaza

Suppose there’s a state of affairs the place you need to merge a number of PDFs into one PDF and ship the merged PDF as a response again to the supply system or retailer the merged PDF in a file location. On this article, you’ll discover ways to do that. There isn’t a such connector in MuleSoft that you should utilize to merge the PDFs. You’ll have to use the Java library org.apache.pdfbox.multipdf to merge the PDFs. It accommodates all needed Java libraries for merging a number of PDFs into one.

Implementation

Step 1

Add the dependency as proven beneath in pom.xml:


	org.apache.pdfbox
	pdfbox
	2.0.1

Step 2

Create a Java class MergeMultiplePDF beneath src/principal/java and create two static strategies mergeAndStorePDF and mergePDFs:

package deal 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 retailer it in a neighborhood listing
    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 Vacation spot File within the PDFMergerUtility Object */
		obj.setDestinationFileName(mergedPdfFileName);
	    /* Iterate by way of the record of PDF filenames */
		for (String file : listPdfFileNames) {
	    /* Add Every PDF recordsdata within the PDFMergerUtility Object */
			obj.addSource(new File(file));
		}
		/* Now the PDFMergerUtility Object has all of the PDFs. Use mergeDocuments methodology to merge the PDFs */
		obj.mergeDocuments(null);
		/* This can retailer the merged PDF within the vacation spot path handed as argument */
	}

	/* 
    Merge PDFs and return the merged PDF as a byte array 
    base64PDF= Record 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 */		
		strive (ByteArrayOutputStream vacation spot = new ByteArrayOutputStream()) {
          /* Create and initialize object of PDFMergerUtility */
			PDFMergerUtility obj = new PDFMergerUtility();
          /* Set Vacation spot Stream because the ByteArrayOutputStream object within the PDFMergerUtility Object */
			obj.setDestinationStream(vacation spot);
          
            /* Iterate by way of the record of Base64 encoded PDF strings */  
			for (String pdf : base64PDF) {	
            /* Initialize ByteArrayInputStream object and retailer every PDF as bytes */
				ByteArrayInputStream bais = new ByteArrayInputStream(pdf.getBytes());
              
            /* Add every base64 decoded PDF within the PDFMergerUtility Object  */
				obj.addSource(Base64.getDecoder().wrap(bais));
			}	
          /* Now the PDFMergerUtility Object has all of the PDFs. Use mergeDocuments methodology to merge the PDFs */
			obj.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
		 /* Return the mergedPDF as a byte array utilizing the ByteArrayOutputStream object */
			return vacation spot.toByteArray();
          
		} catch (IOException e) {
	        throw new Exception("Error occurred while merging pdf files", e);
	    }
		
		
	}

}
  • mergeAndStorePDF – This static methodology accepts two arguments (listPdfFileNames and mergedPdfFileName) and has no return kind. Learn the feedback within the Java class to know each step.
  • mergePDFs – This static methodology accepts one argument (base64PDF) and has the return kind as a byte array. This byte array is definitely the merged PDF file in byte array format. Learn the feedback within the Java class to know each step.

Step 3

Drag and drop an SFTP Record Connector and add the SFTP credentials within the SFTP config. Add the Listing Path and Filename Sample as {*.pdf}. This can retrieve all of the PDF recordsdata from the trail talked about within the property file.

Step 4

Subsequent, initialize a variable base64PDF as a clean array []. This variable will include all base64 encoded PDF strings. Add a alternative element after that to examine if the payload is empty (i.e., the SFTP Record connector picked up any recordsdata or not). If no recordsdata are retrieved then simply log a message No recordsdata discovered. In any other case, use a For-Every element to iterate by way of all of the PDF recordsdata retrieved.

Step 5

Subsequent, learn every PDF as proven above, encode it, and retailer it as a base64 encoded string within the variable base64PDFEncode the PDF utilizing toBase64() methodology of dw::core::Binaries library as proven beneath.

Step 6

Subsequent, name the static methodology mergePDFs of sophistication MergeMultiplePDFGo the record of base64 encoded PDF strings (saved within the variable base64PDF) as an argument to the tactic mergePDFsThe mergePDFs methodology will return the concatenated PDF in byte array format. Encode that byte array to base64 encoded string and retailer it in a variable.

Now, assemble the response payload of MimeType  multipart/form-dataDecode the base64 encoded merged PDF and move it within the content material discipline. Set the Content material-Sort as software/pdf as proven above.

Step 7

Set the MimeType as software/pdf. This can ship the merged PDF as a pdf as a response. You too can retailer this payload in an SFTP output listing.

Enter PDFs

PDF1


PDF2


Output PDF

Merged PDF

The merged PDF can have a complete of all of the pages that every PDF has.

Conclusion

That is how one can merge a number of PDF recordsdata into one PDF and get the merged PDF as a response or retailer the merged PDF in a file location.

Thanks for studying the article and you probably have any questions please be happy to jot down it down within the feedback part.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version