0

I am using a servlet and passing the http response with the byte[] stream to the browser. I have set response.setContentType("application/pdf"); in my java code but it still display garbage code like : JVBERi0xLjQKJeLjz9MKNCAwIG9iago8PC9UeXBlL1hPYmplY3QvQ29sb3JTcGFjZS9EZXZpY2VSR0IvU3VidHlwZS9JbWFnZS9CaXR

What should I do to correctly view the pdf into the browser ?

david a.
  • 5,283
  • 22
  • 24
  • possible duplicate of [Showing PDF bytestream in the response in a new browser window](http://stackoverflow.com/questions/25762363/showing-pdf-bytestream-in-the-response-in-a-new-browser-window) – GregD Mar 02 '15 at 13:33
  • The "garbage" you're getting looks like a base64-encoded PDF header. – david a. Mar 02 '15 at 13:34
  • 1
    The suggested duplicate seems to be a problem with content type headers, but this looks more like a base64 encoding issue, while the contentType part is actually handled properly, as the OP suggested. – GPI Mar 02 '15 at 13:38

1 Answers1

1

PDF documents can easily be recgnozied because their first characters are %PDF followed by a version number.

You can see here that the displayed content does not follow that rule, so that is no PDF. Still, this String looks a lot like Base 64 encoded content, and indeed, if you are to try a base64 decoder, you'll see that the decoded output prints a doc that starts with :

%PDF-1.4
... some binary stuff

Therefore, what seems to be missing is the decoding of the content, prior to sending it through the response. To perform this decoding, Apache Commons Codec has a flexible implementation of Base64 encoding and decoding, but you can also use various classes and utils to do the job. See the answers on this SO thread :

Decode Base64 data in Java

Community
  • 1
  • 1
GPI
  • 9,088
  • 2
  • 31
  • 38