Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed PDF Byte Data in HTML

This should be working, but it seems I am missing something.

I have a pdf file on a local drive. Obviously Chrome and other browsers can't get that local URL since it's sandboxed, so I have a servlet pulling the data from the local drive and sending it back through an ajax call to the web client. I'm not getting any errors, and it seems a pdf viewer is loading, but the file itself won't display. I am encoding it ahead of time, but it still won't work. I will display my numerous approaches below, but I won't include the servlet code since that seems to be working.

Attempt 1:

function embedFile(){
    $.get("FileGetter", function(pdfText){

        var base64EncodedPDF = b64EncodeUnicode(pdfText);
        $("#embedHolder").append("<object id='embedder' width='80%' height='600px'><embed width=100% height=100%"
                                     + ' type="application/pdf"'
                                     + ' src="data:application/pdf;base64,'
                                     + base64EncodedPDF
                                     + "></embed></object>");

            });
        }

 function b64EncodeUnicode(str) {
     return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
                return String.fromCharCode('0x' + p1);
            }));
        }

Attempt 2:

function embedFile(){
    $.get("FileGetter", function(pdfText){

        var base64EncodedPDF = b64EncodeUnicode(pdfText);
        var obj = $('<object id="repObjID" type="application/pdf" width="100%" height="600" border="2"></object>'); 
        obj.attr('data',base64EncodedPDF); 
        var embed = $('<embed type="application/pdf"></embed>'); 
        embed.attr('src',base64EncodedPDF); 
        $('#repObjID').append(embed); 
        $("#docHolder").html(obj);
    }

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,               function(match, p1) {
                return String.fromCharCode('0x' + p1);
            }));
}    
like image 508
Marcel Marino Avatar asked Aug 01 '16 18:08

Marcel Marino


1 Answers

1. Download the binary data with ajax, into an arraybuffer

var xhr = new XMLHttpRequest;
xhr.open('get', '/path/to/pdf', true);
xhr.responseType = 'arraybuffer';
xhr.send();

2. Create Blob and Object URL

var blob = new Blob([xhr.response], {type: 'application/pdf'});
var url = URL.createObjectURL(blob);

3. Load URL in iframe

iframe.src = url;

Demo: https://webblocks.nl/tests/ajax-pdf.html

like image 178
Rudie Avatar answered Nov 12 '22 06:11

Rudie