Displaying a PDF On React

Sometimes you have to display a PDF file on your application, even though it’s a niche feature to do you may be lost. This is going to be a simple follow along, using a library from https://www.npmjs.com/package/react-pdf.

First, let’s import the library into our application.

npm install --save react-pdf

Then we have to import it into our component that we are rendering the PDF file. For my example I have a Resume component that I would like to render the PDF file.

import React from 'react'import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';const Resume = () => {  return (    <div className='main-container'>    </div>  )
}

After we have access to 2 components that comes with the library, the Document and Page components. Document acts like a wrapper for Page.

const Resume = () => {  return (    <div className='main-container'>      <Document >        <Page />      </Document>    </div>  )
}

Document takes in a prop called “file”, this prop can be a URL, base64 content, Uint8Array, and more. So for my example I’m just going to import my PDF file and invoking it into the file prop.

import resume from '../resume.pdf'const Resume = () => {return (    <div className='main-container'>      <Document file={resume} >        <Page />      </Document>    </div>  )
}

Page also take in a prop, “pageNumber” and as you can guess it’s how many pages you are rendering.

const Resume = () => {return (  <div className='main-container'>    <Document file={resume} >      <Page pageNumber={1} />    </Document>  </div>  )
}

And that’s pretty much it, for more documentation checkout https://www.npmjs.com/package/react-pdf.

I’m a Software Engineer who is always learning something new!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store