Displaying PDF in React

Dhrubo Dh
3 min readFeb 4, 2021

--

While I was coding my own portfolio site using React, I needed a way to incorporate my existing pdf version of my resume to my site. With tons of libraries out there, after a bit of research, I was able to include a pdf version of my resume in my React portfolio site using a library called react-pdf. I am going to demonstrate how easy it is to display PDF using the react-pdf library.

So as usual I created a react app using create-react-app and installed the library react-pdf.

npx create-react-app pdf-viewer
cd pdf-viewer
npm i --save react-pdf

react-pdf has a Document component that takes in a file prop and that’s where I passed my actual pdf file. Then inside the Document component, I had to create a page component and that takes in a page number. In my case, my pdf only had one page, so I didn't have to manage the page state but I will show you in the next post how to render PDF with multiple pages.

So, first I added the pdf file to the project directory and the file structure looked like this:

Sample.pdf

I made a component called PdfViewer as well and in that component, I imported Document and Page from react-pdf. PdfViewer component received the sample.pdf from app components as a prop and thus I could pass it to the Document component easily. After the code PdfViewer looked like this:

And the App component looked like this:

Theoretically, this should’ve worked but I’ve got an error that said failed to load the pdf file. Upon looking at the dev console I found out it had to do something with pdf.worker.js and after a lot of googling I figured out that I needed to copy the pdf.worker.js from the node module (node_modules/pdfjs-dist/build/pdf.worker.js) to the public folder of the app and pass that file as workerSrc to the Document component that takes it as options. After adding the pdf.worker.js PdfViewer looked like this:

That successfully rendered the pdf to the browser.

Thank you for reading. I hope my experience helps somebody else. If there are feedbacks or suggestions that please feel free to comment.

--

--

Responses (1)