Display a PDF in Next.js Using React PDF Viewer
This blog talks about how you can display a PDF file in your Next.js app.
Prerequisites1. Create a Next.js project with the following commandnpx create-next-app@latestFollow the instructions and a new Next.js project will be created.
2. Run the Next.js projectType the following command on the terminal.
npm run devOpen a web browser like Chrome, and go to http://localhost:3000. You will see your new Next.js project running.

Now, we will use the React PDF viewer component to display the PDF file on the page.
You can refer this documentation to get started: Getting started — React PDF Viewer (react-pdf-viewer.dev)
Steps to use React PDF Viewer:1. Install a few packagesnpm install pdfjs-dist@3.4.120npm install @react-pdf-viewer/core@3.12.02. Copy the original code
Go to Basic usage — React PDF Viewer (react-pdf-viewer.dev) and paste the code on page.js inside the project.
import { Viewer, Worker } from "@react-pdf-viewer/core";export default function Home() {
return (
);
}3. Run the project
Most likely, you will encounter an error.

This is a pretty common error in Next.js about the usage of client components.
Basically, it just says that React PDF Viewer component uses some code that can only work on client components and not the server components.
4. Fix the server errorWhat you have to do is just type “use client” on top of your page.
Now, the overall code becomes this

Now you will encounter another error.

This error comes when there is a mismatch in the versions of the worker and the pdfjs-dist package.
To fix this, just change the version of pdfjs-dist inside the workerUrl to 3.4.120.
If you run now, you will see the PDF being displayed on the page.

But hold on! There’s something weird.
Look at the right side of the page, there’s a black background which looks odd.
6. Copy stylesTo make the styling correct, copy and paste the styles from this page: starter/nextjs at main · react-pdf-viewer/starter (github.com)
// Import the styles provided by the react-pdf-viewer packagesimport "@react-pdf-viewer/default-layout/lib/styles/index.css";
import "@react-pdf-viewer/core/lib/styles/index.css";
Now, you will encounter another error:
Module not found: Error: Can't resolve '@react-pdf-viewer/default-layout/lib/styles/index.css'To resolve this, install this package:
npm install @react-pdf-viewer/default-layoutNow, final dependencies are

Upon running the project now, the PDF will be displayed on the full page.

import { Viewer, Worker } from "@react-pdf-viewer/core";
import "@react-pdf-viewer/default-layout/lib/styles/index.css";
import "@react-pdf-viewer/core/lib/styles/index.css";
export default function Home() {
return (
);
}Conclusion
In this blog post, we saw how you can display a PDF previewer on a page in Nextjs application.
The post Display a PDF in Next.js Using React PDF Viewer appeared first on Suman Sourabh.