0

We are using this approach to open the content of a PDF document in another tab

  var win = window.open();
  win.document.write('<iframe src="data:application/pdf;' + someDoc.url + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>')

However it seems that over some size the tab freezes and stays in continue loading. I have tried also with 5MB documents.

Is there any better approach to avoid this problem.

Browser used: Google Chrome 80.0.3987.122 or Firefox Extended Support Release (ESR)

davidetrapani
  • 540
  • 2
  • 7
  • 16
  • Some browsers only support data URLs up to some size limit, probably 2 MB. – mkl Feb 26 '20 at 12:20
  • @mkl this limit only applies to the address bar url, you can very well load bigger files from a dataURI: https://jsfiddle.net/nbfdakor/ – Kaiido Feb 26 '20 at 12:50

1 Answers1

1

Load your pdf from a blob:URI instead of from a data:URI.

var win = window.open();
var blob = base64ToBlob(someDoc.url, 'application/pdf');
win.document.write('<iframe src="' + URL.createObjectURL( blob ) + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></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 } );
}

live plnkr

There are bugs in Chrome's plugin and Firefox's pdf.js, I also experienced this problem while writing this answer on a very related question (which doesn't have an accepted answer and can't be used as dupe target).

Kaiido
  • 123,334
  • 13
  • 219
  • 285