mirror of
https://github.com/mozilla/pdf.js.git
synced 2025-04-26 10:08:06 +02:00
Add Create React App example with TypeScript and basic usage
This commit is contained in:
parent
d20ab76242
commit
00c3339520
15 changed files with 377 additions and 0 deletions
62
examples/create-react-app/src/pdf.tsx
Normal file
62
examples/create-react-app/src/pdf.tsx
Normal file
|
@ -0,0 +1,62 @@
|
|||
import React, { useRef, useEffect } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
import pdfjs from 'pdfjs-dist';
|
||||
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';
|
||||
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
|
||||
|
||||
const PdfComponent = ({ src }) => {
|
||||
const canvasRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPdf = async () => {
|
||||
const loadingTask = pdfjs.getDocument(src);
|
||||
|
||||
const pdf = await loadingTask.promise;
|
||||
|
||||
const firstPageNumber = 1;
|
||||
|
||||
const page = await pdf.getPage(firstPageNumber);
|
||||
|
||||
const scale = 1.5;
|
||||
const viewport = page.getViewport({scale: scale});
|
||||
|
||||
// Prepare canvas using PDF page dimensions
|
||||
const canvas = canvasRef.current;
|
||||
|
||||
const context = canvas.getContext('2d');
|
||||
canvas.height = viewport.height;
|
||||
canvas.width = viewport.width;
|
||||
|
||||
// Render PDF page into canvas context
|
||||
const renderContext = {
|
||||
canvasContext: context,
|
||||
viewport: viewport
|
||||
};
|
||||
const renderTask = page.render(renderContext);
|
||||
|
||||
await renderTask.promise;
|
||||
};
|
||||
|
||||
fetchPdf();
|
||||
}, [src]);
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={window.innerWidth}
|
||||
height={window.innerHeight}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
PdfComponent.propTypes = {
|
||||
src: PropTypes.string
|
||||
};
|
||||
|
||||
PdfComponent.defaultProps = {
|
||||
src: `${process.env.PUBLIC_URL}/helloworld.pdf`
|
||||
};
|
||||
|
||||
export default PdfComponent;
|
Loading…
Add table
Add a link
Reference in a new issue