Business

Pdfjs-dist 4.3.136 viewer react example

PDF.js Dist 4.3.136 Viewer React Example: A Comprehensive Guide

In this guide, we will walk through the process of integrating PDF.js 4.3.136 into a React project. PDF.js is a powerful open-source JavaScript library that renders PDF documents directly in the browser. It can be integrated into React applications to enhance the viewing experience of PDF files.

1. Introduction to PDF.js

PDF.js is a widely used JavaScript library created by Mozilla that allows developers to display PDF files directly in web browsers. It doesn’t rely on external plugins and is a versatile tool for rendering and interacting with PDF documents.

The 4.3.136 version comes with improved functionality, bug fixes, and smoother rendering for modern applications.

<a name=”setting-up”></a>

2. Setting up a React Project

Before we integrate PDF.js, we need a basic React environment. If you don’t already have one, follow these steps to create a new React project:

  1. Install Node.js from Node’s official site.
  2. Create a new React app using Create React App.
bash
npx create-react-app pdf-viewer-app
cd pdf-viewer-app

<a name=”installing-pdfjs”></a>

3. Installing PDF.js 4.3.136

Next, let’s install pdfjs-dist which is the npm package for the PDF.js library. We will also install react-pdf, which simplifies using PDF.js in React.

bash
npm install pdfjs-dist@4.3.136 react-pdf

This installs PDF.js version 4.3.136 and react-pdf for easy integration into the React component.

<a name=”creating-viewer”></a>

4. Creating a PDF Viewer Component

Let’s create a React component that uses PDF.js to render a PDF document. First, we’ll create a new component file PDFViewer.js inside the src folder.

javascript
import React, { useEffect, useRef } from "react";
import { getDocument } from "pdfjs-dist/build/pdf";
import "pdfjs-dist/build/pdf.worker.entry";

const PDFViewer = ({ pdfUrl }) => {
const canvasRef = useRef(null);

useEffect(() => {
const loadingTask = getDocument(pdfUrl);
loadingTask.promise.then(pdf => {
pdf.getPage(1).then(page => {
const scale = 1.5;
const viewport = page.getViewport({ scale });
const canvas = canvasRef.current;
const context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;

const renderContext = {
canvasContext: context,
viewport: viewport,
};
page.render(renderContext);
});
});
}, [pdfUrl]);

return <canvas ref={canvasRef}></canvas>;
};

export default PDFViewer;

In this code:

  • We use the getDocument function from pdfjs-dist to load a PDF file from a given URL.
  • The useEffect hook loads the document once the component mounts and renders the first page of the PDF on a canvas.

<a name=”handling-config”></a>

5. Handling PDF.js Configuration

Before rendering, you need to configure the PDF.js worker. In your main index.js or App.js file, ensure that the worker file path is set correctly.

javascript
import * as pdfjsLib from "pdfjs-dist/build/pdf";

pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.js`;

This tells PDF.js where to find its worker script, ensuring it loads properly and processes PDFs in a separate thread.

<a name=”rendering-pdf”></a>

6. Rendering PDF Documents

Now that we’ve set up the PDFViewer component, let’s render it in our main application. Open App.js and import the component:

javascript
import React from "react";
import PDFViewer from "./PDFViewer";

function App() {
return (
<div className="App">
<h1>PDF.js 4.3.136 Viewer in React</h1>
<PDFViewer pdfUrl="/path-to-your-pdf.pdf" />
</div>

);
}

export default App;

In this example:

  • We provide the PDFViewer component with a URL for the PDF file we want to display.
  • Replace /path-to-your-pdf.pdf with the actual path or URL of your PDF document.

<a name=”customizing-viewer”></a>

7. Customizing the Viewer

You can further customize the viewer by allowing for additional functionality, such as:

  • Zooming: Adjust the scale in the getViewport method to allow for zoom controls.
  • Navigation: Implement buttons for navigating between pages of the PDF by updating the page number dynamically.
javascript
const [pageNumber, setPageNumber] = useState(1);

const handleNextPage = () => setPageNumber((prevPage) => prevPage + 1);
const handlePrevPage = () => setPageNumber((prevPage) => Math.max(prevPage - 1, 1));

useEffect(() => {
pdf.getPage(pageNumber).then(page => {
// render page based on pageNumber
});
}, [pageNumber]);

This allows users to navigate through the PDF document page by page.

<a name=”handling-errors”></a>

8. Handling Errors and Loading States

To improve user experience, handle errors and loading states in your component. Modify the useEffect hook in PDFViewer.js to display a loading message and catch errors:

javascript
useEffect(() => {
const loadingTask = getDocument(pdfUrl);
loadingTask.promise
.then(pdf => {
setIsLoading(false);
return pdf.getPage(pageNumber);
})
.then(page => {
// render page
})
.catch(error => {
console.error("Error loading PDF:", error);
setError(true);
});
}, [pdfUrl, pageNumber]);

if (isLoading) {
return <div>Loading...</div>;
}

if (error) {
return <div>Error loading PDF</div>;
}

With this addition:

  • Loading State: A “Loading…” message is displayed while the PDF is being fetched.
  • Error Handling: Errors are caught and an error message is displayed.

<a name=”conclusion”></a>

9. Conclusion

By following this guide, you now have a fully functional PDF viewer in your React application using PDF.js 4.3.136. With the ability to render PDFs, add zoom functionality, and handle navigation, you can further enhance the viewer to fit your application’s needs.

Explore more customization options, such as text selection, annotations, and saving functionalities, to create an advanced and user-friendly PDF viewer.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button