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
| import react, { useEffect, useState } from 'react'; import './index.css'; import * as myPdfjs from 'pdfjs-dist';
myPdfjs.GlobalWorkerOptions.workerSrc = `//cdn.bootcdn.net/ajax/libs/pdf.js/${myPdfjs.version}/pdf.worker.min.js`; export default function App() { const [pdfUrl, setPdfUrl] = useState('http://****.pdf'); const [canvanId, setCanvanId] = useState("pdf-" + parseInt(Math.random() * 10000));
useEffect(() => { setViewDocument(myPdfjs, pdfUrl, canvanId) },[]);
return ( <> <div id={canvanId}> </div> </> ) }
const setViewDocument = async (myPdfjs, pdfUrl, domId) => { let pdfDocument = await getPdfDocument(myPdfjs, pdfUrl); for(let i = 1; i <= pdfDocument._pdfInfo.numPages; i++){ setPdfDocument(domId, pdfDocument, i) } }
const getPdfDocument = async (myPdfjs, pdfUrl) => { let loadingTask = myPdfjs.getDocument(pdfUrl); const pdfDocument = await loadingTask.promise; await pdfDocument.dataLoaded; return pdfDocument; }
const setPdfDocument = async (domId, pdfDocument, page) => { pdfDocument.getPage(page).then(page => { let scale = 2; let viewport = page.getViewport({ scale: scale }); let mainDom = document.getElementById(domId); mainDom.setAttribute("style", 'width:' + viewport.width + 'px') let canvas = document.createElement("canvas"); let context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; let renderContext = { canvasContext: context, viewport: viewport, }; page.render(renderContext); mainDom.appendChild(canvas) }); }
|