Simple React component to wrap up PDF.js. The easiest way to render PDFs in your React app.
npm install @mikecousins/react-pdfreact-pdf-js provides a component for rendering PDF documents using PDF.js.
---



https://react-pdf.cousins.ai/
Install with pnpm add @mikecousins/react-pdf pdfjs-dist, yarn add @mikecousins/react-pdf pdfjs-dist or npm install @mikecousins/react-pdf pdfjs-dist
usePdf hookUse the hook in your app (showing some basic pagination as well):
``js
import React, { useState, useRef } from 'react';
import { usePdf } from '@mikecousins/react-pdf';
const MyPdfViewer = () => {
const [page, setPage] = useState(1);
const canvasRef = useRef(null);
const { pdfDocument, pdfPage } = usePdf({
file: 'test.pdf',
page,
canvasRef,
});
return (
Props
When you call usePdf you'll want to pass in a subset of these props, like this:
>
const { pdfDocument, pdfPage } = usePdf({ canvasRef, file: 'https://example.com/test.pdf', page });$3
A reference to the canvas element. Create with:
>
const canvasRef = useRef(null);and then render it like:
>
and then pass it into usePdf.
$3
URL of the PDF file.
$3
Allows you to specify a callback that is called when the PDF document data will be fully loaded.
Callback is called with PDFDocumentProxy
as an only argument.
$3
Allows you to specify a callback that is called after an error occurred during PDF document data loading.
$3
Allows you to specify a callback that is called when the PDF page data will be fully loaded.
Callback is called with PDFPageProxy
as an only argument.
$3
Allows you to specify a callback that is called after an error occurred during PDF page data loading.
$3
Allows you to specify a callback that is called when the PDF page will be fully rendered into the DOM.
Callback is called with PDFPageProxy
as an only argument.
$3
Allows you to specify a callback that is called after an error occurred during PDF page rendering.
$3
Specify the page that you want to display. Default = 1,
$3
Allows you to scale the PDF. Default = 1.
$3
Allows you to rotate the PDF. Number is in degrees. Default = 0.
$3
Allows you to specify a cmap url. Default = '../node_modules/pdfjs-dist/cmaps/'.
$3
Allows you to specify whether the cmaps are packed or not. Default = false.
$3
Allows you to specify a custom pdf worker url. Default = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/\${pdfjs.version}/pdf.worker.js'.
$3
Allows you to add the withCredentials flag. Default = false.
Returned values
$3
pdfjs's PDFDocumentProxy object.
This can be undefined if document has not been loaded yet.$3
pdfjs's PDFPageProxy` objectMIT © mikecousins