|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useState } from 'react'; |
| 4 | +import { pdfjs, Document, Page } from 'react-pdf'; |
| 5 | +import 'react-pdf/dist/esm/Page/AnnotationLayer.css'; |
| 6 | +import 'react-pdf/dist/esm/Page/TextLayer.css'; |
| 7 | + |
| 8 | +import './Sample.css'; |
| 9 | + |
| 10 | +import type { PDFDocumentProxy } from 'pdfjs-dist'; |
| 11 | + |
| 12 | +pdfjs.GlobalWorkerOptions.workerSrc = new URL( |
| 13 | + 'pdfjs-dist/build/pdf.worker.min.js', |
| 14 | + import.meta.url, |
| 15 | +).toString(); |
| 16 | + |
| 17 | +const options = { |
| 18 | + cMapUrl: '/cmaps/', |
| 19 | + standardFontDataUrl: '/standard_fonts/', |
| 20 | +}; |
| 21 | + |
| 22 | +type PDFFile = string | File | null; |
| 23 | + |
| 24 | +export default function Sample() { |
| 25 | + const [file, setFile] = useState<PDFFile>('./sample.pdf'); |
| 26 | + const [numPages, setNumPages] = useState<number>(); |
| 27 | + |
| 28 | + function onFileChange(event: React.ChangeEvent<HTMLInputElement>): void { |
| 29 | + const { files } = event.target; |
| 30 | + |
| 31 | + if (files && files[0]) { |
| 32 | + setFile(files[0] || null); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + function onDocumentLoadSuccess({ numPages: nextNumPages }: PDFDocumentProxy): void { |
| 37 | + setNumPages(nextNumPages); |
| 38 | + } |
| 39 | + |
| 40 | + return ( |
| 41 | + <div className="Example"> |
| 42 | + <header> |
| 43 | + <h1>react-pdf sample page</h1> |
| 44 | + </header> |
| 45 | + <div className="Example__container"> |
| 46 | + <div className="Example__container__load"> |
| 47 | + <label htmlFor="file">Load from file:</label>{' '} |
| 48 | + <input onChange={onFileChange} type="file" /> |
| 49 | + </div> |
| 50 | + <div className="Example__container__document"> |
| 51 | + <Document file={file} onLoadSuccess={onDocumentLoadSuccess} options={options}> |
| 52 | + {Array.from(new Array(numPages), (el, index) => ( |
| 53 | + <Page key={`page_${index + 1}`} pageNumber={index + 1} /> |
| 54 | + ))} |
| 55 | + </Document> |
| 56 | + </div> |
| 57 | + </div> |
| 58 | + </div> |
| 59 | + ); |
| 60 | +} |
0 commit comments