1import { useRef, useEffect } from 'react';
2import WebViewer, { type WebViewerInstance } from '@pdftron/webviewer';
3import './App.css';
4
5const App = () => {
6 const viewer = useRef<HTMLDivElement | null>(null);
7
8 useEffect(() => {
9 const viewerElement = viewer.current;
10 if (!viewerElement) return;
11
12 let isUnmounted = false;
13 let webViewerInstance: WebViewerInstance | null = null;
14 let onDocumentLoaded: (() => void) | null = null;
15
16 WebViewer(
17 {
18 path: '/lib/webviewer',
19 initialDoc: 'https://apryse.s3.amazonaws.com/public/files/samples/WebviewerDemoDoc.pdf',
20 licenseKey: import.meta.env.VITE_DEMO_KEY, // sign up to get a free trial key at https://dev.apryse.com
21 },
22 viewerElement,
23 ).then((instance: WebViewerInstance) => {
24 if (isUnmounted) {
25 instance.UI.dispose();
26 return;
27 }
28
29 webViewerInstance = instance;
30
31 // Access WebViewer instance here
32 const { documentViewer, annotationManager, Annotations } = instance.Core;
33
34 // Example: Add a rectangle annotation to the first page when the document is loaded
35 onDocumentLoaded = () => {
36 const rectangleAnnot = new Annotations.RectangleAnnotation({
37 PageNumber: 1,
38 // values are in page coordinates with (0, 0) in the top left
39 X: 100,
40 Y: 150,
41 Width: 200,
42 Height: 50,
43 Author: annotationManager.getCurrentUser()
44 });
45
46 annotationManager.addAnnotation(rectangleAnnot);
47 // Need to draw the annotation otherwise it won't show up until the page is refreshed
48 annotationManager.redrawAnnotation(rectangleAnnot);
49 };
50
51 documentViewer.addEventListener('documentLoaded', onDocumentLoaded);
52 });
53
54 return () => {
55 isUnmounted = true;
56
57 if (webViewerInstance) {
58 if (onDocumentLoaded) {
59 webViewerInstance.Core.documentViewer.removeEventListener('documentLoaded', onDocumentLoaded);
60 }
61
62 webViewerInstance.UI.dispose();
63 }
64 };
65 }, []);
66
67 return (
68 <div className="App">
69 <div className="header">React sample</div>
70 <div className="webviewer" ref={viewer}></div>
71 </div>
72 );
73};
74
75export default App;
76