0

My base64 PDF is too large that when I try and open it in a window, the url isn't pasted. I then substring'd it and the link would paste but of course.. it doesn't open as it hasn't received the whole base64.

Code:

   $.ajax({
    url: [database-url-here],
    type: 'GET',
    dataType: 'json',
    success: function(data){
      var pdf = (data.pdf).toString();

      window.open(pdf);
    }
  });
Rinchen
  • 27
  • 8

2 Answers2

1
var w = window.open('', '', 'width=400,height=240'); // open blank page
w.document.write(
  '<embed type="application/pdf" ' +
         'width="400" height="240" ' +
         'src="data:application/pdf;base64,' + pdf + '">'
);
Bob Sponge
  • 4,708
  • 1
  • 23
  • 25
  • Didn't work :/ The base64 still didn't paste into the browser URL. – Rinchen Mar 04 '16 at 15:47
  • Possible your data in `pdf` variable is malformed. Or if you tried `window.open(pdf);` you also can try to set `src` in this way: `'src="' + pdf + '">'` (in case `data:application/pdf;base64,` already is in pdf variable). – Bob Sponge Mar 04 '16 at 18:13
  • I've tested this code in Firefox and its works for me. – Bob Sponge Mar 04 '16 at 18:14
  • It works, but it doesn't paste it when there are too may base64 characters for the browser – Rinchen Mar 07 '16 at 16:54
  • Yep, 5mb pdf opening about 20 secs. You can also try https://github.com/mozilla/pdf.js/ – Bob Sponge Mar 09 '16 at 09:28
1

For too big base64 pdf files I convert it to blob and then create a new URL from that blob. Blob URL is much smaller then base64 url.

To convert I do something like this:

var url = 'data:application/pdf;base64,'+ base64string;
var blobUrl;
fetch(URL)
 .then(res => res.blob())
 .then(URL.createObjectURL)
 .then((ret) => {blobUrl=ret; return blobUrl;})
 .then(console.log)

One can test at this jsfiddle at example 2. Or see other alternatives here

dchang
  • 1,101
  • 10
  • 13