Farhan
Farhan

Reputation: 109

Certain PDFs display blank when displayed using Base64 String

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 ?

Upvotes: 2

Views: 4441

Answers (1)

ultimoTG
ultimoTG

Reputation: 953

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.

Upvotes: 5

Related Questions