Skip to Content

In this Document I would like to share how to create a password protected PDF file in SAP PI using Custom Adapter Module.

Requirement: Pick the sample file from source ftp and pass the file as WinZip with password protected PDF file to target FTP through SAP PI. The Password protected PDF file needs to be zipped and sent to customer location.


/wp-content/uploads/2012/12/pdf_169180.jpg

To achieve this requirement I have used Custom adapter module to create password protected pdf file.

Pre-requisite:

IText library jar –Creating PDF

BouncyCastle – Encrypting the PDF( iText internally uses bouncycastle.org library to encrypt the PDF files).

Jars Used:

  • itext-1.4.8.jar
  • bcprov-jdk15-146.jar

Initially when I started, I was facing the problem with the PDF file being written to NFS with the below statement.

  1. PdfWriter.getInstance(document, new FileOutputStream(

  “/Interface/TEST/AAE/Sucess.pdf”));


Here pdf was getting created but the same file was not getting zipped by payloadZipbean. The trick was to send the output as byte stream and pass it to the next module instead of writing it as a file

Instead of writing the stream to the FileOutputStream I passed the output to ByteArrayOutputStream.

Module code for creating Password protected PDF file.

package com.sap.adaptermodule;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import com.lowagie.text.pdf.*; 
import com.lowagie.text.*;
import com.sap.engine.interfaces.messaging.api.*;
import com.sap.aii.af.lib.mp.module.*;
import com.sap.engine.interfaces.messaging.api.Message;
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;
/**
* @author Srikanth Kakani
*
*/
public class PDFwithPasswordBean implements SessionBean, Module {
      public static final String VERSION_ID = "$Id://tc/aii/30_REL/src/_adapters/_sample/java/user/module/PDFwithPassword_EJBBean.java#1 $";

      static final long serialVersionUID = 7435850550539048633L;

      public void ejbRemove() {
      }

      public void ejbActivate() {
      }

      public void ejbPassivate() {
      }

      public void setSessionContext(SessionContext context) {

      }
      public void ejbCreate() throws javax.ejb.CreateException {
      }

      public ModuleData process(ModuleContext  moduleContext,
                 ModuleData inputModuleData) throws ModuleException {
 AuditAccess audit = null;
 Object obj = null;
 Message msg = null;
 MessageKey key = null;
                 Payload pload = null;
 String Ownerpassword; // Password required to open PDF
 String Userpassword;    // Password for encrypting the PDF file

            try {
 obj = inputModuleData.getPrincipalData();
 msg = (Message) obj;
                 
 key = new MessageKey(msg.getMessageId(), msg.getMessageDirection());
 audit = PublicAPIAccessFactory.getPublicAPIAccess().getAuditAccess();
 audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS," Before getting main payload");
              
              //To get Message Payload
 pload = msg.getMainPayload();
                  // Storing the Payload Content in a Sting
                  String inputMsgPayload = new String(pload.getContent());
                 
 //Defining Size of the pdf document
 Document document = new Document(PageSize.A4, 36, 72, 108, 180);
                  //For Passing the output as array outputstream
 ByteArrayOutputStream output = new ByteArrayOutputStream();
                 
 //writing the pdf document data into output
 PdfWriter writer = PdfWriter.getInstance(document, output);
                 
 //setting the runtime parameters which we can pass from Communication channel as Adapter Module parameters to the Module Context
 Ownerpassword = (String) moduleContext.getContextData("pwd_Owner");
 Userpassword = (String) moduleContext.getContextData("pwd_User");
                 
 //writer.setEncryption() Method to set password to generated PDF
 writer.setEncryption(Userpassword.getBytes(), Ownerpassword.getBytes(),
 //we can provide multiple permissions by ORing different values.
//For example PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY.
 PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                 
                 
 document.open();
 //To print the current Date in the pdf file
 document.add(new Paragraph(new Date().toString()));
 document.add(new Paragraph("Input payload is:"));   
 //Printing input Message payload in the pdf file.
 document.add(new Paragraph(inputMsgPayload));
                 
 document.close();
                 
 //converting the Byte Array Stream into Byte
 byte byt[] = output.toByteArray();
 audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS," -------outputStream is------ "
                                                 +output.toString());
                  //set the payload in bytes
                                                pload.setContent(byt);
                                                msg.setMainPayload(pload);
                                                //Passing the main payload to inputmoduledata
                                                inputModuleData.setPrincipalData(msg);
                                               
            }
 //Exception Handling
            catch (Exception e) {
 ModuleException me = new ModuleException(e);
            }            return inputModuleData;

      }

}

Receiver communication channel configurations.

Below are the configurations to create zip file in ftp

/wp-content/uploads/2012/12/clip_image002_169196.jpg

Below are the Receiver module configurations


Here I am passing the output stream of the pdf file to MessageTransformbean.

The MessageTransformbean will set the file name as Success.pdf and it will send the data to the Standard PayloadZipbean module.This PayloadZipbean module will create a zip file in the target ftp directory.

/wp-content/uploads/2012/12/greenshot_2012_12_26_11_51_33_module_169197.jpg

Note: If we put the Parameter Name as pwd_xxx in the module configuration, automatically it will take the Parameter Value as password text as showed in the screen shot.

Output File in Target FTP:

/wp-content/uploads/2012/12/greenshot_2012_12_26_12_10_42zip_169201.jpg

Zipped Output file containing PDF:
/wp-content/uploads/2012/12/greenshot_2012_12_26_11_55_29_169198.jpg

Here is the Output PDF

/wp-content/uploads/2012/12/greenshot_2012_12_26_11_58_52_output_169199.jpg

To report this post you need to login first.

14 Comments

You must be Logged on to comment or reply to a post.

    1. Former Member Post author

      Hi Praveen,

      If you put Parameter Name as pwd_xxx in the module configuration, by default it will take the parameter value as password text.

      Thanks,

      Srikanth

      (0) 
  1. Azeem Syed

    its a better explain end to end interface.because new developers can’t understand(i suggest prepare end to end document).as my knowledge its a good document.

    Regards ,

    Syed.

    (0) 
  2. Shabarish Vijayakumar

    good one. Quick question, what is the relevance of user pwd? and how do you set it within the api i.e is it is a fixed pwd for the itext api whenever encryption has to be done?

    (0) 
    1. Former Member Post author

      Thanks Shabz.. 🙂

      user pwd is a parameter to the module. which used to open the document once it is created. and yes it is a fixed encryption method for the iText api.

      (0) 
  3. Former Member

    Just wrote this code, haven’t tested but I hope this could help…

    /*

    * Created on May 26, 2014

    *

    * To change the template for this generated file go to

    * Window>Preferences>Java>Code Generation>Code and Comments

    */

    package packme;

    /**

    * @author ashutosh.a.upadhyay

    *

    * To change the template for this generated type comment go to

    * Window>Preferences>Java>Code Generation>Code and Comments

    */

    import java.io.BufferedReader;

    import java.io.ByteArrayOutputStream;

    import java.io.InputStreamReader;

    import javax.ejb.CreateException;

    import javax.ejb.SessionBean;

    import javax.ejb.SessionContext;

    import com.lowagie.text.Document;

    import com.lowagie.text.PageSize;

    import com.lowagie.text.Paragraph;

    import com.lowagie.text.pdf.PdfWriter;

    import com.sap.aii.af.mp.module.Module;

    import com.sap.aii.af.mp.module.ModuleContext;

    import com.sap.aii.af.mp.module.ModuleData;

    import com.sap.aii.af.mp.module.ModuleException;

    import com.sap.aii.af.ra.ms.api.Message;

    import com.sap.aii.af.ra.ms.api.MessageDirection;

    import com.sap.aii.af.ra.ms.api.XMLPayload;

    import com.sap.aii.af.service.auditlog.Audit;

    import com.sap.aii.af.service.auditlog.AuditDirection;

    import com.sap.aii.af.service.auditlog.AuditLogStatus;

    import com.sap.aii.af.service.auditlog.AuditMessageKey;

    /**

    * @ejbHome <{com.sap.aii.af.mp.module.ModuleHome}>

    * @ejbLocal <{com.sap.aii.af.mp.module.ModuleLocal}>

    * @ejbLocalHome <{com.sap.aii.af.mp.module.ModuleLocalHome}>

    * @ejbRemote <{com.sap.aii.af.mp.module.ModuleRemote}>

    * @stateless

    */

    public class TextToPDF implements SessionBean, Module{

      private SessionContext myContext;

      AuditMessageKey amk;

      public void ejbRemove(){

      }

      public void ejbActivate(){

      }

      public void ejbPassivate(){

      }

      public void setSessionContext(SessionContext context){

      myContext = context;

      }

      public void ejbCreate() throws CreateException {

      }

      public ModuleData process(ModuleContext moduleContext,ModuleData inputModuleData)throws ModuleException {

      String text = “”;

      String line = “”;

      Object obj = inputModuleData.getPrincipalData();

      Message msg = null;

      XMLPayload xp = null;

      msg = (Message) obj;

      try {

     

      if (msg.getMessageDirection()== MessageDirection.INBOUND)

      amk = new AuditMessageKey(msg.getMessageId(),AuditDirection.INBOUND);

      else

      amk = new AuditMessageKey(msg.getMessageId(),AuditDirection.OUTBOUND);

     

      xp = msg.getDocument();

      Audit.addAuditLogEntry(amk, AuditLogStatus.SUCCESS,”XML payload object received.”);

     

      if (xp != null){

      Audit.addAuditLogEntry(amk, AuditLogStatus.SUCCESS,”Converstion started….”);

      InputStreamReader in = new InputStreamReader(xp.getInputStream());

      BufferedReader bin = new BufferedReader(in);

      while((line = bin.readLine()) != null){

      System.out.println(line);

      text = text+line;

      text = text+”\n”;

      }

      in.close();

      bin.close();

      byte by [] = text.getBytes();

      Document document = new Document(PageSize.A4, 36, 72, 108, 180);

      ByteArrayOutputStream output = new ByteArrayOutputStream();

      PdfWriter.getInstance(document,output);

      document.open();

      document.add(new Paragraph(text));

      System.out.println(“Text added”);

      document.close();

      byte byt[] = output.toByteArray();

      xp.setContent(byt);

      Audit.addAuditLogEntry(amk, AuditLogStatus.SUCCESS,”Conversion Done Successfully.”);

      }

       inputModuleData.setPrincipalData(msg);

       Audit.addAuditLogEntry(amk, AuditLogStatus.SUCCESS,”Principle data is set successfully.”);

      }

        catch (Exception e){

      Audit.addAuditLogEntry(amk, AuditLogStatus.SUCCESS,”Module Exception Caught .”);

      ModuleException me = new ModuleException(e);

      throw me;

        }

        return inputModuleData;

      }

    }

    (0) 
  4. vinay mittal

    Really informative i am always saving up a local copy of such blogs in case i need to go through it i will save this one too thanks buddy

    (0) 

Leave a Reply