DEV Community

Cover image for πŸ“„ How to Implement a PDF Viewer with Page Navigation in React
Hardik Prajapati
Hardik Prajapati

Posted on β€’ Edited on

1

πŸ“„ How to Implement a PDF Viewer with Page Navigation in React

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
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ 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
Enter fullscreen mode Exit fullscreen mode
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;
Enter fullscreen mode Exit fullscreen mode

πŸ” 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} />
Enter fullscreen mode Exit fullscreen mode

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! πŸ’‘

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️