37

I have to display base64 pdf in new tab. I am using below code

 var windo = window.open("", "");  
 var objbuilder = '';
 objbuilder += ('<embed width=\'100%\' height=\'100%\'  src="data:application/pdf;base64,');
 objbuilder += (fileData);
 objbuilder += ('" type="application/pdf" />');
 windo.document.write(objbuilder); 

It is working in FireFox and not working in Chrome and IE. I even tried with tag, but same output, working in FF but not in Chrome and IE.

I look into below JsFiddles, for which are working in FF but not in Chrome,

http://jsfiddle.net/yLx2W/

http://jsfiddle.net/yLx2W/1/

My Chrome version is : Version 54.0.2840.99 m

FireFox Version : 49.0.2

How can this be done?

1
  • In my case when I tried to display base 64 encoded pdf string in iframe, it displayed blank page. It is working properly only on Firefox. After spending a day to make it work I finally found cause of error. In my PDF document I embedded HTML code that is generated from text editor, when I removed those HTML codes it started working. I found code blocks that are causing this error but there is no logical meaning the cause of bug. It is too long to explain what kind of bug I had, but all I can say is that it is totally nonsense. Jun 12, 2019 at 12:45

5 Answers 5

29

for those who still can't do it, i found this in someone else answer, but i don't remember who...

var objbuilder = '';
objbuilder += ('<object width="100%" height="100%" 
data="data:application/pdf;base64,');
objbuilder += (myBase64string);
objbuilder += ('" type="application/pdf" class="internal">');
objbuilder += ('<embed src="data:application/pdf;base64,');
objbuilder += (myBase64string);
objbuilder += ('" type="application/pdf"  />');
objbuilder += ('</object>');

var win = window.open("#","_blank");
var title = "my tab title";
win.document.write('<html><title>'+ title +'</title><body style="margin-top: 
0px; margin-left: 0px; margin-right: 0px; margin-bottom: 0px;">');
win.document.write(objbuilder);
win.document.write('</body></html>');
layer = jQuery(win.document);

this way we open the pdf in a new tab.

7
  • Thx. Your solution works great with PDFKIT from node.js Feb 17, 2019 at 11:41
  • I have base64String data and need to open in mvc view using iframe control. I am trying to use embed and ifame but none of them working. var pdfData = '@Model.PdfDataString'; $("iframe").attr("src", 'data:application/pdf;base64,{0}'.replace('{0}', pdfData)); $("embed").attr("src", 'data:application/pdf;base64,{0}'.replace('{0}', pdfData)); May 7, 2019 at 20:24
  • sorry, i'm not into MVC
    – CHACO
    May 14, 2019 at 13:09
  • @chaco it's not working for big pdfs in chrome. like this one jsfiddle.net/eqc3umab Sep 28, 2019 at 6:26
  • it allows up to 9 pages i guess
    – CHACO
    Sep 30, 2019 at 14:16
22

It should work with Chrome you can use

<iframe src="data:base64...">

<object data="data:base64...">

I've faced the same issue with IE: it's impossible to display a pdf with a base64 string.

I had to generate temporary files on the server to display them with IE he only display existing file by using a path.

You still can use JS library to display your pdf like PDF.js.

4
  • 3
    I tried Object and iframe also tried URIdata, but not working in Chrome You can see below JSFiddles, jsfiddle.net/yLx2W jsfiddle.net/yLx2W/1 Nov 18, 2016 at 10:28
  • 1
    I've just copy and paste the code on Jsfiddle in a html file and launch it with Chrome, it works
    – Alexis
    Nov 18, 2016 at 12:09
  • Agree... It does not work on fiddle, but it works locally. I use the same code (the iframe one) but it does not work with my data. When it works with the example of @dnyaneshwar
    – NicoESIEA
    Feb 14, 2020 at 23:47
  • How about large PDF files ? It's working with small pdf good, but no large pdf files.
    – dnaz
    Mar 5 at 19:23
7

When the above answer's do not work due to Size Limitations, you can try this solution, it worked for me when I was trying to convert 16+ page PDFs from Base64 back into a PDF in Chrome.

The fix is to convert the base64 back into Binary, pack it inside of a Blob, and then set the iframe's "src" to a Blob-URI pointing to that blob.

var base64 = ("yourBase64StringVariable")
const blob = base64ToBlob( base64, 'application/pdf' );
const url = URL.createObjectURL( blob );
const pdfWindow = window.open("");
pdfWindow.document.write("<iframe width='100%' height='100%' src='" + url + "'></iframe>");

function base64ToBlob( base64, type = "application/octet-stream" ) {
  const binStr = atob( base64 );
  const len = binStr.length;
  const arr = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    arr[ i ] = binStr.charCodeAt( i );
  }
  return new Blob( [ arr ], { type: type } );
}

Original Source of this answer - Open base64 encoded pdf file using javascript. Issue with file size larger than 2 MB

1
  • 1
    Thank you. You saved me. This the solution I'm looking for.
    – Duy Lan Le
    Apr 5, 2022 at 20:44
2
function printPreview(data){
        var type = 'application/pdf';
        let blob = null;
        const blobURL = URL.createObjectURL( pdfBlobConversion(data, 'application/pdf'));
        const theWindow = window.open(blobURL);
        const theDoc = theWindow.document;
        const theScript = document.createElement('script');
        function injectThis() {
            window.print();
        }
        theScript.innerHTML = 'window.onload = ${injectThis.toString()};';
        theDoc.body.appendChild(theScript);
    }
  //converts base64 to blob type for windows
    function pdfBlobConversion(b64Data, contentType) {
          contentType = contentType || '';
          var sliceSize = 512;
          b64Data = b64Data.replace(/^[^,]+,/, '');
          b64Data = b64Data.replace(/\s/g, '');
          var byteCharacters = window.atob(b64Data);
          var byteArrays = [];

          for ( var offset = 0; offset < byteCharacters.length; offset = offset + sliceSize ) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
              byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
          }

          var blob = new Blob(byteArrays, { type: contentType });
          return blob;
        }

pass base64 data to this function and it will show the pdf in new window. This is working in chrome and firefox not in IE. Any help Please. I want it to work in IE also. Its giving error where I give the bloburl to window.

2

Here '@Model.binaryDocument' is the base64 data

1)By Model

<object>
   <embed id="pdfID" type="text/html" width="1200" height="600" src="data:application/pdf;base64,@Model.binaryDocument" />
</object>

2)By js

  $(document).ready(function () {
    var b64Data = "@Model.binaryDocument";
    var contentType = "application/pdf";
     const blob = b64toBlob(b64Data, contentType);
    const blobUrl = URL.createObjectURL(blob);

    (window as Window).location = blobUrl;
  })

const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
    const byteCharacters = atob(b64Data);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) 
       {
        const slice = byteCharacters.slice(offset, offset + sliceSize);

        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }

    const blob = new Blob(byteArrays, { type: contentType });
    return blob;
}

First solution is better for prevent auto downloading pdf.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.