Odeon Odeon - 3 months ago 23
Javascript Question

How can I preview a PDF file generated from an external API in an iframe of my webpage, using Javascript?

I've been trying to find an example online where a PDF is returned by an external API (file sent in response, with the response headers for the Content-Type set to application/pdf) and then the file is processed in JS and shown in an embedded div/iframe.

I've been trying to find an example of that using PDF.js or PDFObject but all I can find use direct path to pdf files hosted on the server. I need to do this on the client-side and the file can only be retrieved using an API.

I apologize if that has been responded somewhere but I can't find anything matching my request, I hope I'm describing it well enough!

//Pseudo code of what I'd like to achieve
$.get('http.service.com/getPDF', function(data) {
var pdfString = changeDataToPDFString(data);

magicLibrary.previewPDF(pdfString, $('#container_pdf'));
}

Answer

For whomever stumbles upon this, here is my very specific solution using RequireJS and PDFJS.

     changeDataToPDFString: function(file) {
         var base64ToUint8Array = function(base64) {
            var raw = atob(base64),
                uint8Array = new Uint8Array(raw.length);

            for (var i = 0; i < raw.length; i++) {
                uint8Array[i] = raw.charCodeAt(i);
            }

            return uint8Array;
         },
         base64Data = file.split(',')[1],
         pdfData = base64ToUint8Array(base64Data);

         return pdfData;
    },
    renderPDF: function(file, container) {
        var self = this,
            pdfData = self.changeDataToPDFString(file);

        require(['pdfjs-dist/build/pdf'], function(app){
            var iframe;

            if(container.find('iframe').length) {
                iframe = container.find('iframe')[0];
                iframe.contentWindow.PDFViewerApplication.open(pdfData);
            }
            else {
                iframe = $('<iframe src="js/lib/pdfjs/web/viewer.html" style="width: 100%; height: 700px;" allowfullscreen="" webkitallowfullscreen=""></iframe>')[0];
                iframe.onload = function() {
                    iframe.contentWindow.PDFViewerApplication.open(pdfData);
                }
                container.append(iframe);
            }
        });
    }