-
-
Notifications
You must be signed in to change notification settings - Fork 924
/
Copy pathSample.tsx
83 lines (66 loc) · 2.33 KB
/
Sample.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use client';
import { useCallback, useState } from 'react';
import { useResizeObserver } from '@wojtekmaj/react-hooks';
import { pdfjs, Document, Page } from 'react-pdf';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import './Sample.css';
import type { PDFDocumentProxy } from 'pdfjs-dist';
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
const options = {
cMapUrl: '/cmaps/',
standardFontDataUrl: '/standard_fonts/',
};
const resizeObserverOptions = {};
const maxWidth = 800;
type PDFFile = string | File | null;
export default function Sample() {
const [file, setFile] = useState<PDFFile>('./sample.pdf');
const [numPages, setNumPages] = useState<number>();
const [containerRef, setContainerRef] = useState<HTMLElement | null>(null);
const [containerWidth, setContainerWidth] = useState<number>();
const onResize = useCallback<ResizeObserverCallback>((entries) => {
const [entry] = entries;
if (entry) {
setContainerWidth(entry.contentRect.width);
}
}, []);
useResizeObserver(containerRef, resizeObserverOptions, onResize);
function onFileChange(event: React.ChangeEvent<HTMLInputElement>): void {
const { files } = event.target;
const nextFile = files?.[0];
if (nextFile) {
setFile(nextFile);
}
}
function onDocumentLoadSuccess({ numPages: nextNumPages }: PDFDocumentProxy): void {
setNumPages(nextNumPages);
}
return (
<div className="Example">
<header>
<h1>react-pdf sample page</h1>
</header>
<div className="Example__container">
<div className="Example__container__load">
<label htmlFor="file">Load from file:</label>{' '}
<input onChange={onFileChange} type="file" />
</div>
<div className="Example__container__document" ref={setContainerRef}>
<Document file={file} onLoadSuccess={onDocumentLoadSuccess} options={options}>
{Array.from(new Array(numPages), (_el, index) => (
<Page
key={`page_${index + 1}`}
pageNumber={index + 1}
width={containerWidth ? Math.min(containerWidth, maxWidth) : maxWidth}
/>
))}
</Document>
</div>
</div>
</div>
);
}