6

I would like to convert a PDF to base64 and show on browser.

The problem is , the following code works for Firefox and Chrome

<iframe src="data:application/pdf;base64,encodeString></iframe>

But not in IE 9 + , suppose the user is using adobe reader plugin, are there any jquery plugin/workaround that allow embed a base64 pdf on iframe? thanks

4

3 回答 3

9

Note: For IE and other browsers like Mozilla, Chrome this works for me

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { 
    //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { 
        // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF1;
        window.open(dataURI, '_blank');
    }
}
于 2017-05-17T08:02:19.613 回答
3

As you've noticed, Internet Explorer does not support the use of DATA URIs as the source of IFRAMEs. The only workaround for this is to return your PDF content from a HTTP/HTTPS or FTP URI and use that as the source of the IFRAME.

于 2013-09-05T08:06:49.007 回答
1

For those that run into this issue later on. Dinesh Rajput's answer used to work, but msSaveOrOpenBlob() is now deprecated and should only be used on older versions of IE and Legacy versions of Edge. Now you can just set the iframe src to your pdf.

I know this is old, but I have been stuck on this for a while and I figured it out.

The issue is that Edge has a char limit for URIs. You have to turn your pdf into a blob first.

//Convert to blob
var byteCharacters = atob(response);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
     byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], { type: 'application/pdf' });

//Convert blob into URL Object
blob = window.URL.createObjectURL(blob);

 //Set URL Object as iFrame src
 document.getElementById('iframe').src = blob;

This should actually work for all modern browsers, so no need for browser/feature check.

于 2021-07-28T20:30:33.437 回答