Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 27 additions & 7 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,54 @@ import React, {useState} from 'react';
import pdfWorkerSource from 'pdfjs-dist/build/pdf.worker.min.mjs';
import * as pdfjs from 'pdfjs-dist';
import ReactFastPDF, {PDFPreviewer} from 'react-fast-pdf';
import type {RotationDegrees} from 'react-fast-pdf';
import './index.css';

pdfjs.GlobalWorkerOptions.workerSrc = URL.createObjectURL(new Blob([pdfWorkerSource], {type: 'text/javascript'}));

function App() {
const [file, setFile] = useState<string | null>(null);
const [rotation, setRotation] = useState<RotationDegrees>(0);

// `.default` is required when referencing the legacy CJS package.
const packageName = ('default' in ReactFastPDF ? (ReactFastPDF.default as {PackageName: string}) : ReactFastPDF).PackageName;

const handleRotate = () => {
setRotation((prev) => ((prev + 90) % 360) as RotationDegrees);
};

return (
<main className="container">
<h1 className="title">Hello, I am {packageName}!</h1>

{file ? (
<>
<button
className="button button_back"
type="button"
onClick={() => setFile(null)}
>
Back
</button>
<div style={{display: 'flex', gap: '10px', marginBottom: '10px', flexWrap: 'wrap'}}>
<button
className="button button_back"
type="button"
onClick={() => {
setFile(null);
setRotation(0);
}}
>
Back
</button>

<button
className="button"
type="button"
onClick={handleRotate}
>
Rotate 90° (Current: {rotation}°)
</button>
</div>

<PDFPreviewer
file={file}
pageMaxWidth={1000}
isSmallScreen={false}
rotation={rotation}
/>
</>
) : (
Expand Down
47 changes: 38 additions & 9 deletions src/PDFPreviewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {Document} from 'react-pdf';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';

import type {PDFDocument, PageViewport} from './types.js';
import type {PDFDocument, PageViewport, RotationDegrees} from './types.js';
import {pdfPreviewerStyles as styles} from './styles.js';
import PDFPasswordForm, {type PDFPasswordFormProps} from './PDFPasswordForm.js';
import PageRenderer from './PageRenderer.js';
Expand All @@ -27,6 +27,7 @@ type Props = {
onLoadError?: () => void;
containerStyle?: CSSProperties;
contentContainerStyle?: CSSProperties;
rotation?: RotationDegrees;
};

type OnPasswordCallback = (password: string | null) => void;
Expand All @@ -48,7 +49,8 @@ function PDFPreviewer({
contentContainerStyle,
shouldShowErrorComponent = true,
onLoadError,
}: Props) {
rotation = 0,
}: Props): JSX.Element {
const [pageViewports, setPageViewports] = useState<PageViewport[]>([]);
const [numPages, setNumPages] = useState(0);
const [containerWidth, setContainerWidth] = useState(0);
Expand Down Expand Up @@ -100,6 +102,7 @@ function PDFPreviewer({
* Calculates a proper page height. The method should be called only when there are page viewports.
* It is based on a ratio between the specific page viewport width and provided page width.
* Also, the app should take into account the page borders.
* When rotation is 90 or 270 degrees, width and height are swapped.
*/
const calculatePageHeight = useCallback(
(pageIndex: number) => {
Expand All @@ -109,12 +112,18 @@ function PDFPreviewer({

const pageWidth = calculatePageWidth();

const {width: pageViewportWidth, height: pageViewportHeight} = pageViewports[pageIndex];
const {width: originalWidth, height: originalHeight} = pageViewports[pageIndex];

// Swap dimensions when rotated 90 or 270 degrees
const isRotated90or270 = rotation === 90 || rotation === 270;
const pageViewportWidth = isRotated90or270 ? originalHeight : originalWidth;
const pageViewportHeight = isRotated90or270 ? originalWidth : originalHeight;

const scale = pageWidth / pageViewportWidth;

return pageViewportHeight * scale + PAGE_BORDER * 2;
},
[pageViewports, calculatePageWidth],
[pageViewports, calculatePageWidth, rotation],
);

const estimatedPageHeight = calculatePageHeight(0);
Expand Down Expand Up @@ -204,7 +213,15 @@ function PDFPreviewer({
if (containerWidth > 0 && containerHeight > 0) {
listRef.current?.resetAfterIndex(0);
}
}, [containerWidth, containerHeight]);
}, [containerWidth, containerHeight, rotation]);

/**
* Scroll back to the top whenever rotation changes so the list offset
* is consistent regardless of how page dimensions change.
*/
useLayoutEffect(() => {
listRef.current?.scrollTo(0);
}, [rotation]);

useLayoutEffect(() => {
if (!containerRef.current) {
Expand All @@ -227,14 +244,20 @@ function PDFPreviewer({
ref={containerRef}
style={{...styles.container, ...containerStyle}}
>
<div style={{...styles.innerContainer, ...(shouldRequestPassword ? styles.invisibleContainer : {})}}>
<div
style={{
...styles.innerContainer,
...(shouldRequestPassword ? styles.invisibleContainer : {}),
}}
>
<Document
file={file}
options={DEFAULT_DOCUMENT_OPTIONS}
externalLinkTarget={DEFAULT_EXTERNAL_LINK_TARGET}
error={shouldShowErrorComponent ? ErrorComponent : null}
onLoadError={onLoadError}
loading={LoadingComponent}
rotate={rotation}
onLoadSuccess={onDocumentLoadSuccess}
onPassword={initiatePasswordChallenge}
>
Expand All @@ -244,11 +267,17 @@ function PDFPreviewer({
style={{...styles.list, ...contentContainerStyle}}
outerRef={setListAttributes}
width={isSmallScreen ? pageWidth : containerWidth}
height={containerHeight}
height={numPages === 1 && estimatedPageHeight < containerHeight ? estimatedPageHeight : containerHeight}
itemCount={numPages}
itemSize={calculatePageHeight}
estimatedItemSize={calculatePageHeight(0)}
itemData={{pageWidth, estimatedPageHeight, calculatePageHeight, getDevicePixelRatio, containerHeight, numPages}}
itemData={{
pageWidth,
estimatedPageHeight,
calculatePageHeight,
getDevicePixelRatio,
numPages,
}}
>
{PageRenderer}
</List>
Expand All @@ -261,6 +290,6 @@ function PDFPreviewer({
);
}

PDFPasswordForm.displayName = 'PDFPreviewer';
PDFPreviewer.displayName = 'PDFPreviewer';

export default memo(PDFPreviewer);
6 changes: 2 additions & 4 deletions src/PageRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,19 @@ type Props = {
calculatePageHeight: (pageIndex: number) => number;
getDevicePixelRatio: (width: number, height: number) => number | undefined;
numPages: number;
containerHeight: number;
};
};

function PageRenderer({index, style, data}: Props) {
const {pageWidth, estimatedPageHeight, calculatePageHeight, getDevicePixelRatio, numPages, containerHeight} = data;
const {pageWidth, estimatedPageHeight, calculatePageHeight, getDevicePixelRatio, numPages} = data;
/**
* Render a specific page based on its index.
* The method includes a wrapper to apply virtualized styles.
*/
const pageHeight = calculatePageHeight(index);
const devicePixelRatio = getDevicePixelRatio(pageWidth, pageHeight);
const parsedHeight = parseFloat(style.height as unknown as string);
const parsedTop = parseFloat(style.top as unknown as string);
const topPadding = numPages > 1 || parsedHeight > containerHeight ? parsedTop + PAGE_BORDER : (containerHeight - parsedHeight) / 2;
const topPadding = numPages === 1 ? parsedTop : parsedTop + PAGE_BORDER;
return (
<div style={{...styles.pageWrapper, ...style, top: `${topPadding}px`}}>
<Page
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import {pdfjs} from 'react-pdf';
import PDFPreviewer from './PDFPreviewer.js';
import type {RotationDegrees} from './types.js';

const PACKAGE_NAME = 'react-fast-pdf';

export {PDFPreviewer, pdfjs};
export type {RotationDegrees};

export default {
PackageName: PACKAGE_NAME,
Expand Down
7 changes: 6 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,9 @@ type ComponentStyles = {
[key: string]: CSSProperties;
};

export type {PDFDocument, PageViewport, ComponentStyles};
/**
* Valid rotation angles for PDF pages (in degrees clockwise)
*/
type RotationDegrees = 0 | 90 | 180 | 270;

export type {PDFDocument, PageViewport, ComponentStyles, RotationDegrees};
Loading