Created
December 10, 2024 13:27
-
-
Save Sparkenstein/7ff162b1c54d6c8c5cb7f0d5e57edddb to your computer and use it in GitHub Desktop.
react pdf autosize with react window
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { | |
useEffect, | |
useId, | |
useMemo, | |
useState, | |
CSSProperties, | |
} from "react"; | |
import AutoSizer from "react-virtualized-auto-sizer"; | |
import { asyncMap } from "@wojtekmaj/async-array-utils"; | |
import { VariableSizeList as List } from "react-window"; | |
import { PDFDocumentProxy, PageViewport } from "pdfjs-dist"; | |
import { Document, Page } from "react-pdf"; | |
function FileCard({ url }) { | |
const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null); | |
const [pageViewports, setPageViewports] = useState<PageViewport[] | null>( | |
null | |
); | |
function getPageHeight(pageIndex: number) { | |
if (!pageViewports) { | |
throw new Error("getPageHeight() called too early"); | |
} | |
const pageViewport = pageViewports[pageIndex]; | |
const scale = 600 / pageViewport.width; | |
const actualHeight = pageViewport.height * scale; | |
return actualHeight; | |
} | |
function onDocumentLoadSuccess(nextPdf: PDFDocumentProxy) { | |
setPdf(nextPdf); | |
} | |
return ( | |
<div> | |
<AutoSizer style={{ height: "100%", width: "100%" }}> | |
{({ height, width }) => { | |
return ( | |
<Document file={url} onLoadSuccess={onDocumentLoadSuccess}> | |
{pdf && pageViewports && ( | |
<List | |
style={{ overflowX: "hidden" }} | |
width={width} | |
height={height} | |
estimatedItemSize={800} | |
itemCount={pdf.numPages} | |
itemSize={getPageHeight} | |
itemData={{ height: 800, width: 600 }} | |
> | |
{Row} | |
</List> | |
)} | |
</Document> | |
); | |
}} | |
</AutoSizer> | |
</div> | |
); | |
} | |
function Row({ | |
index, | |
style, | |
data, | |
}: { | |
index: number; | |
style: CSSProperties; | |
data: { | |
height: number; | |
width: number; | |
}; | |
}) { | |
return ( | |
<div style={style}> | |
<Page | |
width={data.width} | |
height={data.height} | |
pageIndex={index} | |
renderAnnotationLayer={false} | |
renderTextLayer={false} | |
/> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment