cancel
Showing results for 
Search instead for 
Did you mean: 

Merging Multiple PDF Attachments into a Single PDF in SAP PI/PO Using Java Mapping

Laxman_shukla
Discoverer
0 Kudos

Hello!

Today I will try to explain how we can merge multiple PDF attachment input into single PDF.

In SAP Process Integration/Process Orchestration (PI/PO), efficient handling of document attachments is crucial for streamlined business processes. Often, there's a need to consolidate multiple PDF attachments into a single PDF file for easier management and distribution. In this blog, we'll explore how to achieve this seamlessly using Java Mapping.

Brief requirement: The real life scenario demanded to send a bundle of different third party system generated PDF as an attachment to SAP PI/PO . The multiple PDF should be merged together and send as an merged output to another third party application. 

  1. Understanding Input and Output:

    • Input: Multiple PDF attachments in the message payload.
    • Output: Single merged PDF file.
  2. Java Mapping Implementation:

    • Create a new Java Mapping program in SAP NetWeaver Developer Studio or SAP Integration Suite.
    • Import necessary libraries for PDF handling (e.g., iText).
    • Implement logic to:
      • Iterate through the input PDF attachments.
      • Extract content from each PDF attachment.
      • Append the content to the output PDF file.

 

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.Collection;

import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.io.*;

import com.sap.aii.mapping.api.AbstractTransformation;
import com.sap.aii.mapping.api.Attachment;
import com.sap.aii.mapping.api.InputAttachments;
import com.sap.aii.mapping.api.OutputAttachments;
import com.sap.aii.mapping.api.StreamTransformationException;
import com.sap.aii.mapping.api.TransformationInput;
import com.sap.aii.mapping.api.TransformationOutput;
//import com.sap.aii.mapping.api.exception.AttachmentNotFoundException;
import com.sap.engine.interfaces.messaging.api.MessageDirection;
import com.sap.engine.interfaces.messaging.api.MessageKey;
import com.sap.engine.interfaces.messaging.api.PublicAPIAccessFactory;
import com.sap.engine.interfaces.messaging.api.auditlog.AuditAccess;
import com.sap.engine.interfaces.messaging.api.auditlog.AuditLogStatus;

public class PDFMergingUtility extends AbstractTransformation {

    @Override
    public void transform(TransformationInput transformationInput, TransformationOutput transformationOutput)
            throws StreamTransformationException {

        final String DASH = "-";
        String msgID;
        String uuidTimeLow = "";
        String uuidTimeMid = "";
        String uuidTimeHighAndVersion = "";
        String uuidClockSeqAndReserved = "";
        String uuidClockSeqLow = "";
        String uuidNode = "";
        String msgUUID = "";
        AuditAccess audit;
        MessageKey msgKey;

        InputAttachments inputAttachments = transformationInput.getInputAttachments();
        OutputAttachments outputAttachments = transformationOutput.getOutputAttachments();

        try {
            msgID = transformationInput.getInputHeader().getMessageId();
            uuidTimeLow = msgID.substring(0, 8);
            uuidTimeMid = msgID.substring(8, 12);
            uuidTimeHighAndVersion = msgID.substring(12, 16);
            uuidClockSeqAndReserved = msgID.substring(16, 18);
            uuidClockSeqLow = msgID.substring(18, 20);
            uuidNode = msgID.substring(20, 32);
            msgUUID = uuidTimeLow + DASH + uuidTimeMid + DASH + uuidTimeHighAndVersion + DASH + uuidClockSeqAndReserved
                    + uuidClockSeqLow + DASH + uuidNode;
            msgKey = new MessageKey(msgUUID, MessageDirection.INBOUND);
            audit = PublicAPIAccessFactory.getPublicAPIAccess().getAuditAccess();
            audit.addAuditLogEntry(msgKey, AuditLogStatus.SUCCESS, "Java Mapping: Started");

            if (inputAttachments != null && inputAttachments.areAttachmentsAvailable()) {
                Collection<String> collectionIDs = inputAttachments.getAllContentIds(true);
                PDFMergerUtility pdfMerger = new PDFMergerUtility();

                for (String attachmentID : collectionIDs) {
                    Attachment attachment = null;
                    try {
                        attachment = inputAttachments.getAttachment(attachmentID);
                        String contentType = attachment.getContentType();

                        if (contentType.contains("pdf")) {
                            File tempFile = File.createTempFile("temp", ".pdf");
                            Files.write(tempFile.toPath(), attachment.getContent());
                            pdfMerger.addSource(tempFile);
                        }
                    } catch (Exception e) {
                        audit.addAuditLogEntry(msgKey, AuditLogStatus.WARNING,
                                "Attachment not found: " + attachmentID);
                    }
                }

                ByteArrayOutputStream mergedPDFStream = new ByteArrayOutputStream();
                pdfMerger.setDestinationStream(mergedPDFStream);
                pdfMerger.mergeDocuments(null);

                Attachment mergedAttachment = outputAttachments.create("MergedDocument.pdf",
                        mergedPDFStream.toByteArray());

      //Writing merged document as an attachment.
                outputAttachments.setAttachment(mergedAttachment);
                audit.addAuditLogEntry(msgKey, AuditLogStatus.SUCCESS, "Java Mapping: Merged PDF created");
            } else {
                audit.addAuditLogEntry(msgKey, AuditLogStatus.WARNING, "No attachments found");
            }
        } catch (Exception exception) {
            throw new StreamTransformationException(exception.toString());
        }
    }
}

 

 

Accepted Solutions (0)

Answers (0)