Working with PDFs in a React app? Want to add a jump to the page feature? π In this blog, Iβll show you how to use @react-pdf-viewer to display a PDF and navigate to a specific page using a page number! π
π¦ Packages Required
Before we start, install the required packages:
npm install @react-pdf-viewer/core @react-pdf-viewer/page-navigation pdfjs-dist
π οΈ Setting Up the Component
Hereβs the complete PDFViewer component that:
β Loads a PDF file from a given URL π
β Allows jumping to a specific page using page number π
β
Uses
@react-pdf-viewer/page-navigation plugin for navigation
import React, { useEffect, useRef } from "react";
import { Viewer, Worker } from "@react-pdf-viewer/core";
import { pageNavigationPlugin } from "@react-pdf-viewer/page-navigation";
import * as pdfjs from "pdfjs-dist";
import "pdfjs-dist/build/pdf.worker.entry";
import "@react-pdf-viewer/core/lib/styles/index.css";
// Fix: Set workerSrc manually
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
"pdfjs-dist/build/pdf.worker.min.js",
import.meta.url
).toString();
const PDFViewer = ({ docUrl, pageNumber }) => {
const pageNavPluginInstance = pageNavigationPlugin();
const { jumpToPage } = pageNavPluginInstance;
useEffect(() => {
if (pageNumber > 0) {
jumpToPage(pageNumber - 1);
}
}, [pageNumber, jumpToPage]);
if (!docUrl) {
return (
<div
className="mr-4"
style={{
width: "40%",
border: "2px solid gray",
borderRadius: "10px",
overflow: "hidden",
}}
>
<h5
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%",
color: "gray",
}}
>
No document URL provided.
</h5>
</div>
);
}
return (
<div
className="ml-4"
style={{
width: "40%",
border: "2px solid gray",
borderRadius: "10px",
overflow: "hidden",
}}
>
<Worker workerUrl={pdfjs.GlobalWorkerOptions.workerSrc}>
<Viewer fileUrl={docUrl} plugins={[pageNavPluginInstance]} />
</Worker>
</div>
);
};
export default PDFViewer;
π How It Works?
1οΈβ£ docUrl: Pass the PDF file URL to display the document.
2οΈβ£ pageNumber: Set this to the page you want to jump to.
3οΈβ£ pageNavigationPlugin: Helps us navigate to a page.
4οΈβ£ useEffect Hook: When pageNumber updates, the viewer jumps to that page automatically.
π― Usage Example
Hereβs how you can use this component in your app:
<PDFViewer docUrl="https://example.com/sample.pdf" pageNumber={5} />
This will open the PDF and jump to page 5 automatically! πβ¨
π Conclusion
With @react-pdf-viewer, integrating a PDF viewer in React is super easy! π οΈ This method allows users to jump to a specific page dynamically, improving the user experience. Try it out and enhance your PDF handling in React apps! π‘
Top comments (0)