Skip to content
Open
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
@@ -1,31 +1,51 @@
import React, {useState} from 'react';
import ReactFastPDF, {PDFPreviewer} from 'react-fast-pdf';
import type {RotationDegrees} from 'react-fast-pdf';
import './index.css';

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
45 changes: 34 additions & 11 deletions src/PDFPreviewer.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import pdfWorkerSource from 'pdfjs-dist/build/pdf.worker.min.mjs';
import React, {memo, useCallback, useLayoutEffect, useRef, useState} from 'react';
import type {CSSProperties, ReactNode} from 'react';
import times from 'lodash/times.js';
import React, {useCallback, useLayoutEffect, useRef, useState, memo} from 'react';
import type {CSSProperties, ReactNode, JSX} from 'react';
import {times} from 'lodash';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restore the CommonJS-safe lodash import

In the published package we emit ESM (package.json has "type": "module"), so this becomes import { times } from 'lodash'. lodash@4 is the CommonJS build, which means SSR/test environments that execute our dist files directly instead of prebundling them can fail at module load time before PDFPreviewer renders. The previous lodash/times.js default import avoided that interop problem.

Useful? React with 👍 / 👎.

import {VariableSizeList as List} from 'react-window';
import {Document, pdfjs} 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 @@ -28,6 +28,8 @@ type Props = {
onLoadError?: () => void;
containerStyle?: CSSProperties;
contentContainerStyle?: CSSProperties;
/** Rotation angle for all pages (0, 90, 180, 270 degrees) */
rotation?: RotationDegrees;
};

type OnPasswordCallback = (password: string | null) => void;
Expand All @@ -51,7 +53,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 @@ -103,6 +106,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 @@ -112,12 +116,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 @@ -207,7 +217,7 @@ function PDFPreviewer({
if (containerWidth > 0 && containerHeight > 0) {
listRef.current?.resetAfterIndex(0);
}
}, [containerWidth, containerHeight]);
}, [containerWidth, containerHeight, rotation]);

useLayoutEffect(() => {
if (!containerRef.current) {
Expand All @@ -230,14 +240,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 @@ -251,7 +267,14 @@ function PDFPreviewer({
itemCount={numPages}
itemSize={calculatePageHeight}
estimatedItemSize={calculatePageHeight(0)}
itemData={{pageWidth, estimatedPageHeight, calculatePageHeight, getDevicePixelRatio, containerHeight, numPages}}
itemData={{
pageWidth,
estimatedPageHeight,
calculatePageHeight,
getDevicePixelRatio,
containerHeight,
numPages,
}}
>
{PageRenderer}
</List>
Expand All @@ -264,6 +287,6 @@ function PDFPreviewer({
);
}

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

export default memo(PDFPreviewer);
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import PDFPreviewer from './PDFPreviewer.js';
import type {RotationDegrees} from './types.js';

const PACKAGE_NAME = 'react-fast-pdf';

export {PDFPreviewer};
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