0
# Event Handling
1
2
Comprehensive event system for PDF loading, page navigation, user interactions, and error handling with detailed callback information. This covers all events and callbacks available in the PDF component.
3
4
## Capabilities
5
6
### Loading Events
7
8
Handle PDF loading progress and completion events.
9
10
```typescript { .api }
11
/**
12
* PDF loading event handlers
13
* Monitor PDF download and loading progress
14
*/
15
interface LoadingEvents {
16
/**
17
* Called during PDF download/loading progress
18
* @param percent - Loading progress from 0 to 1
19
*/
20
onLoadProgress?: (percent: number) => void;
21
22
/**
23
* Called when PDF loading is complete
24
* @param numberOfPages - Total number of pages in the PDF
25
* @param path - Local file path where PDF is stored
26
* @param size - PDF dimensions in points
27
* @param tableContents - PDF table of contents (optional)
28
*/
29
onLoadComplete?: (
30
numberOfPages: number,
31
path: string,
32
size: { height: number; width: number },
33
tableContents?: TableContent[]
34
) => void;
35
}
36
37
type TableContent = {
38
/** Nested table of contents items */
39
children: TableContent[];
40
/** Native pointer reference */
41
mNativePtr: number;
42
/** Page index for this item */
43
pageIdx: number;
44
/** Display title for this item */
45
title: string;
46
};
47
```
48
49
**Usage Examples:**
50
51
```typescript
52
53
source={{ uri: "https://example.com/large-document.pdf" }}
54
onLoadProgress={(progress) => {
55
console.log(`Loading: ${Math.round(progress * 100)}%`);
56
// Update progress bar, loading indicator, etc.
57
}}
58
onLoadComplete={(numberOfPages, filePath, { width, height }, tableContents) => {
59
console.log(`Loaded ${numberOfPages} pages`);
60
console.log(`PDF size: ${width}x${height} points`);
61
console.log(`Cached at: ${filePath}`);
62
63
if (tableContents) {
64
console.log("Table of contents available:");
65
tableContents.forEach(item => {
66
console.log(`- ${item.title} (page ${item.pageIdx + 1})`);
67
});
68
}
69
}}
70
style={{ flex: 1 }}
71
/>
72
```
73
74
### Navigation Events
75
76
Handle page navigation and current page changes.
77
78
```typescript { .api }
79
/**
80
* Page navigation event handlers
81
* Monitor user navigation through PDF pages
82
*/
83
interface NavigationEvents {
84
/**
85
* Called when the current page changes
86
* @param page - Current page number (1-based)
87
* @param numberOfPages - Total number of pages
88
*/
89
onPageChanged?: (page: number, numberOfPages: number) => void;
90
}
91
```
92
93
**Usage Example:**
94
95
```typescript
96
const [currentPage, setCurrentPage] = useState(1);
97
const [totalPages, setTotalPages] = useState(0);
98
99
100
source={{ uri: "document.pdf" }}
101
onPageChanged={(page, total) => {
102
setCurrentPage(page);
103
setTotalPages(total);
104
console.log(`Page ${page} of ${total}`);
105
}}
106
style={{ flex: 1 }}
107
/>
108
109
// Display page indicator
110
<Text>{`${currentPage} / ${totalPages}`}</Text>
111
```
112
113
### User Interaction Events
114
115
Handle user touch interactions and gestures.
116
117
```typescript { .api }
118
/**
119
* User interaction event handlers
120
* Respond to touch gestures and user interactions
121
*/
122
interface InteractionEvents {
123
/**
124
* Called when user single-taps on a page
125
* @param page - Page number that was tapped (1-based)
126
* @param x - X coordinate of tap relative to page
127
* @param y - Y coordinate of tap relative to page
128
*/
129
onPageSingleTap?: (page: number, x: number, y: number) => void;
130
131
/**
132
* Called when zoom scale changes
133
* @param scale - New scale factor
134
*/
135
onScaleChanged?: (scale: number) => void;
136
137
/**
138
* Called when user taps on a link within the PDF
139
* @param url - URL or link destination
140
*/
141
onPressLink?: (url: string) => void;
142
}
143
```
144
145
**Usage Examples:**
146
147
```typescript
148
149
source={{ uri: "interactive-document.pdf" }}
150
onPageSingleTap={(page, x, y) => {
151
console.log(`Tapped page ${page} at coordinates (${x}, ${y})`);
152
// Show context menu, add annotation, etc.
153
}}
154
onScaleChanged={(scale) => {
155
console.log(`Zoom level: ${Math.round(scale * 100)}%`);
156
// Update zoom controls, save preference, etc.
157
}}
158
onPressLink={(url) => {
159
console.log(`Link pressed: ${url}`);
160
// Handle external links
161
if (url.startsWith('http')) {
162
Linking.openURL(url);
163
}
164
}}
165
style={{ flex: 1 }}
166
/>
167
```
168
169
### Error Handling
170
171
Handle errors during PDF loading and rendering.
172
173
```typescript { .api }
174
/**
175
* Error handling
176
* Handle various error conditions during PDF operations
177
*/
178
interface ErrorEvents {
179
/**
180
* Called when an error occurs during PDF loading or rendering
181
* @param error - Error object with details about the failure
182
*/
183
onError?: (error: Error) => void;
184
}
185
```
186
187
**Usage Examples:**
188
189
```typescript
190
191
source={{ uri: "https://example.com/document.pdf" }}
192
onError={(error) => {
193
console.error("PDF Error:", error);
194
195
// Handle different error types
196
if (error.message?.includes("404")) {
197
Alert.alert("Error", "PDF document not found");
198
} else if (error.message?.includes("password")) {
199
Alert.alert("Error", "PDF requires a password");
200
} else if (error.message?.includes("network")) {
201
Alert.alert("Error", "Network error loading PDF");
202
} else {
203
Alert.alert("Error", "Failed to load PDF");
204
}
205
}}
206
style={{ flex: 1 }}
207
/>
208
```
209
210
### Complete Event Handler Example
211
212
Comprehensive example showing all event handlers working together.
213
214
```typescript { .api }
215
/**
216
* Complete event handling setup
217
* Example showing all available event handlers
218
*/
219
interface CompleteEvents extends LoadingEvents, NavigationEvents, InteractionEvents, ErrorEvents {}
220
```
221
222
**Complete Usage Example:**
223
224
```typescript
225
import React, { useState } from "react";
226
import { View, Text, Alert, ActivityIndicator } from "react-native";
227
import Pdf from "react-native-pdf";
228
229
export default function CompletePdfViewer() {
230
const [loading, setLoading] = useState(true);
231
const [progress, setProgress] = useState(0);
232
const [currentPage, setCurrentPage] = useState(1);
233
const [totalPages, setTotalPages] = useState(0);
234
const [scale, setScale] = useState(1);
235
236
return (
237
<View style={{ flex: 1 }}>
238
{/* Status bar */}
239
<View style={{ flexDirection: "row", justifyContent: "space-between", padding: 10 }}>
240
<Text>Page: {currentPage}/{totalPages}</Text>
241
<Text>Zoom: {Math.round(scale * 100)}%</Text>
242
</View>
243
244
245
source={{
246
uri: "https://example.com/document.pdf",
247
cache: true
248
}}
249
// Loading events
250
onLoadProgress={(percent) => {
251
setProgress(percent);
252
console.log(`Loading progress: ${Math.round(percent * 100)}%`);
253
}}
254
onLoadComplete={(numberOfPages, filePath, { width, height }, tableContents) => {
255
setLoading(false);
256
setTotalPages(numberOfPages);
257
console.log(`PDF loaded: ${numberOfPages} pages, ${width}x${height}px`);
258
259
if (tableContents?.length) {
260
console.log("Table of contents:", tableContents);
261
}
262
}}
263
// Navigation events
264
onPageChanged={(page, total) => {
265
setCurrentPage(page);
266
console.log(`Navigated to page ${page} of ${total}`);
267
}}
268
// Interaction events
269
onPageSingleTap={(page, x, y) => {
270
console.log(`Single tap on page ${page} at (${x}, ${y})`);
271
// Could show/hide controls, add annotations, etc.
272
}}
273
onScaleChanged={(newScale) => {
274
setScale(newScale);
275
console.log(`Scale changed to ${newScale}`);
276
}}
277
onPressLink={(url) => {
278
console.log(`Link pressed: ${url}`);
279
Alert.alert("Link", `Open ${url}?`);
280
}}
281
// Error handling
282
onError={(error) => {
283
setLoading(false);
284
console.error("PDF Error:", error);
285
Alert.alert("Error", "Failed to load PDF document");
286
}}
287
style={{ flex: 1 }}
288
/>
289
290
{/* Loading overlay */}
291
{loading && (
292
<View style={{
293
position: "absolute",
294
top: 0,
295
left: 0,
296
right: 0,
297
bottom: 0,
298
justifyContent: "center",
299
alignItems: "center",
300
backgroundColor: "rgba(255,255,255,0.8)"
301
}}>
302
<ActivityIndicator size="large" />
303
<Text>{Math.round(progress * 100)}% loaded</Text>
304
</View>
305
)}
306
</View>
307
);
308
}
309
```
310
311
### Event Timing and Lifecycle
312
313
Understanding when events are triggered during PDF lifecycle.
314
315
```typescript { .api }
316
/**
317
* Event lifecycle and timing
318
* Order and timing of events during PDF operations
319
*/
320
interface EventLifecycle {
321
// 1. Loading starts - component mounts
322
// 2. onLoadProgress - called repeatedly during download
323
// 3. onLoadComplete - called when PDF is ready
324
// 4. onPageChanged - called for initial page and navigation
325
// 5. onPageSingleTap - called on user interaction
326
// 6. onScaleChanged - called on zoom changes
327
// 7. onPressLink - called when links are tapped
328
// 8. onError - called if any errors occur
329
}
330
```