Display embedded PDF in Internet Explorer 11 from binary string or base64

roray picture roray · Oct 21, 2016 · Viewed 10k times · Source

There is a 3rd party service which sends me a PDF file in either binary string or base64 encoded. Is there any possibility to display the PDF embedded in IE 11 using either binary string or base64 encoded.

From SO and other forums, I concluded that IE 11 supports data uri only for images and not PDF (I might be wrong) which rules out base64. So the only option left is to display from binary string. I am using it in a Node App but I do not have the option to first save the retrieved file to Node server and use static URL.

Please let me know if above is achievable in IE 11.

Currently I'm trying to use npm package of https://github.com/pipwerks/PDFObject. For Chrome & Firefox, I retrieve the base64 file and embed it using the above package and works fine.

Answer

roray picture roray · Dec 19, 2016

This solution uses pdf.js

Key steps in rendering a base64 PDF using PDF.js library

  • First decode it using atob
  • Then initializing a Uint8Array using above decoded data

Abstract from express-pdfjs/scripts/App.js

let options = {
      method: 'GET',
      uri: 'http://localhost:5000/getBase64Pdf',
      resolveWithFullResponse: true
    }
rp(options)
  .then((response) => {
    if (response.statusCode !== 200) {
      console.error('http not 200 but : ', response.statusCode)
    } else {
      console.info('connected successfully : ' + response.statusCode)
      let pdfData = atob(response.body)
      let uint8ArrayPdf = new Uint8Array(pdfData.length)
      for (let i = 0; i < pdfData.length; i++) {
        uint8ArrayPdf[i] = pdfData.charCodeAt(i)
      }
      let pdfjsframe = document.getElementById('pdfViewer');
      pdfjsframe.contentWindow.PDFViewerApplication.open(uint8ArrayPdf);
    }
  })

pdfViewer is an iframe in index.html

<iframe id="pdfViewer" src="http://localhost:3000/express-pdfjs/pdfViewer/web/viewer.html" height="1600" width="850" />

Please find a sample implementation for this using React on client side @ https://github.com/rohanray/so-pdf-base64

Update: Also have a look at @user3590235 answer : Display embedded PDF in Internet Explorer 11 from binary string or base64