A react native PDF view component for displaying PDF documents from various sources with caching support.
—
Programmatic control methods for navigation and component manipulation. This covers all methods available for controlling the PDF component programmatically.
Programmatically navigate to specific pages within the PDF document.
/**
* Navigate to a specific page in the PDF
* @param pageNumber - Target page number (1-based)
* @throws Error if pageNumber is not a valid number
*/
setPage(pageNumber: number): void;Usage Examples:
import React, { useRef } from "react";
import { View, Button } from "react-native";
import Pdf from "react-native-pdf";
export default function PdfWithNavigation() {
const pdfRef = useRef<Pdf>(null);
const goToPage = (page: number) => {
try {
pdfRef.current?.setPage(page);
} catch (error) {
console.error("Navigation error:", error);
Alert.alert("Error", "Invalid page number");
}
};
return (
<View style={{ flex: 1 }}>
{/* Navigation controls */}
<View style={{ flexDirection: "row", justifyContent: "space-around", padding: 10 }}>
<Button title="Go to Page 1" onPress={() => goToPage(1)} />
<Button title="Go to Page 5" onPress={() => goToPage(5)} />
<Button title="Go to Page 10" onPress={() => goToPage(10)} />
</View>
<Pdf
ref={pdfRef}
source={{ uri: "document.pdf" }}
onLoadComplete={(numberOfPages) => {
console.log(`PDF loaded with ${numberOfPages} pages`);
}}
style={{ flex: 1 }}
/>
</View>
);
}Direct manipulation of native component properties for advanced use cases.
/**
* Set native properties directly on the underlying native component
* @param nativeProps - Object containing native properties to set
*/
setNativeProps(nativeProps: object): void;Usage Examples:
import React, { useRef, useEffect } from "react";
import Pdf from "react-native-pdf";
export default function AdvancedPdfControl() {
const pdfRef = useRef<Pdf>(null);
const updateNativeProps = () => {
// Direct native property manipulation
pdfRef.current?.setNativeProps({
page: 3,
scale: 1.5,
// Other native properties as needed
});
};
return (
<Pdf
ref={pdfRef}
source={{ uri: "document.pdf" }}
onLoadComplete={() => {
// Set initial properties after loading
setTimeout(() => {
updateNativeProps();
}, 1000);
}}
style={{ flex: 1 }}
/>
);
}Proper component reference handling for programmatic control.
/**
* PDF component reference interface
* Access to component methods through ref
*/
interface PdfRef {
/** Navigate to specific page */
setPage: (pageNumber: number) => void;
/** Set native properties */
setNativeProps: (nativeProps: object) => void;
}Usage Examples:
import React, { useRef, useImperativeHandle, forwardRef } from "react";
import Pdf from "react-native-pdf";
// Custom PDF wrapper with enhanced control
const ControlledPdf = forwardRef<PdfRef, PdfProps>((props, ref) => {
const pdfRef = useRef<Pdf>(null);
useImperativeHandle(ref, () => ({
setPage: (pageNumber: number) => {
pdfRef.current?.setPage(pageNumber);
},
setNativeProps: (nativeProps: object) => {
pdfRef.current?.setNativeProps(nativeProps);
},
// Add custom methods
goToFirstPage: () => {
pdfRef.current?.setPage(1);
},
goToLastPage: (totalPages: number) => {
pdfRef.current?.setPage(totalPages);
}
}));
return <Pdf ref={pdfRef} {...props} />;
});
// Usage
export default function App() {
const pdfRef = useRef<PdfRef>(null);
return (
<ControlledPdf
ref={pdfRef}
source={{ uri: "document.pdf" }}
onPress={() => pdfRef.current?.goToFirstPage()}
style={{ flex: 1 }}
/>
);
}Helper functions and patterns for common navigation scenarios.
/**
* Navigation utility functions
* Common patterns for PDF navigation control
*/
interface NavigationUtils {
/** Navigate to next page */
nextPage: (currentPage: number, totalPages: number) => void;
/** Navigate to previous page */
previousPage: (currentPage: number) => void;
/** Navigate to first page */
goToFirst: () => void;
/** Navigate to last page */
goToLast: (totalPages: number) => void;
/** Navigate by relative offset */
navigateBy: (offset: number, currentPage: number, totalPages: number) => void;
}Complete Navigation Example:
import React, { useState, useRef } from "react";
import { View, TouchableOpacity, Text, Alert } from "react-native";
import Pdf from "react-native-pdf";
export default function FullNavigationPdf() {
const pdfRef = useRef<Pdf>(null);
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const navigateToPage = (pageNumber: number) => {
if (pageNumber < 1 || pageNumber > totalPages) {
Alert.alert("Error", `Page must be between 1 and ${totalPages}`);
return;
}
try {
pdfRef.current?.setPage(pageNumber);
} catch (error) {
console.error("Navigation error:", error);
Alert.alert("Error", "Failed to navigate to page");
}
};
const nextPage = () => {
if (currentPage < totalPages) {
navigateToPage(currentPage + 1);
}
};
const previousPage = () => {
if (currentPage > 1) {
navigateToPage(currentPage - 1);
}
};
const goToFirst = () => navigateToPage(1);
const goToLast = () => navigateToPage(totalPages);
return (
<View style={{ flex: 1 }}>
{/* Navigation controls */}
<View style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
padding: 10,
backgroundColor: "#f0f0f0"
}}>
<TouchableOpacity
onPress={goToFirst}
disabled={currentPage === 1}
style={{ padding: 8, opacity: currentPage === 1 ? 0.5 : 1 }}
>
<Text>First</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={previousPage}
disabled={currentPage === 1}
style={{ padding: 8, opacity: currentPage === 1 ? 0.5 : 1 }}
>
<Text>Previous</Text>
</TouchableOpacity>
<Text>{currentPage} / {totalPages}</Text>
<TouchableOpacity
onPress={nextPage}
disabled={currentPage === totalPages}
style={{ padding: 8, opacity: currentPage === totalPages ? 0.5 : 1 }}
>
<Text>Next</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={goToLast}
disabled={currentPage === totalPages}
style={{ padding: 8, opacity: currentPage === totalPages ? 0.5 : 1 }}
>
<Text>Last</Text>
</TouchableOpacity>
</View>
<Pdf
ref={pdfRef}
source={{ uri: "document.pdf" }}
onLoadComplete={(numberOfPages) => {
setTotalPages(numberOfPages);
console.log(`PDF loaded with ${numberOfPages} pages`);
}}
onPageChanged={(page, total) => {
setCurrentPage(page);
}}
style={{ flex: 1 }}
/>
</View>
);
}Proper error handling when using programmatic navigation methods.
/**
* Error handling patterns for navigation
* Safe navigation with proper error handling
*/
interface NavigationErrorHandling {
/** Validate page number before navigation */
validatePageNumber: (page: number, totalPages: number) => boolean;
/** Safe navigation with error handling */
safeNavigate: (pdfRef: React.RefObject<Pdf>, page: number) => Promise<boolean>;
}Error Handling Example:
const safeNavigate = async (pdfRef: React.RefObject<Pdf>, pageNumber: number, totalPages: number) => {
// Validate inputs
if (!pdfRef.current) {
console.error("PDF component reference not available");
return false;
}
if (typeof pageNumber !== 'number' || isNaN(pageNumber)) {
console.error("Invalid page number:", pageNumber);
return false;
}
if (pageNumber < 1 || pageNumber > totalPages) {
console.error(`Page ${pageNumber} out of range (1-${totalPages})`);
return false;
}
try {
pdfRef.current.setPage(pageNumber);
return true;
} catch (error) {
console.error("Navigation failed:", error);
return false;
}
};
// Usage
const handleNavigation = async (page: number) => {
const success = await safeNavigate(pdfRef, page, totalPages);
if (!success) {
Alert.alert("Navigation Error", "Could not navigate to the requested page");
}
};Install with Tessl CLI
npx tessl i tessl/npm-react-native-pdf