0

I am new to groovy and to this forum. I am using a middleware tool (SAP CPI) where I am getting a PDF in base64 string format. I need to send the PDF to another system. This is what I did:

  • Store the Base64 input in a string.
  • Pass it through a Base64 Decoder (this is an inbuilt function)
  • Use below code and pass the base64 string as an input to "body":
    import com.sap.gateway.ip.core.customdev.util.Message;
    import java.util.HashMap;
    def Message processData(Message message){
    def body = message.getBody(String.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
    outputStream.write(body.getBytes())
    message.setBody(outputStream.toString())
    return message;
    }
    

What I get as an output looks something like below:

%PDF-1.7
%????
5 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
14 0 obj
<</Title(T....

and so on...

Now when I save this output as a pdf file, it is either blank or it says

There was an error opening this document. The file is damaged and could not be repaired.

What am I doing wrong? Thanks in advance!

Note: Due to limitation of the middleware, I cannot create a whole project, but will rather have to use processData() function and can manipulate the string inside it. Thanks!

Sandra Rossi
  • 11,934
  • 5
  • 22
  • 48
  • PDF is not a string. So problem appeared when you try to convert bytes to string outputStream.toString() – daggett May 30 '21 at 07:31
  • Thanks for your response.I have tried removing the toString() and using the binary output. I copy and paste the output in a notepad and save it as a pdf file. But when I open it, it still gives me the same error. Anything else I should try? – VoiceOfReason May 30 '21 at 10:10
  • You can't copy paste binary data into notepad because notepad supports only text encodings.. – daggett May 30 '21 at 10:24
  • did some more tweaking and turned out converting it to string was actually the problem. the code looks like: import com.sap.gateway.ip.core.customdev.util.Message; import java.util.HashMap; def Message processData(Message message) { def text = message.getBody(String) byte[] decoded = text.decodeBase64() def out = new String(decoded) message.setBody(out) return message } Now I am able to open the output as a pdf. Thank you! – VoiceOfReason May 30 '21 at 11:39

0 Answers0