### Install Dependencies for iOS Example
Source: https://github.com/wonday/react-native-pdf/blob/master/README.md
Run these commands in the project folder to ensure all dependencies are available before running the iOS example.
```bash
yarn install (or npm install)
cd ios
pod install
cd ..
react-native run-ios
```
--------------------------------
### Install react-native-pdf and react-native-blob-util
Source: https://github.com/wonday/react-native-pdf/blob/master/README.md
Use npm or yarn to install the necessary packages. Ensure both react-native-pdf and react-native-blob-util are installed.
```bash
# Using npm
npm install react-native-pdf react-native-blob-util --save
# or using yarn:
yarn add react-native-pdf react-native-blob-util
```
--------------------------------
### Example: Network Request with Authentication Headers
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
Configure a network request for a PDF with custom authentication and user-agent headers.
```javascript
{
uri: 'https://api.example.com/pdf',
cache: true,
method: 'GET',
headers: {
'Authorization': 'Bearer eyJhbGc...',
'User-Agent': 'MyApp/1.0',
'X-Custom-Header': 'value'
}
}
```
--------------------------------
### iOS Installation for React Native 0.60+
Source: https://github.com/wonday/react-native-pdf/blob/master/README.md
For React Native 0.60 and above, simply run 'pod install' in the ios directory. Linking is handled automatically.
```bash
pod install
```
--------------------------------
### Scalable Content Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PinchZoomView.md
Demonstrates how to use PinchZoomView to make content scalable with pinch gestures. It tracks and displays the current scale.
```javascript
import React from 'react';
import { View, Text } from 'react-native';
import PinchZoomView from 'react-native-pdf/PinchZoomView';
export function ScalableContent() {
const [scale, setScale] = React.useState(1);
return (
{
setScale(scale => scale * pinchScale);
}}
style={{ flex: 1 }}
>
Pinch me! Scale: {scale.toFixed(2)}x
);
}
```
--------------------------------
### Basic PDF Viewer Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/README.md
A simple example of how to render a PDF from a URI using the Pdf component with basic styling.
```javascript
```
--------------------------------
### Example: 24-hour Cache Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
Configure caching for a PDF with a custom filename and a 24-hour expiration time.
```javascript
{
uri: 'https://example.com/document.pdf',
cache: true,
cacheFileName: 'my-document-v1',
expiration: 86400 // 24 hours in seconds
}
```
--------------------------------
### Start Metro Bundler
Source: https://github.com/wonday/react-native-pdf/blob/master/FabricExample/README.md
Run this command from the root of your React Native project to start the Metro dev server. This is essential for the development workflow.
```sh
# Using npm
npm start
# OR using Yarn
yarn start
```
--------------------------------
### Install react-native-pdf with yarn
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/INDEX.md
Install the react-native-pdf library and its peer dependency react-native-blob-util using yarn. Ensure you have yarn installed.
```bash
yarn add react-native-pdf react-native-blob-util
```
--------------------------------
### Set Initial Page
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
Specify the starting page for the PDF viewer using the `page` prop.
```javascript
// Start at page 5
```
--------------------------------
### Install CocoaPods Dependencies for iOS
Source: https://github.com/wonday/react-native-pdf/blob/master/FabricExample/README.md
Before building the iOS app, install the necessary CocoaPods dependencies. Run 'bundle install' once to install the bundler, and 'bundle exec pod install' subsequently or after updating native dependencies.
```sh
bundle install
```
```sh
bundle exec pod install
```
--------------------------------
### UWP Bundled Asset Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
For Windows (UWP) applications, use the `ms-appx:///` scheme to reference PDF files bundled with the app.
```javascript
{
uri: "ms-appx:///assets/file.pdf"
}
```
--------------------------------
### Install react-native-pdf with npm
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/INDEX.md
Install the react-native-pdf library and its peer dependency react-native-blob-util using npm. Ensure you have npm installed.
```bash
npm install react-native-pdf react-native-blob-util
```
--------------------------------
### onScaleChanged Callback Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PinchZoomView.md
Example of how to implement the onScaleChanged callback to log pinch gesture details like scale, pageX, and pageY to the console.
```javascript
onScaleChanged={({scale, pageX, pageY}) => {
console.log(`Pinch scale: ${scale.toFixed(2)}x at (${pageX}, ${pageY})`);
}}
```
--------------------------------
### Static Require() Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Use the `require()` function to reference a local PDF file. This method is primarily supported on iOS.
```javascript
source={require('./assets/file.pdf')}
```
--------------------------------
### Bundled App Assets Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Reference a PDF file that is bundled with your application's assets. This is supported on iOS and Android.
```javascript
{
uri: "bundle-assets://pdfs/document.pdf"
}
```
--------------------------------
### Example Usage of scrollToXY
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PdfViewFlatList.md
Demonstrates how to use the scrollToXY method with a ref to the PdfViewFlatList component to scroll to a specific position.
```javascript
const flatListRef = useRef(null);
// Scroll to position (200, 300)
flatListRef.current.scrollToXY(200, 300);
```
--------------------------------
### Full-Featured PDF Viewer Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/README.md
An example showcasing advanced configuration options for the Pdf component, including zoom, paging, and various event handlers.
```javascript
console.log(`${p*100}%`)}
onLoadComplete={(pages, path) => console.log(`${pages} pages`)}
onPageChanged={(page, total) => console.log(`Page ${page}/${total}`)}
onError={(err) => console.error(err)}
onPageSingleTap={(page, x, y) => console.log(`Tapped page ${page}`)}
onScaleChanged={(scale) => console.log(`Zoom: ${scale}x`)}
onPressLink={(url) => Linking.openURL(url)}
/>
```
--------------------------------
### Basic PdfPageView Usage
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PdfPageView.md
Example demonstrating how to use the PdfPageView component to render a single PDF page. Ensure you have the fileNo from PdfManager.loadFile().
```javascript
import React from 'react';
import PdfPageView from 'react-native-pdf/PdfPageView';
export function SinglePageViewer({fileNo}) {
return (
);
}
```
--------------------------------
### Absolute File System Path Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Specify an absolute path to a PDF file on the device's file system. Ensure the path is correctly formatted with the `file:///` prefix.
```javascript
{
uri: "file:///sdcard/Documents/file.pdf"
}
```
--------------------------------
### High-Zoom UI Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
This setup allows for higher zoom levels and enables double-tap to zoom, suitable for detailed document viewing.
```javascript
```
--------------------------------
### Remote PDF URI Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Use this format to specify a PDF located at a remote URL via HTTP or HTTPS.
```javascript
{
uri: "https://example.com/file.pdf"
}
```
--------------------------------
### Windows Installation for RNW 0.62
Source: https://github.com/wonday/react-native-pdf/blob/master/README.md
Specific instructions for integrating react-native-pdf and react-native-blob-util into a Windows project using Visual Studio 2019, particularly for RNW 0.62.
```csharp
- Open your solution in Visual Studio 2019 (eg. `windows\yourapp.sln`)
- Right-click Solution icon in Solution Explorer > Add > Existing Project...
- If running RNW 0.62: add `node_modules\react-native-pdf\windows\RCTPdf\RCTPdf.vcxproj`
- If running RNW 0.62: add `node_modules\react-native-blob-util\windows\ReactNativeBlobUtil\ReactNativeBlobUtil.vcxproj`
- Right-click main application project > Add > Reference...
- Select `progress-view` and in Solution Projects
- If running 0.62, also select `RCTPdf` and `ReactNativeBlobUtil`
- In app `pch.h` add `#include "winrt/RCTPdf.h"
- If running 0.62, also select `#include "winrt/ReactNativeBlobUtil.h"`
- In `App.cpp` add `PackageProviders().Append(winrt::progress_view::ReactPackageProvider());` before `InitializeComponent();`
- If running RNW 0.62, also add `PackageProviders().Append(winrt::RCTPdf::ReactPackageProvider());` and `PackageProviders().Append(winrt::ReactNativeBlobUtil::ReactPackageProvider());`
```
--------------------------------
### Base64 Encoded PDF Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Provide a PDF directly as a Base64 encoded string. The `data:` URI scheme must be used with the correct MIME type.
```javascript
{
uri: "data:application/pdf;base64,JVBERi0xLjc..."
}
```
--------------------------------
### Usage Example for iOS PdfViewer
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PdfView.md
Demonstrates how to use the PdfView component to display a PDF file on iOS. It includes handling load completion, page changes, and errors, along with setting display properties like fitPolicy and spacing.
```javascript
import React from 'react';
import { View } from 'react-native';
import PdfView from 'react-native-pdf/PdfView';
export function IosPdfViewer() {
const [pages, setPages] = React.useState(0);
return (
{
setPages(numberOfPages);
console.log(`Loaded: ${size.width}x${size.height}pt`);
}}
onPageChanged={(page, total) => {
console.log(`Page ${page}/${total}`);
}}
onError={(error) => {
console.error('PDF Error:', error);
}}
fitPolicy={2}
spacing={10}
/>
);
}
```
--------------------------------
### iOS Installation for React Native 0.59 and below
Source: https://github.com/wonday/react-native-pdf/blob/master/README.md
For older versions of React Native (0.59 and below), you need to manually link the packages using 'react-native link'.
```bash
react-native link react-native-blob-util
react-native link react-native-pdf
```
--------------------------------
### Load PDF File and Get Metadata
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PdfManager.md
Use this method to load a PDF file from a given path and retrieve its metadata. It requires an absolute file path and optionally accepts a password for encrypted PDFs. The returned promise resolves with the internal file number, total number of pages, and the width and height of the first page in PDF points.
```javascript
import PdfManager from 'react-native-pdf/PdfManager';
async function loadPdf() {
try {
const [fileNo, pages, width, height] = await PdfManager.loadFile(
'/storage/emulated/0/Download/document.pdf',
'password123'
);
console.log(`Loaded PDF: ${pages} pages, ${width}x${height} points`);
console.log(`Internal ID: ${fileNo}`);
} catch (error) {
console.error('Failed to load PDF:', error);
}
}
```
--------------------------------
### PinchZoomView _handleStartShouldSetPanResponder
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PinchZoomView.md
This method determines whether the component should become the responder when a touch starts. It returns false to ignore single-touch events, ensuring only multi-touch gestures trigger zoom.
```typescript
_handleStartShouldSetPanResponder(e: GestureResponderEvent, gestureState: PanResponderGestureState): boolean
Returns false to not intercept single-touch events.
```
--------------------------------
### Example Usage of Type Guards
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/types.md
Demonstrates how to use the type guard functions within an event handler to conditionally access properties based on the event type. This ensures type safety.
```typescript
onTextSelectionChange={(event) => {
if (isSelectionChanged(event)) {
const text = event.nativeEvent.text; // TypeScript knows text exists
}
}}
```
--------------------------------
### PDF Viewer with Page Navigation in React Native
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/INDEX.md
Implement PDF page navigation using `useRef` to control the PDF component. This example includes 'Previous' and 'Next' buttons with state management for the current and total page numbers.
```javascript
import React, { useRef } from 'react';
import { Button, View, Text } from 'react-native';
import Pdf from 'react-native-pdf';
export function PdfWithNavigation() {
const pdfRef = useRef(null);
const [currentPage, setCurrentPage] = React.useState(1);
const [totalPages, setTotalPages] = React.useState(0);
return (
setTotalPages(numberOfPages)}
onPageChanged={(page) => setCurrentPage(page)}
style={{ flex: 1 }}
/>
);
}
```
--------------------------------
### Build and Run iOS App
Source: https://github.com/wonday/react-native-pdf/blob/master/FabricExample/README.md
After setting up CocoaPods, use this command to build and run the iOS application. Ensure Metro is running in a separate terminal.
```sh
# Using npm
npm run ios
# OR using Yarn
yarn ios
```
--------------------------------
### Pdf Constructor
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Initializes the Pdf component with source-specific configuration.
```javascript
constructor(props: PdfProps)
```
--------------------------------
### Import and Use Pdf Component
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/modules.md
Import the Pdf component and use it by providing a source URI for the PDF file and styling. This is the most common way to integrate the PDF viewer.
```javascript
import Pdf from 'react-native-pdf';
```
--------------------------------
### Not Recommended Import (Internal Implementation)
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/modules.md
Avoid importing these components as they are internal implementation details and may change without notice. Use only if you understand the risks.
```javascript
// These are implementation details - do not use in application code
import PdfView from 'react-native-pdf/PdfView';
import PdfPageView from 'react-native-pdf/PdfPageView';
import PinchZoomView from 'react-native-pdf/PinchZoomView';
import DoubleTapView from 'react-native-pdf/DoubleTapView';
import PdfViewFlatList from 'react-native-pdf/PdfViewFlatList';
```
--------------------------------
### Content URI Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
For iOS, you can use a Content URI to access PDFs managed by other applications. This requires a specific React Native patch.
```javascript
{
uri: "content://com.example.blobs/xxxxxxxx"
}
```
--------------------------------
### PdfManager.loadFile
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/modules.md
The PdfManager provides a static method to load PDF files and retrieve metadata. This is useful for pre-loading or getting information about a PDF before rendering it.
```APIDOC
## PdfManager.loadFile
### Description
Loads a PDF file and returns its metadata, including file ID, page count, and dimensions. This method is accessible via the `PdfManager` native module bridge.
### Method
`static loadFile(path: string, password?: string): Promise<[number, number, number, number]>`
### Parameters
- **path** (string) - Required - The path to the PDF file.
- **password** (string) - Optional - The password for encrypted PDF files.
### Returns
A Promise that resolves to an array containing:
- file ID (number)
- page count (number)
- dimensions (width: number, height: number)
```
--------------------------------
### Get PDF Element Ref
Source: https://github.com/wonday/react-native-pdf/blob/master/README.md
Obtain a reference to the PDF component to interact with its methods. This ref is essential for calling methods like setPage.
```javascript
return (
{ this.pdf = pdf; }}
source={source}
...
/>
);
```
--------------------------------
### Build and Run Android App
Source: https://github.com/wonday/react-native-pdf/blob/master/FabricExample/README.md
Execute this command in a new terminal window from your project's root directory to build and launch the Android application. Ensure Metro is running.
```sh
# Using npm
npm run android
# OR using Yarn
yarn android
```
--------------------------------
### Peer Dependencies for react-native-pdf
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/modules.md
This JSON snippet outlines the required peer dependencies for react-native-pdf. Ensure 'react-native-blob-util' is installed with a version greater than or equal to 0.13.7.
```json
{
"react": "*",
"react-native": "*",
"react-native-blob-util": ">=0.13.7"
}
```
--------------------------------
### Recommended Import (Public API)
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/modules.md
Use this pattern for importing the main Pdf component from the public API. It includes type definitions for enhanced development.
```javascript
// Main component
import Pdf from 'react-native-pdf';
// With types
import Pdf, {
type PdfProps,
type PdfRef,
type Source
} from 'react-native-pdf';
```
--------------------------------
### Blob URL Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
On Android, Blob URLs can be used to reference PDF data. Ensure the URL includes offset and size parameters if necessary.
```javascript
{
uri: "blob:xxxxxxxx-...?offset=0&size=xxx"
}
```
--------------------------------
### Accessing PDF Reference with createRef
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/INDEX.md
Use `createRef` to get a reference to the Pdf component in class components. This allows you to call methods like `setPage`.
```typescript
import React from 'react';
// Assuming PdfRef is defined elsewhere
// this.pdf = React.createRef();
// this.pdf.current?.setPage(5);
```
--------------------------------
### Accessing PDF Reference with useRef
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/INDEX.md
Use `useRef` to get a reference to the Pdf component in functional components. This allows you to call methods like `setPage`.
```typescript
import { useRef } from 'react';
// Assuming PdfRef is defined elsewhere
// const pdfRef = useRef(null);
// pdfRef.current?.setPage(5);
```
--------------------------------
### PdfViewFlatList Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PdfViewFlatList.md
This snippet shows the typical props used when integrating PdfViewFlatList within a PdfView component. It highlights key configuration options for performance and user experience.
```javascript
}
initialScrollIndex={this.props.page < 1 ? 0 : this.props.page - 1}
onViewableItemsChanged={this._onViewableItemsChanged}
viewabilityConfig={VIEWABILITYCONFIG}
onScroll={this._onScroll}
onContentSizeChange={this._onListContentSizeChange}
scrollEnabled={!this.props.singlePage}
/>
```
--------------------------------
### TypeScript Text Selection Event Example
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Handles text selection events on iOS. The event object indicates whether text was selected or the selection was cleared.
```typescript
{
nativeEvent: { type: 'selectionCleared' }
}
// or
{
nativeEvent: { type: 'selectionChanged', text: 'selected text' }
}
```
--------------------------------
### Add PDF to Project Assets
Source: https://github.com/wonday/react-native-pdf/blob/master/windows/README.md
Include this XML snippet in your app's .vcxproj file to bundle a PDF asset with your application. Ensure it is placed before the \"packages.config\" entry.
```xml
true
```
--------------------------------
### Utility Methods
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/MANIFEST.md
Utility methods for gesture handling and list manipulation.
```APIDOC
## Utility Methods
### Description
Utility methods for enhanced functionality.
### Methods
- **PinchZoomView gesture handlers**: Provides gesture handling for pinch-to-zoom functionality.
- **DoubleTapView methods**: Methods for handling double-tap gestures.
- **PdfView lifecycle methods**: Lifecycle methods for the PDF view component.
- **PdfViewFlatList.scrollToXY(x: number, y: number)**: Scrolls the PDF view to the specified X and Y coordinates.
```
--------------------------------
### Usage Example of DoubleTapView
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/DoubleTapView.md
Demonstrates how to use the DoubleTapView component in a React Native application to handle single and double taps, updating a tap count display.
```javascript
import React from 'react';
import { View, Text } from 'react-native';
import DoubleTapView from 'react-native-pdf/DoubleTapView';
export function TappableContent() {
const [tapCount, setTapCount] = React.useState(0);
return (
{
setTapCount(c => c + 1);
console.log(`Single tap #${tapCount} at (${x}, ${y})`);
}}
onDoubleTap={() => {
console.log('Double tap - zoom in!');
setTapCount(0);
}}
style={{ flex: 1, backgroundColor: '#fff' }}
>
Tap count: {tapCount}
);
}
```
--------------------------------
### Full-Screen Reader Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
Use this configuration for a full-screen PDF reader experience. It enables paging for a book-like navigation.
```javascript
```
--------------------------------
### Preload PDFs to Warm Cache
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/advanced-patterns.md
Optimize initial load times by pre-loading important PDF documents into the cache. The `warmPdfCache` function takes an array of URIs, attempts to load metadata for each, and uses `Promise.allSettled` to handle the results asynchronously. This ensures that frequently accessed PDFs are readily available.
```javascript
async function warmPdfCache(uris) {
const promises = uris.map(async (uri) => {
try {
const source = {
uri,
cache: true,
cacheFileName: `preload-${hashUri(uri)}`
};
// Preload by trying to load metadata
await PdfManager.loadFile(uri, '');
} catch (error) {
console.warn(`Failed to preload ${uri}:`, error);
}
});
await Promise.allSettled(promises);
}
// Usage
React.useEffect(() => {
const importantDocs = [
'https://example.com/guide.pdf',
'https://example.com/terms.pdf'
];
warmPdfCache(importantDocs);
}, []);
```
--------------------------------
### PDF Viewer with Caching and Navigation
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/README.md
Configures the Pdf component with caching enabled and demonstrates how to use a ref to navigate to a specific page after loading.
```javascript
const pdfRef = useRef(null);
setTotal(pages)}
onPageChanged={(page) => setCurrent(page)}
/>
// Jump to page 5
pdfRef.current?.setPage(5);
```
--------------------------------
### Configure Progress Container Style
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
Customize the appearance of the loading indicator's container. This allows for background color and border radius adjustments.
```javascript
```
--------------------------------
### Implement PDF Viewer Analytics Tracking
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/advanced-patterns.md
This component tracks user interactions within a PDF viewer, such as opening, closing, page changes, zooming, link clicks, and errors, sending events to Firebase Analytics. Ensure `@react-native-firebase/analytics` is installed and configured.
```javascript
import analytics from '@react-native-firebase/analytics';
export function AnalyticsPdfViewer({ documentId, uri }) {
const pdfRef = useRef(null);
const startTimeRef = useRef(Date.now());
const pagesVisitedRef = useRef(new Set([1]));
const trackEvent = async (event, params = {}) => {
await analytics().logEvent(event, {
documentId,
timestamp: new Date().toISOString(),
...params
});
};
React.useEffect(() => {
trackEvent('pdf_opened', { duration: 0 });
return () => {
const duration = Date.now() - startTimeRef.current;
const pagesViewed = pagesVisitedRef.current.size;
trackEvent('pdf_closed',
{
duration: Math.round(duration / 1000),
pagesViewed
}
);
};
}, []);
return (
{
pagesVisitedRef.current.add(page);
trackEvent('page_viewed', { page, total });
}}
onScaleChanged={(scale) => {
trackEvent('zoom_changed', { scale });
}}
onPressLink={(url) => {
trackEvent('link_clicked', { url });
}}
onError={(error) => {
trackEvent('pdf_error', { message: error.message });
}}
style={{ flex: 1 }}
/>
);
}
```
--------------------------------
### iOS Info.plist Configuration for HTTP
Source: https://github.com/wonday/react-native-pdf/blob/master/README.md
Add this configuration to your iOS `info.plist` file to allow insecure HTTP connections for specific domains when loading PDFs.
```xml
NSAppTransportSecurityNSExceptionDomainsyourserver.comNSIncludesSubdomainsNSTemporaryExceptionAllowsInsecureHTTPLoadsNSTemporaryExceptionMinimumTLSVersionTLSv1.1
```
--------------------------------
### Clear Old PDF Cache Files
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/advanced-patterns.md
Implement a function to clean up the cache by removing PDF files older than a specified number of days. This function iterates through files in the cache directory, checks their last modified date, and deletes those exceeding the age limit using `RNFetchBlob.fs.unlink`. Ensure `RNFetchBlob` is properly installed and configured.
```javascript
async function clearOldCache(olderThanDays = 30) {
const cacheDir = RNFetchBlob.fs.dirs.CacheDir;
const files = await RNFetchBlob.fs.ls(cacheDir);
const now = Date.now();
const thirtyDaysMs = olderThanDays * 24 * 60 * 60 * 1000;
for (const file of files) {
if (file.endsWith('.pdf')) {
try {
const stats = await RNFetchBlob.fs.stat(`${cacheDir}/${file}`);
if (now - stats.lastModified > thirtyDaysMs) {
await RNFetchBlob.fs.unlink(`${cacheDir}/${file}`);
}
} catch (error) {
console.error(`Error checking ${file}:`, error);
}
}
}
}
```
--------------------------------
### Thumbnail Grid Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
Configure the PDF component to display a single page at a time with a fixed small scale, suitable for thumbnail previews. Scrolling and double-tap zoom are disabled.
```javascript
```
--------------------------------
### _renderList()
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PdfView.md
Renders the main FlatList component that displays all the pages of the PDF with specific performance optimizations.
```APIDOC
## _renderList()
```typescript
_renderList(): React.ReactElement
```
Render the FlatList with all pages.
**Configuration:**
- windowSize: 11 (render 11 pages at a time)
- maxToRenderPerBatch: 1 (render one page per batch)
- pinchGestureEnabled: false (handled by PinchZoomView)
- initialScrollIndex: page - 1 (1-based to 0-based)
```
--------------------------------
### Fit to Width with Custom Loading Indicator
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Configure the PDF to fit its width and provide a custom loading indicator using renderActivityIndicator. Also logs loading progress.
```javascript
import { ActivityIndicator } from 'react-native';
(
)}
onLoadProgress={(percent) => console.log(`${(percent * 100).toFixed(0)}%`)}
style={{ flex: 1 }}
/>
```
--------------------------------
### Custom Authentication Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
This configuration shows how to use custom authentication headers for fetching PDFs from an API. It supports methods like POST and includes authorization headers.
```javascript
```
--------------------------------
### Fit-to-Width Document Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
Configure the PDF to fit the width of the screen. This is useful for documents where content width is more important than height.
```javascript
```
--------------------------------
### Usage of PdfRef to Set Page
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/types.md
Demonstrates how to use the `PdfRef` interface with `useRef` to programmatically navigate to a specific page in the PDF viewer.
```typescript
const pdfRef = useRef(null);
// Later...
pdfRef.current?.setPage(5);
```
--------------------------------
### _getItemLayout(data, index)
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PdfView.md
Provides the FlatList with item layout information (length, offset, index) for performance optimization.
```APIDOC
## _getItemLayout(data, index)
```typescript
_getItemLayout(data: any[], index: number): {length, offset, index}
```
Provide FlatList with item dimensions for optimization.
**Returns:** Object with calculated page and separator dimensions
```
--------------------------------
### Basic PDF Loading
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/Pdf.md
Load and display a PDF from a URI. Handles the onLoadComplete callback to log the number of pages.
```javascript
import React from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import Pdf from 'react-native-pdf';
export default function BasicPdfViewer() {
const source = {
uri: 'https://samples.leanpub.com/thereactnativebook-sample.pdf',
cache: true
};
return (
{
console.log(`PDF has ${numberOfPages} pages`);
}}
style={styles.pdf}
/>
);
}
const styles = StyleSheet.create({
container: { flex: 1, marginTop: 25 },
pdf: { flex: 1, width: Dimensions.get('window').width }
});
```
--------------------------------
### Handle Missing PDF Source
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/errors.md
Catch errors when the 'source' prop is missing, null, or undefined. Ensure a valid source prop with a 'uri' property is provided.
```javascript
try {
// Missing source - will throw
} catch (error) {
console.error(error); // "no pdf source!"
}
```
--------------------------------
### Pdf Component Ref Methods
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/types.md
Provides methods to interact with the Pdf component instance after it has been rendered.
```APIDOC
## PdfRef
### Description
Ref interface for the Pdf component.
### Methods
#### setPage(pageNumber: number)
- **Description**: Navigate to the specified page number.
- **Parameters**:
- **pageNumber** (number) - Required - The page number to navigate to.
### Usage
```typescript
const pdfRef = useRef(null);
// Later...
pdfRef.current?.setPage(5);
```
```
--------------------------------
### Integrating DoubleTapView with PdfView
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/DoubleTapView.md
Shows how to wrap PdfPageView with DoubleTapView to enable tap gestures. Handles single and double taps with custom callbacks.
```javascript
this._onItemSingleTap(index, x, y)}
onDoubleTap={() => this._onItemDoubleTap(index)}
style={{flexDirection: this.props.horizontal ? 'row' : 'column'}}>
{/* separator if not last page */}
```
--------------------------------
### Graceful Fallback UI for PDF Loading Errors
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/advanced-patterns.md
Implement a fallback UI with a retry button and optional placeholder when the PDF fails to load. This pattern helps users recover from transient errors.
```javascript
export function PdfWithFallback({ uri, placeholder }) {
const [error, setError] = React.useState(null);
const [useCache, setUseCache] = React.useState(true);
return (
{error ? (
{error}
{
setError(null);
setUseCache(!useCache); // Force reload
}}
/>
{placeholder && (
{placeholder}
)}
) : (
{
if (error.message.includes('DownloadFailed') && useCache) {
// Retry without cache clear
setUseCache(false);
} else {
setError(error.message);
}
}}
style={{ flex: 1 }}
/>
)}
);
}
```
--------------------------------
### Define PDF Source Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/types.md
Use the Source type to configure how PDF files are loaded, including URI, headers, caching, and expiration.
```typescript
type Source = {
uri?: string;
headers?: {
[key: string]: string;
};
cache?: boolean;
cacheFileName?: string;
expiration?: number;
method?: string;
};
```
```typescript
const source: Source = {
uri: 'https://example.com/document.pdf',
cache: true,
cacheFileName: 'my-document',
expiration: 86400, // 24 hours
headers: {
'Authorization': 'Bearer token123'
}
};
```
--------------------------------
### Integration with PdfView
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PinchZoomView.md
Shows how PinchZoomView can be used to wrap content within PdfView, enabling pinch-to-zoom on PDF documents. It requires layout and scale change handlers.
```javascript
{this.state.pdfLoaded && this._renderList()}
```
--------------------------------
### Offline-First with Caching Configuration
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/configuration.md
Configure the PDF component for offline use by enabling caching with a specified file name and expiration time. Includes an error handler for download failures.
```javascript
{
if (error.message.includes('DownloadFailed')) {
// Try to load from cache instead
}
}}
style={{ flex: 1 }}
/>
```
--------------------------------
### React Native PDF Ref Methods
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/README.md
Illustrates the available methods on the Pdf component's ref, such as navigating to a specific page.
```typescript
// Ref methods:
// `setPage(pageNumber: number): void`
```
--------------------------------
### Handling PDF Download Progress
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/INDEX.md
Implement the `onLoadProgress` callback to track the download progress of a PDF. The progress value ranges from 0 to 1.
```javascript
{
// progress is 0 to 1
console.log(`Loading: ${Math.round(progress * 100)}%`);
}}
/>
```
--------------------------------
### Source Type
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/types.md
Configuration object for loading PDF files, specifying URI, headers, caching, and request method.
```APIDOC
## Source Type
### Description
PDF source configuration object for loading PDF files.
### Fields
#### Path Parameters
- **uri** (string) - Required - PDF location URI (http://, file://, data:, bundle-assets://, content://, blob:, ms-appx://)
- **headers** (object) - Optional - Custom HTTP headers for network requests (e.g., Authorization, User-Agent)
- **cache** (boolean) - Optional - Cache downloaded PDFs to device storage (default: false)
- **cacheFileName** (string) - Optional - Custom name for cache file; defaults to SHA1(uri).pdf
- **expiration** (number) - Optional - Cache expiration in seconds (0 = never expire, default: 0)
- **method** (string) - Optional - HTTP method for requests (default: "GET")
### Request Example
```typescript
const source = {
uri: 'https://example.com/document.pdf',
cache: true,
cacheFileName: 'my-document',
expiration: 86400, // 24 hours
headers: {
'Authorization': 'Bearer token123'
}
};
```
```
--------------------------------
### Uncommon Import (Lower-level API)
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/modules.md
This pattern imports PdfManager for direct PDF loading, which is a lower-level API and less commonly used. Ensure you handle asynchronous operations correctly.
```javascript
// Direct PDF loading
import PdfManager from 'react-native-pdf/PdfManager';
const [fileNo, pages, width, height] = await PdfManager.loadFile(path, password);
```
--------------------------------
### Provide FlatList Item Layout Information
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/api-reference/PdfView.md
Optimizes FlatList performance by providing layout information (length, offset, index) for each page item. This allows the list to render more efficiently.
```typescript
_getItemLayout(data: any[], index: number): {length, offset, index}
```
--------------------------------
### Implement Resumable Downloads for PDFs
Source: https://github.com/wonday/react-native-pdf/blob/master/_autodocs/advanced-patterns.md
This hook manages the source for a PDF, enabling resumable downloads by setting appropriate cache headers and file names. It's useful for large PDF files where interruptions might occur.
```javascript
function useResumablePdfSource(uri, cacheKey) {
const [source, setSource] = React.useState(null);
const [downloadProgress, setDownloadProgress] = React.useState(0);
React.useEffect(() => {
const fullUri = `${uri}?cache_key=${cacheKey}`;
setSource({
uri: fullUri,
cache: true,
cacheFileName: `resume-${cacheKey}`,
headers: {
'Accept-Encoding': 'gzip, deflate',
'Cache-Control': 'max-age=2592000'
}
});
}, [uri, cacheKey]);
return { source, downloadProgress };
}
```