Display PDF with Visualforce

I have a PDF which is retrieved via web services calls. The PDF is sent over in a base64 encoded string. I would like to be able to visit a page and output the result of this request. Currently I am converting the encoded base64 string in to a binary blob (It doesn’t seem apex supports byte arrays? strange..). Is there a way for me to output this to the screen for the user? I would like to not have to save this; just output it.

Currently, I am using this:

Controller:

Blob PDFOutputBOL =  EncodingUtil.base64Decode(match1);

Page:

<apex:page controller="DownloadPDF" sidebar="false" showHeader="false" contentType="application/pdf">
{!PDFOutputBOL}
</apex:page>

Checking my HTTP response, I get the following:

HTTP/1.1 200 OK Date: Tue, 15 Jan 2013 14:18:36 GMT X-Powered-By:
Salesforce.com ApexPages P3P: CP=”CUR OTR STA” Cache-Control:
no-cache, must-revalidate, max-age=0, no-store, private Pragma:
no-cache Expires: Tue, 15 Jan 2013 14:18:36 GMT Content-Type:
application/pdf; charset=UTF-8 Content-Length: 40

core.filemanager.ByteBlobValue@6ed6c5ba

What can I do to just print the PDF?

Answer

You can embed a PDF in a Visualforce (or any other HTML) page via a data URI. Using your example, the code would be something like:

<apex:page controller="DownloadPDF" sidebar="false" showHeader="false" contentType="application/pdf">
    <script>
        window.location.href = "data:application/pdf;base64,{!match1}";
    </script>
</apex:page>

Note that you need the base64 encoded data – in your example, match1, rather than PDFOutputBOL.

Caveat: I don’t know how widely this is supported. Results of some informal testing:

Works on:

  • Mac OS X 10.6.8
    • Chrome 23.0.1271.101
    • Safari 5.1.7
  • Windows 7 SP1
    • Chrome 24.0.1312.52
    • Safari 5.1.7

Doesn’t work on:

  • Mac OS X 10.6.8
    • Firefox 17.0.1
  • Windows 7 SP1
    • IE 9.0.8112.16421
    • Firefox 18.0

You may be able to get it to work on those browsers with the appropriate plugin.

Attribution
Source : Link , Question Author : Kyle , Answer Author : metadaddy

Leave a Comment