This guide will help you integrate PDF.js Express Viewer into a React application on the browser. You can also checkout a ready to go sample on GitHub.
Get the React sample source code herePrerequisites
1. Install PDF.js Express Viewer NPM module
Run the following command in your Terminal or Command Line:
npm i @pdftron/pdfjs-express-viewer
2. Copy static assets
Next we must copy the static assets required for WebViewer to run. The files are located in node_modules/@pdftron/pdfjs-express-viewer/public
and must be moved into a location that will be served and publicly accessible. In React, it will be public
folder.
Inside of a GitHub project, we automate the copying of static resources by executing copy-webviewer-files.js.
3. Place WebViewer into a component
- Import WebViewer into your component.
import WebViewer from '@pdftron/pdfjs-express-viewer';
- Create a reference where WebViewer will be placed or mounted.
const MyComponent = () => {
const viewer = useRef(null);
return (
<div className="MyComponent">
<div className="header">React sample</div>
<div className="webviewer" ref={viewer}></div>
</div>
);
};
- Inside of
useEffect
hook orcomponentDidMount
lifecycle method initialize WebViewer. Ensure that the path property in the constructor points to where you copied static assetsnode_modules/@pdftron/pdfjs-express-viewer/public
in Reactpublic
folder.
const MyComponent = () => {
const viewer = useRef(null);
useEffect(() => {
WebViewer(
{
path: '/webviewer/lib',
initialDoc: '/files/pdftron_about.pdf',
},
viewer.current,
).then((instance) => {
// now you can access APIs through the WebViewer instance
const { Core } = instance;
// adding an event listener for when a document is loaded
Core.documentViewer.addEventListener('documentLoaded', () => {
console.log('document loaded');
});
// adding an event listener for when the page number has changed
Core.documentViewer.addEventListener('pageNumberUpdated', (pageNumber) => {
console.log(`Page number is: ${pageNumber}`);
});
});
}, []);
return (
<div className="MyComponent">
<div className="header">React sample</div>
<div className="webviewer" ref={viewer}></div>
</div>
);
};
- Run the app by running
npm start
.
You can now checkout other guides like how to open your own documents or how to disable certain features.