Categories
JavaScript Answers

How to display PDF from an array buffer with JavaScript?

Spread the love

Sometimes, we want to display PDF from an array buffer with JavaScript.

In this article, we’ll look at how to display PDF from an array buffer with JavaScript.

How to display PDF from an array buffer with JavaScript?

To display PDF from an array buffer with JavaScript, we can use the Fetch API.

For instance, we write:

<iframe id='pdfViewer'>

</iframe>

to add an iframe.

Then we write:

const pdfSrc = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf';

(async () => {
  const res = await fetch(pdfSrc)
  const data = await res.arrayBuffer()
  $("#pdfViewer").attr("src", URL.createObjectURL(new Blob([data], {
    type: "application/pdf"
  })))
})()

to call fetch with the pdfSrc to fetch the PDF binary.

Then we call res.arrayBuffer to assign the response to data.

Next, we call attr to set the src attribute to a URL that we create from the data PDF binary by converting that to a Blob instance.

If CORS is allowed, then the PDF should be displayed in the iframe.

Conclusion

To display PDF from an array buffer with JavaScript, we can use the Fetch API.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *