This guide will help you integrate a free trial of PDF.js Express 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 NPM module
Run the following command in your Terminal or Command Line:
npm i @pdftron/pdfjs-express
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/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';
- 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/public
in Reactpublic
folder.
const MyComponent = () => {
const viewer = useRef(null);
useEffect(() => {
WebViewer(
{
path: '/webviewer/lib',
initialDoc: '/files/pdftron_about.pdf',
},
viewer.current,
).then((instance) => {
});
}, []);
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.