2

I am trying to show PDF file in a web page using its base64.

below is reactJS code for the same.

<object style={{ width: '100%', height:'842pt' }} type="application/pdf" data={`data:application/pdf;base64,${props.docImageData.base64Image}`} />

so using above code my view in web page is blank but the base64 is absolutely valid since I have verified in online viewer (https://base64.guru/converter/decode/pdf) so over here also I am able to download generated pdf but the preview went blank. Is it some browser issue ?

Please also note that base64 size is around 4.2 MB, is there any size constraint ?

Farhan
  • 105
  • 1
  • 10
  • Have you tried logging the value of `props.docImageData.base64Image`. May be it's not defined or not coming through? Also, the HTML `object` tag doesn't have a style property. However, it does have `height` and `width` properties. May be try using something like - ` – ultimoTG Sep 24 '20 at 22:13
  • yes, I have tried logging props.docImageData.base64Image and I have verified the result in online viewer (https://base64.guru/converter/decode/pdf) over here also preview went blank but the download option over the page gives me exact pdf file. – Farhan Sep 25 '20 at 08:48
  • yes, I experienced the same issues you did when I tried to load a 4.4 MB base64 string in the browser. Smaller files worked fine but the browser would show a blank screen for big files. I also made the https://base64.guru/converter/decode/pdf site crash a couple of times trying to convert it. :) But I did find an alternate solution that works well. See my answer below. – ultimoTG Sep 27 '20 at 19:52

1 Answers1

4

If you're having issues loading PDF files in the browser using the <object> tag and large base64 strings, here's a solution you can try.

Take your base64 string and turn it into a blob. Here, largePDF is equivalent to your props.docImageData.base64Image - this is the base64 string

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;
};

const blob = new Blob([b64toBlob(largePDF)], { type: 'application/pdf' });
const fileURL = URL.createObjectURL(blob);

**Code Credit for ** - Creating a BLOB from a Base64 string in JavaScript

Then, take the blob url and load that with the object tag: <object style={{ width: '100%', height:'842pt' }} type="application/pdf" data={fileURL} />

I tested this with a file that is 4.4 MB in size.

ultimoTG
  • 853
  • 6
  • 9