Insert a PDF in your project in minutes!
Have you ever wanted a quick and easy way to render a PDF in React? Look no further than react-pdf. It provides a fast and simple method to beautifully display any pdf just like an image.
First, install react-pdf. Below are examples of how to do so with npm, yarn, and bun. Please note Bun is not officially supported by react-pdf, but many users report it works well.
npm
npm install @react-pdf/renderer --save
Yarn
yarn add @react-pdf/renderer
Bun
bun add @react-pdf/renderer
Next, make sure you have your necessary imports. I will also be using a Box component from MUI as I find it gives good control over how my components look. The following code is at the top of my Resume.js file from the resume page on my personal website.
import React from 'react';
import { pdfjs, Document, Page } from 'react-pdf';
import { Box } from "@mui/material";
Now, you can insert your PDF! Make sure the PDF that you wish to display is in your /public
folder. Then, render it in the file you are working with in /src
. The code framework is as follows, where you can change the filename and desired size:
<Document file={{ url: process.env.PUBLIC_URL + '/file.pdf' }}>
<Page size="A4" />
</Document>
This is how I have worked it into my code for my personal website.
<Box>
<div style={{ maxWidth: '800px', margin: '0 auto', maxHeight: '1025px', overflow: 'hidden', marginBottom: '20px' }}>
<Document file={{ url: process.env.PUBLIC_URL + '/resume.pdf' }}>
<Page pageNumber={1} width={800} />
</Document>
</div>
</Box>
For more information on react-pdf's components and their props, visit their documentation page here.
🎵 🎵 🎵
Thank you for reading! What project are you working on that needs a PDF insertion? Did react-pdf work well for you? Have a better method? Let me know down below!
Top comments (0)