Add a PDF to your React App in 3 Easy Steps
This step by step guide walks through adding a PDF to an application.
While creating my website, I wanted to display my resume, which is in PDF format. Although I was able to embed it, I didn’t like its display and looked for a different option. I chose to use React-PDF. Please be aware that your PDF will display as an image.
- Install React-PDF
Install React-PDF by entering the following in your terminal:
$ npm install react-pdfOR$ yarn add react-pdf
2. Import files
Once installed, import React-PDF and your files into your component as follows:
- In the last line, PDF.js worker is enabled to render the PDF files without affecting page performance.
- On line 2, Resume.pdf is imported from the utils folder. There is also an option to use an URL instead of importing a file.
3. Render to the page
Now that everything is set up, render the PDF file by including the following:
- If using an URL, replace the file with the URL:
- As mentioned before, the PDF will display as an image, but I needed the links on my resume to be functional. To work around this issue, I rendered it within a href that links to my functional resume.
- Styling took a bit of time. React-PDF creates multiple divs when rendering, which made finding which element I wanted to style hard. Using developer tools I found .react-pdf__Page__canvas was the div of the PDF.
- There is also an option to display multiple pages, which can be found in the documentation here.
React-PDF is an easy way to display PDFs in your React application. There are some limitations as the file displays as images, but it provides more flexibility when it comes to styling. If the PDF file consists of multiple pages, React-PDF also offers a way to display them. I would like to see a download or zoom option. Unfortunately, I couldn’t find them in the documentation. I may eventually change how I display my PDF, but for now, this is a great option.
If this article helped, you have any suggestions, or used another method to display your PDF, please let me know.