Search code examples
javaservletspdfresponsebytestream

How to display pdf from byte[] stream in browser?


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 ?


Solution

  • 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