Jeff
Jeff

Reputation: 1800

Rendering PDFs in ie inside the browser

I've looked at so many different SO posts about this today.

I have an application that needs to show PDF documents inside the browser. This application also needs to run in IE (11+).

Here's the thing: an iframe with a src works just fine. Something like:

<iframe src="www.myurl.com/thedocument"></iframe>

However, www.myurl.com/thedocument is now protected by oAuth. What this means is I need to request www.myurl.com/thedocument with the appropriate authorization header credentials.

This means (i think), that I have to request www.myurl.com/thedocument via ajax. The ajax request returns base64, or a byte[] containing the document.

IE doesn't support data URIs to render PDFs, so i can't just splat the response from my ajax request into the iframe.

So.. now I'm stuck.

Any ideas?

Thanks

Upvotes: 7

Views: 1148

Answers (1)

tmw
tmw

Reputation: 482

One option would be to use PDF.js, a javascript library for rendering PDFs into an HTML5 canvas with support for IE10+. The library supports loading PDF data from a TypedArray (e.g. Uint8Array), that could be produced from the result of an ajax request.

I've prepared a short example here that displays a single page PDF stored in a base64-encoded binary. To avoid performing the base64 conversion, a TypedArray could also be retrieved directly from an XMLHttpRequest response:

function reqListener () {
    var byteArray = new Uint8Array(this.response);
    PDFJS.getDocument(byteArray).then(function(page) {
        // ....
    });
}

var req = new XMLHttpRequest();
req.addEventListener("load", reqListener);
req.responseType = "arraybuffer";
req.open("GET", "http://www.example.com/example.pdf");
req.send();

To support the features that you would expect in a native pdf viewer (printing etc.) the library includes an example viewer that you can adapt for your own purposes.

Upvotes: 3

Related Questions