Published in · 3 min read · Jun 5, 2020
--
I want to show you an easy and simple way to display PDF
files using React in the browser. I will be using a library called react-pdf. This library is capable of rendering PDF
files given an URL or a local file inside the project or base64 encoded version.
To get started, create a simple React
application using Create React App. To do this you can run the following commands:
npx create-react-app display-pdf-app
cd display-pdf-app
npm start
After this, add the react-pdf
library to the project using the following command:
npm install --save react-pdf
To render the PDF
file, react-pdf
has a Document component where you need to pass a file prop. Then inside the Document component, you need to create a Page component. Simple isn’t it? Sample code:
import React from 'react';
import { Document, Page } from 'react-pdf';import samplePDF from './test.pdf';
export default function Test() {
return (
<Document file={samplePDF}>
<Page pageNumber={1} />
</Document>
);
}
The final project structure will look like this:
Let’s start with creating single-page.js
and all-pages.js
inside the components
-pdf
folder with the following contents:
single-page.js
Now navigate to App.js
and replace the content with the following code: