Categories
JavaScript Answers

How to render a PDF file using a base64 file source instead of URL with Pdf.js?

Spread the love

Sometimes, we want to render a PDF file using a base64 file source instead of URL with Pdf.js.

In this article, we’ll look at how to render a PDF file using a base64 file source instead of URL with Pdf.js.

How to render a PDF file using a base64 file source instead of URL with Pdf.js?

To render a PDF file using a base64 file source instead of URL with Pdf.js, we convert the base64 URL into a Uint8Array.

For instance, we write

const BASE64_MARKER = ";base64,";

const convertDataURIToBinary = (dataURI) => {
  const base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  const base64 = dataURI.substring(base64Index);
  const raw = window.atob(base64);
  const rawLength = raw.length;
  const array = new Uint8Array(new ArrayBuffer(rawLength));

  for (let i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
};

const pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK...";
const pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray);

to define the convertDataURIToBinary .

to get the base64 content with dataURI.substring(base64Index).

Then we call atob with base64 to decode the base64 string.

Next, we create a Uint8Array with an ArrayBuffer.

Then we put the decoded base64 content into the array Uint8Array.

Next, we call convertDataURIToBinary with pdfAsDataUri to convert the base64 URL to a Uint8Array.

And then we call getDocument with the Uint8Array to render it.

Conclusion

To render a PDF file using a base64 file source instead of URL with Pdf.js, we convert the base64 URL into a Uint8Array.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.