Display PDFs in your React app as easily as if they were images.
—
Document loading and management functionality for handling PDF files from various sources with comprehensive loading states, error handling, and password protection.
Main container component that loads and manages PDF documents, providing context and lifecycle management for all child components.
/**
* Loads a document passed using `file` prop and provides context to child components
* @param props - Document configuration and event handlers
* @returns React element containing PDF document context
*/
function Document(props: DocumentProps): React.ReactElement;
interface DocumentProps {
/** PDF file source - can be URL, ArrayBuffer, Blob, File object, or parameter object */
file?: File;
/** Function called when document loads successfully */
onLoadSuccess?: (document: PDFDocumentProxy) => void;
/** Function called when document fails to load */
onLoadError?: (error: Error) => void;
/** Function called during loading progress */
onLoadProgress?: (args: { loaded: number; total: number }) => void;
/** Function called when password-protected PDF requires authentication */
onPassword?: (callback: (password: string | null) => void, reason: PasswordResponse) => void;
/** Function called when document source is retrieved successfully */
onSourceSuccess?: () => void;
/** Function called when document source fails to be retrieved */
onSourceError?: (error: Error) => void;
/** Function called when outline or thumbnail items are clicked */
onItemClick?: (args: OnItemClickArgs) => void;
/** Child components or render function */
children?: React.ReactNode | ((props: DocumentRenderProps) => React.ReactNode);
/** Class names for styling */
className?: ClassName;
/** Custom error message or component */
error?: NodeOrRenderer;
/** Custom loading message or component */
loading?: NodeOrRenderer;
/** Custom no-data message or component */
noData?: NodeOrRenderer;
/** PDF.js configuration options */
options?: Options;
/** Document scale factor */
scale?: number;
/** Document rotation in degrees */
rotate?: number | null;
/** Rendering mode for all pages */
renderMode?: RenderMode;
/** External link target for annotations */
externalLinkTarget?: ExternalLinkTarget;
/** External link rel attribute for annotations */
externalLinkRel?: ExternalLinkRel;
/** Path prefix for annotation SVG images */
imageResourcesPath?: ImageResourcesPath;
/** React ref for the main document div */
inputRef?: React.Ref<HTMLDivElement | null>;
}Usage Examples:
import { Document, Page } from "react-pdf";
// Basic document loading from URL
function BasicPDFViewer() {
return (
<Document file="https://example.com/sample.pdf">
<Page pageNumber={1} />
</Document>
);
}
// Document with all lifecycle handlers
function AdvancedPDFViewer() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [pdf, setPdf] = useState(null);
return (
<Document
file="https://example.com/sample.pdf"
onLoadSuccess={(pdf) => {
setPdf(pdf);
setLoading(false);
console.log('Loaded PDF with', pdf.numPages, 'pages');
}}
onLoadError={(error) => {
setError(error);
setLoading(false);
}}
onLoadProgress={({ loaded, total }) => {
console.log('Loading progress:', (loaded / total) * 100, '%');
}}
onPassword={(callback, reason) => {
const password = prompt('Enter PDF password:');
callback(password);
}}
options={{
cMapUrl: '/cmaps/',
wasmUrl: '/wasm/',
httpHeaders: {
'Authorization': 'Bearer token'
}
}}
>
{pdf && <Page pageNumber={1} />}
</Document>
);
}Different ways to provide PDF files to the Document component.
type File = string | ArrayBuffer | Blob | Source | null;
interface Source {
/** Binary PDF data */
data?: BinaryData;
/** PDF file URL */
url?: string;
/** PDF.js data range transport */
range?: PDFDataRangeTransport;
}
type BinaryData = TypedArray | ArrayBuffer | number[] | string;Usage Examples:
// URL string
<Document file="https://example.com/sample.pdf" />
// Local file from input
function FileUploader() {
const [file, setFile] = useState(null);
return (
<div>
<input
type="file"
accept=".pdf"
onChange={(e) => setFile(e.target.files[0])}
/>
{file && <Document file={file}><Page pageNumber={1} /></Document>}
</div>
);
}
// ArrayBuffer data
const pdfData = new ArrayBuffer(/* PDF data */);
<Document file={pdfData} />
// Parameter object with options
<Document
file={{
url: 'https://example.com/sample.pdf',
httpHeaders: { 'Authorization': 'Bearer token' }
}}
/>Support for password-protected PDF documents with customizable authentication flow.
type OnPassword = (callback: OnPasswordCallback, reason: PasswordResponse) => void;
type OnPasswordCallback = (password: string | null) => void;
interface PasswordResponses {
readonly NEED_PASSWORD: 1;
readonly INCORRECT_PASSWORD: 2;
}
type PasswordResponse = 1 | 2;Usage Examples:
function PasswordProtectedPDF() {
const [password, setPassword] = useState('');
const [showPasswordInput, setShowPasswordInput] = useState(false);
const handlePassword = (callback, reason) => {
if (reason === PasswordResponses.NEED_PASSWORD) {
setShowPasswordInput(true);
// Use state or modal for password input
callback(password);
} else if (reason === PasswordResponses.INCORRECT_PASSWORD) {
alert('Incorrect password, please try again');
callback(null); // Try again or cancel
}
};
return (
<Document
file="https://example.com/protected.pdf"
onPassword={handlePassword}
>
<Page pageNumber={1} />
</Document>
);
}Advanced PDF.js options for customizing document loading and rendering behavior.
interface Options extends Omit<DocumentInitParameters, 'url' | 'data' | 'range'> {
/** Character map URL for non-Latin characters */
cMapUrl?: string;
/** Custom HTTP headers for document requests */
httpHeaders?: Record<string, string>;
/** WebAssembly URL for PDF.js WASM builds */
wasmUrl?: string;
/** Include credentials in cross-origin requests */
withCredentials?: boolean;
/** Maximum allowed image size in pixels */
maxImageSize?: number;
/** Disable font face loading */
disableFontFace?: boolean;
/** Disable range requests for streaming */
disableRange?: boolean;
/** Disable streaming of PDF data */
disableStream?: boolean;
/** Stop parsing when first error encountered */
stopAtErrors?: boolean;
}Usage Examples:
const pdfOptions = {
cMapUrl: '/node_modules/pdfjs-dist/cmaps/',
wasmUrl: '/node_modules/pdfjs-dist/build/',
httpHeaders: {
'Authorization': 'Bearer ' + authToken,
'X-Custom-Header': 'value'
},
withCredentials: true,
maxImageSize: 1024 * 1024,
disableFontFace: false,
stopAtErrors: false
};
<Document
file="https://api.example.com/document.pdf"
options={pdfOptions}
/>Comprehensive event system for handling document lifecycle and user interactions.
type OnDocumentLoadSuccess = (document: PDFDocumentProxy) => void;
type OnDocumentLoadError = (error: Error) => void;
type OnDocumentLoadProgress = (args: { loaded: number; total: number }) => void;
type OnSourceSuccess = () => void;
type OnSourceError = (error: Error) => void;
interface OnItemClickArgs {
/** Destination reference for internal links */
dest?: Dest;
/** Zero-based page index */
pageIndex: number;
/** One-based page number */
pageNumber: number;
}
type Dest = Promise<ResolvedDest> | ResolvedDest | string | null;
type ResolvedDest = (RefProxy | number)[];Document context data available to child components through React context.
interface DocumentRenderProps {
/** Loaded PDF document proxy */
pdf: PDFDocumentProxy;
/** Link service for navigation */
linkService: LinkService;
/** Function to register page elements for navigation */
registerPage: (pageIndex: number, ref: HTMLDivElement) => void;
/** Function to unregister page elements */
unregisterPage: (pageIndex: number) => void;
/** Image resources path for annotations */
imageResourcesPath?: string;
/** Item click handler */
onItemClick?: (args: OnItemClickArgs) => void;
/** Rendering mode */
renderMode?: RenderMode;
/** Document scale */
scale?: number;
/** Document rotation */
rotate?: number | null;
}Install with Tessl CLI
npx tessl i tessl/npm-react-pdf