How to render PDF docs in React with Adobe PDF Embed API (fetching URL).

Before I get to HOW I want to talk about WHY first. I was building a platform that would render PDF docs sourced out of my AWS s3 bucket and I just <Iframe>-ed it on the page which was easy to do and seems to work just fine. Well testing the application I have realized something — if you have a multi-page PDF doc that is being iframed (or <embed>) you won't be able to render it from a mobile device, the mobile browser will render it in an image and will show you only the first page of the document. That’s not gonna work for me and after exploring options I’ve come up with an idea to use Adobe Embed PDF API and here I’ll walk you through the setup for React app.

First of all, we need to create an account and generate a client id key to use it. It is free and upon creating the key it’ll ask you for the domain name it will be used from (side note: It won’t work from any other domain name and even localhost won’t be able to render the doc, although it’ll render the pdf reader so you can tell that it work).

create new credentials here:

  1. Add above’s script in ./public/index.html at the bottom of the body tag.

2. Create a document in ViewSDKClient.js in ./src/ViewSDKClient.js

3. Let’s fill it in:

I got this file from their GitHub repo and made a few changes, first of all, there are two places where you need to insert your generated client id.

4. Inside of the component you want to render a pdf you need to make sure you have a link for that available, like if you’re making an API call to get that link.

let me explain the logic here:

First, we import all the necessary things, especially ViewSDKClient file that we just created, then I used axios to make API call instead of fetch and React.useEffect instead of ‘ComponentDidMount’ since I’m using the functional component.

State to keep track of data after the fetch and re-render components accordingly.

making an API call to fetch data and store it on the state.

LoadPDF is a function that is called when <div> with an id of ‘pdf-div’ being loaded, which happens after we get a response back.

in our return, we first check if dataIsLoaded, defaults to false in our state, and until we get our promise, we’ll be rendering CircularProgress from the Material-UI library.

Second check if it hasFile, that we get in from the promise when data comes back, is it is we render

if not, we’ll render the message that there is no file.

Well finally when we get to load our <div id=”pdf-div”> that will fire up loadPDF function and it’ll attach pdf reader to that div. You might want to play around with the height and width of that div depending on your need.

That’s pretty much all of it, if you have any questions, please leave them in the comments.