0
# Document Management
1
2
Document loading and management functionality for handling PDF files from various sources with comprehensive loading states, error handling, and password protection.
3
4
## Capabilities
5
6
### Document Component
7
8
Main container component that loads and manages PDF documents, providing context and lifecycle management for all child components.
9
10
```typescript { .api }
11
/**
12
* Loads a document passed using `file` prop and provides context to child components
13
* @param props - Document configuration and event handlers
14
* @returns React element containing PDF document context
15
*/
16
function Document(props: DocumentProps): React.ReactElement;
17
18
interface DocumentProps {
19
/** PDF file source - can be URL, ArrayBuffer, Blob, File object, or parameter object */
20
file?: File;
21
/** Function called when document loads successfully */
22
onLoadSuccess?: (document: PDFDocumentProxy) => void;
23
/** Function called when document fails to load */
24
onLoadError?: (error: Error) => void;
25
/** Function called during loading progress */
26
onLoadProgress?: (args: { loaded: number; total: number }) => void;
27
/** Function called when password-protected PDF requires authentication */
28
onPassword?: (callback: (password: string | null) => void, reason: PasswordResponse) => void;
29
/** Function called when document source is retrieved successfully */
30
onSourceSuccess?: () => void;
31
/** Function called when document source fails to be retrieved */
32
onSourceError?: (error: Error) => void;
33
/** Function called when outline or thumbnail items are clicked */
34
onItemClick?: (args: OnItemClickArgs) => void;
35
/** Child components or render function */
36
children?: React.ReactNode | ((props: DocumentRenderProps) => React.ReactNode);
37
/** Class names for styling */
38
className?: ClassName;
39
/** Custom error message or component */
40
error?: NodeOrRenderer;
41
/** Custom loading message or component */
42
loading?: NodeOrRenderer;
43
/** Custom no-data message or component */
44
noData?: NodeOrRenderer;
45
/** PDF.js configuration options */
46
options?: Options;
47
/** Document scale factor */
48
scale?: number;
49
/** Document rotation in degrees */
50
rotate?: number | null;
51
/** Rendering mode for all pages */
52
renderMode?: RenderMode;
53
/** External link target for annotations */
54
externalLinkTarget?: ExternalLinkTarget;
55
/** External link rel attribute for annotations */
56
externalLinkRel?: ExternalLinkRel;
57
/** Path prefix for annotation SVG images */
58
imageResourcesPath?: ImageResourcesPath;
59
/** React ref for the main document div */
60
inputRef?: React.Ref<HTMLDivElement | null>;
61
}
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import { Document, Page } from "react-pdf";
68
69
// Basic document loading from URL
70
function BasicPDFViewer() {
71
return (
72
<Document file="https://example.com/sample.pdf">
73
<Page pageNumber={1} />
74
</Document>
75
);
76
}
77
78
// Document with all lifecycle handlers
79
function AdvancedPDFViewer() {
80
const [loading, setLoading] = useState(true);
81
const [error, setError] = useState(null);
82
const [pdf, setPdf] = useState(null);
83
84
return (
85
<Document
86
file="https://example.com/sample.pdf"
87
onLoadSuccess={(pdf) => {
88
setPdf(pdf);
89
setLoading(false);
90
console.log('Loaded PDF with', pdf.numPages, 'pages');
91
}}
92
onLoadError={(error) => {
93
setError(error);
94
setLoading(false);
95
}}
96
onLoadProgress={({ loaded, total }) => {
97
console.log('Loading progress:', (loaded / total) * 100, '%');
98
}}
99
onPassword={(callback, reason) => {
100
const password = prompt('Enter PDF password:');
101
callback(password);
102
}}
103
options={{
104
cMapUrl: '/cmaps/',
105
wasmUrl: '/wasm/',
106
httpHeaders: {
107
'Authorization': 'Bearer token'
108
}
109
}}
110
>
111
{pdf && <Page pageNumber={1} />}
112
</Document>
113
);
114
}
115
```
116
117
### File Input Types
118
119
Different ways to provide PDF files to the Document component.
120
121
```typescript { .api }
122
type File = string | ArrayBuffer | Blob | Source | null;
123
124
interface Source {
125
/** Binary PDF data */
126
data?: BinaryData;
127
/** PDF file URL */
128
url?: string;
129
/** PDF.js data range transport */
130
range?: PDFDataRangeTransport;
131
}
132
133
type BinaryData = TypedArray | ArrayBuffer | number[] | string;
134
```
135
136
**Usage Examples:**
137
138
```typescript
139
// URL string
140
<Document file="https://example.com/sample.pdf" />
141
142
// Local file from input
143
function FileUploader() {
144
const [file, setFile] = useState(null);
145
146
return (
147
<div>
148
<input
149
type="file"
150
accept=".pdf"
151
onChange={(e) => setFile(e.target.files[0])}
152
/>
153
{file && <Document file={file}><Page pageNumber={1} /></Document>}
154
</div>
155
);
156
}
157
158
// ArrayBuffer data
159
const pdfData = new ArrayBuffer(/* PDF data */);
160
<Document file={pdfData} />
161
162
// Parameter object with options
163
<Document
164
file={{
165
url: 'https://example.com/sample.pdf',
166
httpHeaders: { 'Authorization': 'Bearer token' }
167
}}
168
/>
169
```
170
171
### Password Handling
172
173
Support for password-protected PDF documents with customizable authentication flow.
174
175
```typescript { .api }
176
type OnPassword = (callback: OnPasswordCallback, reason: PasswordResponse) => void;
177
type OnPasswordCallback = (password: string | null) => void;
178
179
interface PasswordResponses {
180
readonly NEED_PASSWORD: 1;
181
readonly INCORRECT_PASSWORD: 2;
182
}
183
184
type PasswordResponse = 1 | 2;
185
```
186
187
**Usage Examples:**
188
189
```typescript
190
function PasswordProtectedPDF() {
191
const [password, setPassword] = useState('');
192
const [showPasswordInput, setShowPasswordInput] = useState(false);
193
194
const handlePassword = (callback, reason) => {
195
if (reason === PasswordResponses.NEED_PASSWORD) {
196
setShowPasswordInput(true);
197
// Use state or modal for password input
198
callback(password);
199
} else if (reason === PasswordResponses.INCORRECT_PASSWORD) {
200
alert('Incorrect password, please try again');
201
callback(null); // Try again or cancel
202
}
203
};
204
205
return (
206
<Document
207
file="https://example.com/protected.pdf"
208
onPassword={handlePassword}
209
>
210
<Page pageNumber={1} />
211
</Document>
212
);
213
}
214
```
215
216
### PDF.js Configuration
217
218
Advanced PDF.js options for customizing document loading and rendering behavior.
219
220
```typescript { .api }
221
interface Options extends Omit<DocumentInitParameters, 'url' | 'data' | 'range'> {
222
/** Character map URL for non-Latin characters */
223
cMapUrl?: string;
224
/** Custom HTTP headers for document requests */
225
httpHeaders?: Record<string, string>;
226
/** WebAssembly URL for PDF.js WASM builds */
227
wasmUrl?: string;
228
/** Include credentials in cross-origin requests */
229
withCredentials?: boolean;
230
/** Maximum allowed image size in pixels */
231
maxImageSize?: number;
232
/** Disable font face loading */
233
disableFontFace?: boolean;
234
/** Disable range requests for streaming */
235
disableRange?: boolean;
236
/** Disable streaming of PDF data */
237
disableStream?: boolean;
238
/** Stop parsing when first error encountered */
239
stopAtErrors?: boolean;
240
}
241
```
242
243
**Usage Examples:**
244
245
```typescript
246
const pdfOptions = {
247
cMapUrl: '/node_modules/pdfjs-dist/cmaps/',
248
wasmUrl: '/node_modules/pdfjs-dist/build/',
249
httpHeaders: {
250
'Authorization': 'Bearer ' + authToken,
251
'X-Custom-Header': 'value'
252
},
253
withCredentials: true,
254
maxImageSize: 1024 * 1024,
255
disableFontFace: false,
256
stopAtErrors: false
257
};
258
259
<Document
260
file="https://api.example.com/document.pdf"
261
options={pdfOptions}
262
/>
263
```
264
265
### Event Handlers
266
267
Comprehensive event system for handling document lifecycle and user interactions.
268
269
```typescript { .api }
270
type OnDocumentLoadSuccess = (document: PDFDocumentProxy) => void;
271
type OnDocumentLoadError = (error: Error) => void;
272
type OnDocumentLoadProgress = (args: { loaded: number; total: number }) => void;
273
type OnSourceSuccess = () => void;
274
type OnSourceError = (error: Error) => void;
275
276
interface OnItemClickArgs {
277
/** Destination reference for internal links */
278
dest?: Dest;
279
/** Zero-based page index */
280
pageIndex: number;
281
/** One-based page number */
282
pageNumber: number;
283
}
284
285
type Dest = Promise<ResolvedDest> | ResolvedDest | string | null;
286
type ResolvedDest = (RefProxy | number)[];
287
```
288
289
### Document Context
290
291
Document context data available to child components through React context.
292
293
```typescript { .api }
294
interface DocumentRenderProps {
295
/** Loaded PDF document proxy */
296
pdf: PDFDocumentProxy;
297
/** Link service for navigation */
298
linkService: LinkService;
299
/** Function to register page elements for navigation */
300
registerPage: (pageIndex: number, ref: HTMLDivElement) => void;
301
/** Function to unregister page elements */
302
unregisterPage: (pageIndex: number) => void;
303
/** Image resources path for annotations */
304
imageResourcesPath?: string;
305
/** Item click handler */
306
onItemClick?: (args: OnItemClickArgs) => void;
307
/** Rendering mode */
308
renderMode?: RenderMode;
309
/** Document scale */
310
scale?: number;
311
/** Document rotation */
312
rotate?: number | null;
313
}
314
```