react-native-pdf-renderer 2.3.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,168 +1,411 @@
1
- # React-Native Pdf Renderer
1
+ <p align="center">
2
+ <img src="docs/cover.svg" alt="React Native PDF Renderer - Pure native, zoomable PDF viewer for Android and iOS" width="800">
3
+ <br>
4
+ <sub>A zoomable, blazing fast, zero dependencies, pure native, typed PDF Renderer for Android and iOS.</sub>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <b>React Native PDF Renderer</b> provides high-performance, dependency-free native PDF rendering for React Native by directly utilizing Android's <a href="https://developer.android.com/reference/android/graphics/pdf/PdfRenderer">PdfRenderer</a> and Apple's <a href="https://developer.apple.com/documentation/pdfkit">PDFKit</a>. Enjoy smooth multi-page scrolling, fluid pinch-to-zoom, thumbnail previews, and comprehensive scale events without the maintenance burden of third-party native binaries.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="LICENSE"><img src="https://img.shields.io/github/license/douglasjunior/react-native-pdf-renderer?style=flat-square&color=8B7BFF" alt="MIT License"></a>
13
+ <a href="https://www.npmjs.com/package/react-native-pdf-renderer"><img src="https://img.shields.io/npm/v/react-native-pdf-renderer?style=flat-square&color=3FD0FF" alt="npm version"></a>
14
+ <a href="https://www.npmjs.com/package/react-native-pdf-renderer"><img src="https://img.shields.io/npm/dt/react-native-pdf-renderer?style=flat-square&color=FF6A8E" alt="npm downloads"></a>
15
+ <img src="https://img.shields.io/badge/platform-Android_%7C_iOS-lightgrey?style=flat-square" alt="Platform Android and iOS">
16
+ <img src="https://img.shields.io/badge/React_Native->=0.80.0-61DAFB?style=flat-square&logo=react&logoColor=black" alt="React Native >= 0.80.0">
17
+ <img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript strict">
18
+ <a href="https://github.com/douglasjunior/react-native-pdf-renderer/pulls"><img src="https://img.shields.io/badge/PRs-welcome-22C55E?style=flat-square" alt="PRs welcome"></a>
19
+ </p>
20
+
21
+ <p align="center">
22
+ <a href="#-quick-start"><b>Quick Start</b></a> ·
23
+ <a href="#-why-another-pdf-renderer">Why</a> ·
24
+ <a href="#-previews">Previews</a> ·
25
+ <a href="#-requirements">Requirements</a> ·
26
+ <a href="#-installation">Installation</a> ·
27
+ <a href="#-basic-usage">Usage</a> ·
28
+ <a href="#-api-reference">API Reference</a> ·
29
+ <a href="#-limitations--caveats">Limitations</a> ·
30
+ <a href="#-testing-with-jest">Testing</a> ·
31
+ <a href="#-contributing">Contributing</a>
32
+ </p>
33
+
34
+ ---
35
+
36
+ ## 🚀 Quick Start
2
37
 
3
- [![License MIT](https://img.shields.io/badge/licence-MIT-blue.svg)](https://github.com/douglasjunior/react-native-pdf-renderer/blob/main/LICENSE)
4
- [![npm version](https://img.shields.io/npm/v/react-native-pdf-renderer.svg)](https://www.npmjs.com/package/react-native-pdf-renderer?activeTab=versions)
5
- [![npm downloads](https://img.shields.io/npm/dt/react-native-pdf-renderer.svg)](https://www.npmjs.com/package/react-native-pdf-renderer)
38
+ ```bash
39
+ # 1. Install package
40
+ yarn add react-native-pdf-renderer
41
+ # or: npm i -S react-native-pdf-renderer
42
+
43
+ # 2. Install CocoaPods dependencies for iOS
44
+ cd ios && pod install
45
+ ```
46
+
47
+ ```tsx
48
+ import React from 'react';
49
+ import { SafeAreaView } from 'react-native-safe-area-context';
50
+ import PdfRendererView from 'react-native-pdf-renderer';
51
+
52
+ export default function App() {
53
+ return (
54
+ <SafeAreaView style={{ flex: 1 }}>
55
+ <PdfRendererView
56
+ style={{ flex: 1, backgroundColor: '#000000' }}
57
+ source="file:///path/to/local/file.pdf"
58
+ distanceBetweenPages={16}
59
+ maxZoom={5}
60
+ onPageChange={(current, total) => {
61
+ console.log(`Page: ${current + 1} of ${total}`);
62
+ }}
63
+ />
64
+ </SafeAreaView>
65
+ );
66
+ }
67
+ ```
68
+
69
+ ---
70
+
71
+ ## 💡 Why Another PDF Renderer?
72
+
73
+ The main reason why this library was created is to **avoid using third-party native dependencies**, such as `com.github.TalbotGooday:AndroidPdfViewer`, `com.github.mhiew:android-pdf-viewer`, `react-native-blob-util`, or `react-native-webview`.
74
+
75
+ ### But why?
76
+
77
+ Every React Native developer knows (or will discover soon) [the pain of updating the React Native ecosystem](https://x.com/flexbox_/status/1806786055057674337) whenever a new major Android or iOS version comes out. Third-party native wrappers often become abandoned, break during Gradle or Xcode updates, or introduce incompatible native architectures.
6
78
 
7
- ⚛ A zoomable, blazing fast, zero dependencies, pure native, typed PDF Renderer for Android and iOS.
79
+ Here, we eliminate this friction entirely:
8
80
 
9
- It uses [PdfRenderer](https://developer.android.com/reference/android/graphics/pdf/PdfRenderer) for Android and [PdfKit](https://developer.apple.com/documentation/pdfkit) for iOS.
81
+ - ⚛️ **Pure Platform Native:** Relies exclusively on official platform SDK engines: [PdfRenderer](https://developer.android.com/reference/android/graphics/pdf/PdfRenderer) on Android and [PDFKit](https://developer.apple.com/documentation/pdfkit) on iOS.
82
+ - 🛡️ **Zero Native Bloat:** Zero third-party C++/Java/Obj-C dependencies to link, compile, or debug during React Native upgrades.
83
+ - 🔍 **Pinch-to-Zoom & Pan:** Smooth, continuous gesture-based scaling with configurable zoom ceilings and scale tracking.
84
+ - 📑 **Single & Multi-Page Modes:** Seamless vertical continuous scroll for multi-page documents, or single-page view for thumbnail covers.
85
+ - 🛡️ **OOM & Canvas Crash Prevention:** Built-in `maxPageResolution` safeguards on Android prevent out-of-memory bitmap allocations during deep zooms.
86
+ - 📘 **TypeScript Included:** Written in TypeScript with complete prop definitions and IntelliSense documentation.
87
+ - 🧪 **Mock Ready:** Pre-configured Jest mock included for painless snapshot and unit testing.
10
88
 
11
- |Android|iOS|
12
- |-|-|
13
- |<img src="https://github.com/douglasjunior/react-native-pdf-renderer/raw/main/screenshots/android.gif" width="240"/>|<img src="https://github.com/douglasjunior/react-native-pdf-renderer/raw/main/screenshots/ios.gif" width="240"/>
89
+ ---
14
90
 
15
- ## Why another PDF renderer?
91
+ ## 📸 Previews
16
92
 
17
- The main reason why I create this library is to avoid using third-party native dependencies, like `com.github.TalbotGooday:AndroidPdfViewer`, `com.github.mhiew:android-pdf-viewer`, `react-native-blob-util` or even `react-native-webview`.
93
+ | Android | iOS |
94
+ |:---:|:---:|
95
+ | <img src="https://github.com/douglasjunior/react-native-pdf-renderer/raw/main/screenshots/android.gif" width="280" alt="Android PDF Renderer Demo" /> | <img src="https://github.com/douglasjunior/react-native-pdf-renderer/raw/main/screenshots/ios.gif" width="280" alt="iOS PDF Renderer Demo" /> |
18
96
 
19
- But why?
97
+ ---
20
98
 
21
- Every React Native developer knows (or will discover soon) [the pain of updating the React Native ecosystem](https://x.com/flexbox_/status/1806786055057674337) when a new version of Android or iOS comes out, so here we want to avoid this pain as much as possible.
99
+ ## 📋 Requirements
22
100
 
23
- ## Requirements
101
+ | Platform / Tool | Minimum Version | Notes |
102
+ |---|---|---|
103
+ | **React Native** | `>= 0.80.0` | Old & New Architecture support |
104
+ | **iOS** | `>= 12.0` | Uses native `PDFKit` |
105
+ | **Android** | `API 21+` (Android 5.0+) | Uses native `android.graphics.pdf.PdfRenderer` |
24
106
 
25
- - React Native >= 0.71.0
26
- - iOS >= 12.0
27
- - Android >= API 21
107
+ ---
28
108
 
29
- ## Install
109
+ ## 📦 Installation
30
110
 
31
- Install dependency package
111
+ ### 1. Install JavaScript Package
112
+
113
+ Using yarn:
32
114
  ```bash
33
115
  yarn add react-native-pdf-renderer
34
116
  ```
35
- Or
117
+
118
+ Using npm:
36
119
  ```bash
37
120
  npm i -S react-native-pdf-renderer
38
121
  ```
39
122
 
40
- Go to the folder **your-project/ios** and run `pod install`, and you're done.
123
+ ### 2. iOS CocoaPods Setup
41
124
 
42
- ### Android specific (optional)
125
+ Navigate to your `ios` folder and run `pod install`:
126
+
127
+ ```bash
128
+ cd ios && pod install
129
+ ```
43
130
 
44
- Customize the [`androidx.recyclerview:recyclerview`](https://developer.android.com/jetpack/androidx/releases/recyclerview) version by setting `ext` in your `android/build.gradle` file.
131
+ ### 3. Android Specific Setup (Optional)
45
132
 
46
- Example:
133
+ You can customize the [`androidx.recyclerview:recyclerview`](https://developer.android.com/jetpack/androidx/releases/recyclerview) version by configuring `ext` inside your root `android/build.gradle` file (defaults to `1.4.0`):
47
134
 
48
135
  ```gradle
49
136
  buildscript {
50
137
  ext {
51
- recyclerviewVersion = "1.2.1"
138
+ recyclerViewVersion = "1.4.0"
52
139
  }
53
140
  ...
54
141
  }
55
142
  ```
56
143
 
57
- ## Basic usage
144
+ ---
145
+
146
+ ## 🛠 Basic Usage
58
147
 
59
- There is only one component that you need to use to render the PDF file.
148
+ There is only one primary component that you need to render PDF documents: `<PdfRendererView />`.
60
149
 
61
- ```jsx
150
+ ```tsx
151
+ import React from 'react';
152
+ import { View, StyleSheet } from 'react-native';
153
+ import { SafeAreaView } from 'react-native-safe-area-context';
62
154
  import PdfRendererView from 'react-native-pdf-renderer';
63
155
 
64
156
  const App = () => {
65
157
  return (
66
- <SafeAreaView style={{flex: 1}}>
158
+ <SafeAreaView style={styles.container}>
67
159
  <PdfRendererView
68
- style={{backgroundColor: 'red'}}
160
+ style={styles.pdf}
69
161
  source="file:///path/to/local/file.pdf"
70
162
  distanceBetweenPages={16}
71
163
  maxZoom={5}
72
164
  onPageChange={(current, total) => {
73
- console.log(current, total);
165
+ console.log(`Current page: ${current + 1} / ${total}`);
166
+ }}
167
+ onError={() => {
168
+ console.warn('Failed to load PDF');
74
169
  }}
75
170
  />
76
171
  </SafeAreaView>
77
172
  );
78
- }
173
+ };
174
+
175
+ const styles = StyleSheet.create({
176
+ container: {
177
+ flex: 1,
178
+ },
179
+ pdf: {
180
+ flex: 1,
181
+ backgroundColor: '#1e1e1e',
182
+ },
183
+ });
79
184
 
80
185
  export default App;
81
186
  ```
82
187
 
83
- The `source` prop must point to a file stored inside the device memory.
188
+ ### 📁 Working with Remote Files
84
189
 
85
- If the file is online, you can use some third-party library like `expo-file-system`, `rn-fetch-blob`, or `react-native-blob-util` to download and save it locally.
190
+ > [!IMPORTANT]
191
+ > The `source` prop **must point to a local file stored inside the device's storage** (e.g., `file:///data/user/0/...` or `file:///var/mobile/...`).
86
192
 
87
- For more details, see the [Sample Project](https://github.com/douglasjunior/react-native-pdf-renderer/blob/main/Sample/App.tsx).
193
+ If your PDF file is hosted on a remote server, download it to device storage first using a file system library such as [`expo-file-system`](https://docs.expo.dev/versions/latest/sdk/filesystem/) (use `expo-file-system/legacy` on Expo SDK 54+), `react-native-blob-util`, or `rn-fetch-blob`:
88
194
 
89
- ## PdfRendererView props
195
+ ```tsx
196
+ import React, { useState, useEffect } from 'react';
197
+ import { ActivityIndicator, StyleSheet, Text, View } from 'react-native';
198
+ // Note: expo-file-system/legacy is used on Expo SDK 54+; earlier SDKs import from 'expo-file-system'
199
+ import * as FileSystem from 'expo-file-system/legacy';
200
+ import PdfRendererView from 'react-native-pdf-renderer';
201
+
202
+ export function RemotePdfViewer({ url }: { url: string }) {
203
+ const [localUri, setLocalUri] = useState<string | null>(null);
204
+ const [error, setError] = useState<string | null>(null);
205
+
206
+ useEffect(() => {
207
+ let isMounted = true;
208
+
209
+ async function downloadPdf() {
210
+ try {
211
+ setError(null);
212
+ const fileUri = `${FileSystem.documentDirectory}document.pdf`;
213
+ const result = await FileSystem.downloadAsync(url, fileUri);
214
+ if (result.status < 200 || result.status >= 300) {
215
+ throw new Error(`Download failed (HTTP ${result.status})`);
216
+ }
217
+ if (isMounted) {
218
+ setLocalUri(result.uri);
219
+ }
220
+ } catch (err) {
221
+ if (isMounted) {
222
+ setError(err instanceof Error ? err.message : 'Failed to download PDF');
223
+ }
224
+ }
225
+ }
226
+
227
+ downloadPdf();
228
+ return () => {
229
+ isMounted = false;
230
+ };
231
+ }, [url]);
232
+
233
+ if (error) {
234
+ return (
235
+ <View style={styles.center}>
236
+ <Text style={styles.errorText}>{error}</Text>
237
+ </View>
238
+ );
239
+ }
240
+
241
+ if (!localUri) {
242
+ return (
243
+ <View style={styles.center}>
244
+ <ActivityIndicator size="large" color="#3fd0ff" />
245
+ </View>
246
+ );
247
+ }
248
+
249
+ return (
250
+ <PdfRendererView
251
+ style={{ flex: 1 }}
252
+ source={localUri}
253
+ distanceBetweenPages={16}
254
+ maxZoom={5}
255
+ />
256
+ );
257
+ }
258
+
259
+ const styles = StyleSheet.create({
260
+ center: {
261
+ flex: 1,
262
+ justifyContent: 'center',
263
+ alignItems: 'center',
264
+ },
265
+ errorText: {
266
+ color: '#ef4444',
267
+ fontSize: 14,
268
+ },
269
+ });
270
+ ```
271
+
272
+ For a comprehensive real-world example featuring scale indicators, full-screen toggles, and modal dialogues, see the [Sample Project](https://github.com/douglasjunior/react-native-pdf-renderer/blob/main/Sample/App.tsx).
273
+
274
+ ---
275
+
276
+ ## 📖 API Reference
277
+
278
+ ### `<PdfRendererView />` Props
279
+
280
+ | Prop | Type | Default | Description |
281
+ |---|---|:---:|---|
282
+ | `source` | `string` | — | Path to a local file stored on the device (e.g. `file:///path/to/file.pdf`). |
283
+ | `distanceBetweenPages` | `number` | `16` | Vertical spacing in `DPI` between rendered pages. |
284
+ | `maxZoom` | `number` | `5` | Maximum allowable zoom scale factor. |
285
+ | `maxPageResolution` | `number` | `2048` | *(Android only)* Maximum page resolution (width/height) in pixels when zooming. Designed to prevent Android OOM / Canvas crashes when zooming deeply ([#26](https://github.com/douglasjunior/react-native-pdf-renderer/issues/26)). |
286
+ | `singlePage` | `boolean` | `false` | Renders only the first page without scrolling. Ideal for displaying document thumbnails. |
287
+ | `onPageChange` | `(current: number, total: number) => void` | — | Callback invoked when the user scrolls between pages. `current` is zero-indexed. |
288
+ | `onScaleChange` | `(scale: number) => void` | — | *(Android only)* Invoked continuously while a pinch gesture is in progress. `1` is the unzoomed baseline (fit-to-width in multi-page mode and fit-to-center in `singlePage` mode). Never exceeds `maxZoom`. |
289
+ | `onError` | `() => void` | — | Callback invoked when an error occurs while rendering the PDF. |
290
+ | `style` | `StyleProp<ViewStyle>` | — | Styles applied to the native view container. *(Note: border radius is not directly supported; see [Limitations](#border-radius)).* |
291
+ | `testID` | `string` | — | Optional identifier used to locate this view in automated end-to-end testing. |
90
292
 
91
- |Name|Type|Default|Description|
92
- |-|-|-|-|
93
- |source|`string`||Path to a file stored on the device.|
94
- |distanceBetweenPages|`number`|`16`|Distance in `DPI` between pages.|
95
- |maxZoom|`number`|`5`|Max zoom scale.|
96
- |maxPageResolution|`number`|`2048`|(Android only) Max page resolution (width/height) in pixels when zooming. Defined to prevent Android crash when zooming too much: https://github.com/douglasjunior/react-native-pdf-renderer/issues/26 . |
97
- |singlePage|`boolean`|`false`|Renders only the first page without scroll. (useful for display thumbnail)|
98
- |onPageChange|`(current: number, total: number) => void`||Invoked on pages scroll.|
99
- |onError|`() => void`||Invoked when an error occurs.|
100
- |style|`StyleProp<ViewStyle>`||Styles to be applied to the native [view](https://reactnative.dev/docs/view-style-props).|
293
+ ---
101
294
 
102
- ## Limitations
295
+ ## ⚠ Limitations & Caveats
103
296
 
104
- ### Page interactions
297
+ ### Page Interactions
105
298
 
106
- Because Android renders the PDF page as a full image, it does not support text selection, accessibility, or handling links.
299
+ Because Android renders PDF pages as full bitmap images via `android.graphics.pdf.PdfRenderer`, native text selection, screen reader accessibility for PDF contents, and hyperlink clicks within the PDF are not supported on Android.
107
300
 
108
- If any of these features are important for your product, we recommend adding a button to open the PDF in an external PDF viewer.
301
+ > [!TIP]
302
+ > If text selection or interactive document links are critical for your use case, we recommend adding an action button to open the PDF in the platform's external system viewer.
109
303
 
110
- ### Size measuring
304
+ ### Size Measuring
111
305
 
112
- The `PdfRendererView` is `flex: 1` by default, so you need to make sure that your parents `View`s are `flex: 1` or have a fixed `width/height`.
306
+ `PdfRendererView` has `flex: 1` applied by default. Ensure that parent containers either have `flex: 1` or explicitly defined dimensions (`width` and `height`).
113
307
 
114
- ### Border radius
308
+ ### Border Radius
115
309
 
116
- The `borderRadius` style is ignored by React Native custom view in Android and crashes on iOS. (read more [#1](https://github.com/douglasjunior/react-native-pdf-renderer/issues/1#issuecomment-1483395465))
310
+ The `borderRadius` style property is ignored by React Native custom views on Android and can cause native crashes on iOS (read more in issue [#1](https://github.com/douglasjunior/react-native-pdf-renderer/issues/1#issuecomment-1483395465)).
117
311
 
118
- If you need `borderRadius`, the best option is to wrap the `PdfRendererView` in another `View`.
312
+ If you need rounded corners, wrap `<PdfRendererView />` inside a container `View` with clipping:
119
313
 
120
- ```jsx
314
+ ```tsx
121
315
  <View style={{ flex: 1, borderRadius: 24, overflow: 'hidden' }}>
122
316
  <PdfRendererView
123
- // ...
317
+ style={{ flex: 1 }}
318
+ source="file:///path/to/file.pdf"
124
319
  />
125
320
  </View>
126
321
  ```
127
322
 
128
- ### Android crash when zooming too much
323
+ ### Android Crash When Zooming Too Much
129
324
 
130
- To prevent Android from crashing when zooming too much, we have a `maxPageResolution` prop that limits the page resolution when zooming. (read more [#26](https://github.com/douglasjunior/react-native-pdf-renderer/issues/26))
325
+ To protect Android devices from out-of-memory crashes when zooming into large documents, use the `maxPageResolution` prop.
131
326
 
132
- If you are receiving the error `java.lang.RuntimeException: Canvas: trying to draw too large(134806560bytes) bitmap`, try to reduce the `maxPageResolution` prop.
327
+ > [!WARNING]
328
+ > If you encounter `java.lang.RuntimeException: Canvas: trying to draw too large(134806560bytes) bitmap`, reduce `maxPageResolution` (e.g. to `1536` or `1024`). Refer to [Issue #26](https://github.com/douglasjunior/react-native-pdf-renderer/issues/26) for details.
133
329
 
134
- ## Mock with jest
330
+ ---
331
+
332
+ ## 🧪 Testing with Jest
333
+
334
+ The library bundles a pre-configured mock view to ensure your test suites run smoothly:
135
335
 
136
336
  ```js
337
+ // jest.setup.js or in your test file
137
338
  jest.mock('react-native-pdf-renderer', () => require('react-native-pdf-renderer/dist/mock'));
138
339
  ```
139
340
 
140
- ## Contribute
341
+ ---
141
342
 
142
- New features, bug fixes, and improvements are welcome! For questions and suggestions use the [issues](https://github.com/douglasjunior/react-native-pdf-renderer/issues).
343
+ ## 🤝 Contributing
143
344
 
144
- <a href="https://www.patreon.com/douglasjunior"><img src="http://i.imgur.com/xEO164Z.png" alt="Become a Patron!" width="200" /></a>
145
- [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://paypal.me/douglasnassif)
345
+ Contributions, bug reports, and pull requests are warmly welcome!
146
346
 
147
- ## Thanks to
347
+ 1. Fork the repository and create your branch from `main`.
348
+ 2. Ensure code compiles and adheres to linting rules.
349
+ 3. Open a pull request explaining your changes and motivation.
148
350
 
149
- This lib is only possible thanks to the community help:
351
+ For questions, discussions, or feature suggestions, please check out the [Issues](https://github.com/douglasjunior/react-native-pdf-renderer/issues) page.
150
352
 
151
- - RecyclerView `notifyDataSetChanged()` not working on React Native: https://stackoverflow.com/a/49381907/2826279
152
- - Add pinch to zoom on RecyclerView: https://stackoverflow.com/a/37895783/2826279
153
- - Using `Matrix` to handle zoom in a View: https://stackoverflow.com/a/55299327/2826279
154
- - [Daniel Felipe Sartório](https://github.com/danielfelipesartorio) for the help with Android native code
353
+ ### Support the Author
155
354
 
156
- ## Star History
355
+ If this library saved you time or solved your PDF rendering challenges, consider supporting the maintainer:
157
356
 
158
- [![Star History Chart](https://api.star-history.com/svg?repos=douglasjunior/react-native-pdf-renderer&type=Date)](https://star-history.com/#douglasjunior/react-native-pdf-renderer)
357
+ <p align="left">
358
+ <a href="https://www.patreon.com/douglasjunior"><img src="https://img.shields.io/badge/Patreon-F96854?style=for-the-badge&logo=patreon&logoColor=white" alt="Become a Patron!" height="32" /></a>
359
+ &nbsp;
360
+ <a href="https://paypal.me/douglasnassif"><img src="https://img.shields.io/badge/Donate-PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white" alt="Donate with PayPal" height="32" /></a>
361
+ </p>
159
362
 
160
- ## License
363
+ ---
161
364
 
162
- ```
365
+ ## 🙏 Thanks to
366
+
367
+ This library is possible thanks to valuable contributions and solutions from the community:
368
+
369
+ - [RecyclerView `notifyDataSetChanged()` not working on React Native](https://stackoverflow.com/a/49381907/2826279)
370
+ - [Add pinch to zoom on RecyclerView](https://stackoverflow.com/a/37895783/2826279)
371
+ - [Using `Matrix` to handle zoom in a View](https://stackoverflow.com/a/55299327/2826279)
372
+ - [Daniel Felipe Sartório](https://github.com/danielfelipesartorio) for native Android code assistance
373
+
374
+ ---
375
+
376
+ ## ⭐ Star History
377
+
378
+ <p align="center">
379
+ <a href="https://star-history.com/#douglasjunior/react-native-pdf-renderer&Date">
380
+ <picture>
381
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=douglasjunior/react-native-pdf-renderer&type=Date&theme=dark" />
382
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=douglasjunior/react-native-pdf-renderer&type=Date" width="600" />
383
+ </picture>
384
+ </a>
385
+ </p>
386
+
387
+ ---
388
+
389
+ ## 📄 License
390
+
391
+ ```text
163
392
  The MIT License (MIT)
164
393
 
165
394
  Copyright (c) 2023 Douglas Nassif Roma Junior
166
395
  ```
167
396
 
168
- See the full [license file](https://github.com/douglasjunior/react-native-pdf-renderer/blob/main/LICENSE).
397
+ See the full [license file](LICENSE).
398
+
399
+ ---
400
+
401
+ ## 🌐 Author & More Projects
402
+
403
+ <p align="center">
404
+ <a href="https://douglasjunior.work">
405
+ <img src="docs/portfolio-banner.svg" alt="Discover more open source projects by Douglas Junior" width="800" />
406
+ </a>
407
+ </p>
408
+
409
+ <p align="center">
410
+ Discover more open-source libraries, creative animation engines, and developer tools at <a href="https://douglasjunior.work"><b>douglasjunior.work</b></a>.
411
+ </p>
@@ -53,7 +53,13 @@ if (isNewArchitectureEnabled()) {
53
53
  }
54
54
 
55
55
  apply plugin: 'com.android.library'
56
- apply plugin: 'kotlin-android'
56
+ // AGP 9 ships built-in Kotlin support and registers the `kotlin` extension
57
+ // itself. Applying the Kotlin plugin on top of it fails configuration with
58
+ // "Cannot add extension with name 'kotlin'". Only apply it when nothing has
59
+ // registered that extension yet.
60
+ if (project.extensions.findByName('kotlin') == null) {
61
+ apply plugin: 'kotlin-android'
62
+ }
57
63
 
58
64
  def reactNativeArchitectures() {
59
65
  def value = project.getProperties().get("reactNativeArchitectures")
package/android/gradlew CHANGED
File without changes
@@ -41,6 +41,7 @@ import java.util.Map;
41
41
  public class PdfRendererViewManagerImpl {
42
42
  public static final String REACT_MODULE_NAME = "RNPdfRendererView";
43
43
  private static final String ON_PAGE_CHANGE_EVENT = "onPageChange";
44
+ private static final String ON_SCALE_CHANGE_EVENT = "onScaleChange";
44
45
  private static final String ON_ERROR_EVENT = "onError";
45
46
 
46
47
  public static Map<String, Object> getExportedCustomBubblingEventTypeConstants() {
@@ -50,6 +51,11 @@ public class PdfRendererViewManagerImpl {
50
51
  put("bubbled", ON_PAGE_CHANGE_EVENT);
51
52
  }});
52
53
  }});
54
+ put(ON_SCALE_CHANGE_EVENT, new HashMap<>() {{
55
+ put("phasedRegistrationNames", new HashMap<String, String>() {{
56
+ put("bubbled", ON_SCALE_CHANGE_EVENT);
57
+ }});
58
+ }});
53
59
  put(ON_ERROR_EVENT, new HashMap<>() {{
54
60
  put("phasedRegistrationNames", new HashMap<String, String>() {{
55
61
  put("bubbled", ON_ERROR_EVENT);
@@ -66,7 +72,7 @@ public class PdfRendererViewManagerImpl {
66
72
  var maxZoom = params.hasKey("maxZoom") ? Double.valueOf(params.getDouble("maxZoom")).floatValue() : 5;
67
73
 
68
74
  if (TextUtils.isEmpty(source)) return;
69
- var file = new File(source.replace("file://", ""));
75
+ var file = new File(source.replaceFirst("^file:/*", "/"));
70
76
 
71
77
  view.post(() -> {
72
78
  try {
@@ -105,6 +111,23 @@ public class PdfRendererViewManagerImpl {
105
111
  };
106
112
  }
107
113
 
114
+ public static Event<?> createOnScaleChangeEvent(int surfaceId, int targetId, float scale) {
115
+ return new Event(surfaceId, targetId) {
116
+ @NonNull
117
+ @Override
118
+ public String getEventName() {
119
+ return ON_SCALE_CHANGE_EVENT;
120
+ }
121
+
122
+ @Override
123
+ protected WritableMap getEventData() {
124
+ var data = Arguments.createMap();
125
+ data.putDouble("scale", scale);
126
+ return data;
127
+ }
128
+ };
129
+ }
130
+
108
131
  public static Event<?> createOnErrorEvent(int surfaceId, int targetId) {
109
132
  return new Event(surfaceId, targetId) {
110
133
  @NonNull
@@ -55,6 +55,7 @@ public class PdfRendererRecyclerView extends RecyclerView {
55
55
  private final ScaleGestureDetector mScaleDetector;
56
56
  private final Matrix mMatrix;
57
57
  private final ObservableZoom mZoomObserver;
58
+ private final ScaleTracker mScaleTracker;
58
59
  private final LayoutManager mLayoutManager;
59
60
  private final PdfRendererRecyclerViewListener mListener;
60
61
  private boolean mRequestedLayout = false;
@@ -70,6 +71,7 @@ public class PdfRendererRecyclerView extends RecyclerView {
70
71
  super(context);
71
72
 
72
73
  mZoomObserver = new ObservableZoom(mMinZoom);
74
+ mScaleTracker = new ScaleTracker(mMinZoom, mMaxZoom);
73
75
 
74
76
  mLayoutManager = new LayoutManager(context);
75
77
  mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
@@ -108,6 +110,47 @@ public class PdfRendererRecyclerView extends RecyclerView {
108
110
 
109
111
  public void setMaxZoom(float maxZoom) {
110
112
  this.mMaxZoom = maxZoom;
113
+ mScaleTracker.setMaxScale(maxZoom);
114
+
115
+ /*
116
+ * Lowering the cap below the zoom already applied would leave the matrix above
117
+ * the new limit: the view would keep drawing the old zoom while the reported
118
+ * scale, which is clamped, stopped describing it. Bring the matrix down now.
119
+ */
120
+ var values = new float[9];
121
+ mMatrix.getValues(values);
122
+ if (values[Matrix.MSCALE_X] > mMaxZoom) {
123
+ validateMatrixLimits();
124
+ postInvalidateOnAnimation();
125
+ dispatchScaleChangeEvent();
126
+ mZoomObserver.setZoom(mMaxZoom);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Reports the effective scale to JavaScript. Must be called only once the matrix
132
+ * holds a value inside the allowed range, either because
133
+ * {@link #validateMatrixLimits()} just ran or because the scale was reset to a
134
+ * known-valid one.
135
+ * <p>
136
+ * This is intentionally separate from {@link ObservableZoom}, which stays on its
137
+ * gesture-end cadence because every notification re-renders the visible page bitmaps.
138
+ */
139
+ private void dispatchScaleChangeEvent() {
140
+ var values = new float[9];
141
+ mMatrix.getValues(values);
142
+
143
+ dispatchScaleChangeEvent(values[Matrix.MSCALE_X]);
144
+ }
145
+
146
+ /**
147
+ * Reports a zoom level that is already known, for the paths that set it rather
148
+ * than read it back from the matrix.
149
+ */
150
+ private void dispatchScaleChangeEvent(float scale) {
151
+ if (mScaleTracker.shouldDispatch(scale)) {
152
+ mListener.onScaleChange(this, mScaleTracker.getScale());
153
+ }
111
154
  }
112
155
 
113
156
  private void dispatchPageChangeEvent() {
@@ -161,6 +204,16 @@ public class PdfRendererRecyclerView extends RecyclerView {
161
204
  : 1;
162
205
  mMatrix.setScale(scale, scale);
163
206
  mMatrix.postTranslate((w - scale * mWidth) / 2f, (h - scale * mHeight) / 2f);
207
+
208
+ /*
209
+ * The matrix was just reset, so whatever zoom the user had applied is gone
210
+ * (a device rotation is the common case). Report it, otherwise JavaScript
211
+ * keeps the stale scale until the next gesture.
212
+ *
213
+ * The value above is a layout compensation factor from integer division, not
214
+ * a zoom level, so the baseline is reported instead of reading the matrix back.
215
+ */
216
+ dispatchScaleChangeEvent(mMinZoom);
164
217
  }
165
218
 
166
219
  private boolean isScrollingInsideZoomedArea() {
@@ -265,11 +318,14 @@ public class PdfRendererRecyclerView extends RecyclerView {
265
318
  mMatrix.setScale(1, 1, 0, 0);
266
319
  validateMatrixLimits();
267
320
  postInvalidateOnAnimation();
321
+ dispatchScaleChangeEvent();
268
322
  mZoomObserver.setZoom(1);
269
323
  }
270
324
 
271
325
  public interface PdfRendererRecyclerViewListener {
272
326
  void onPageChange(PdfRendererRecyclerView target, int position, int total);
327
+
328
+ void onScaleChange(PdfRendererRecyclerView target, float scale);
273
329
  }
274
330
 
275
331
  private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@@ -288,6 +344,7 @@ public class PdfRendererRecyclerView extends RecyclerView {
288
344
  mMatrix.postScale(factor, factor, getWidth() / 2f, getHeight() / 2f);
289
345
  validateMatrixLimits();
290
346
  postInvalidateOnAnimation();
347
+ dispatchScaleChangeEvent();
291
348
 
292
349
  return true;
293
350
  }
@@ -333,6 +390,7 @@ public class PdfRendererRecyclerView extends RecyclerView {
333
390
  validateMatrixLimits();
334
391
 
335
392
  postInvalidateOnAnimation();
393
+ dispatchScaleChangeEvent();
336
394
 
337
395
  mZoomObserver.setZoom(newZoom);
338
396
  return true;
@@ -0,0 +1,90 @@
1
+ // MIT License
2
+
3
+ // Copyright (c) 2026 Douglas Nassif Roma Junior
4
+
5
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ // of this software and associated documentation files (the "Software"), to deal
7
+ // in the Software without restriction, including without limitation the rights
8
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ // copies of the Software, and to permit persons to whom the Software is
10
+ // furnished to do so, subject to the following conditions:
11
+
12
+ // The above copyright notice and this permission notice shall be included in all
13
+ // copies or substantial portions of the Software.
14
+
15
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ // SOFTWARE.
22
+
23
+ package com.github.douglasjunior.reactNativePdfRenderer.modules;
24
+
25
+ /**
26
+ * Decides whether an observed scale should be reported to JavaScript, and with
27
+ * which value. It clamps the observed scale to the allowed range and suppresses
28
+ * repeats and imperceptible changes, so the event is emitted only on the frames
29
+ * where the effective scale moves by a meaningful amount.
30
+ * <p>
31
+ * This is the <b>event</b> trail. It is deliberately separate from
32
+ * {@link ObservableZoom}, which drives page bitmap re-rendering and is notified
33
+ * only when a gesture ends.
34
+ */
35
+ public class ScaleTracker {
36
+ /**
37
+ * Smallest scale change worth a round trip to JavaScript.
38
+ * <p>
39
+ * {@link android.view.ScaleGestureDetector} reports a new scale on every touch
40
+ * move, and every event costs the consumer a re-render, so a slow pinch used to
41
+ * emit one per touch sample while moving the image by nothing visible. This caps
42
+ * the event count by distance travelled instead: about 100 per unit of scale, a
43
+ * step below what is perceptible at any zoom this view allows. A fast pinch
44
+ * across the whole range is unaffected, since each of its frames already moves
45
+ * further than this.
46
+ */
47
+ private static final float SCALE_EPSILON = 0.01f;
48
+
49
+ private final float minScale;
50
+ private float maxScale;
51
+ private float lastDispatchedScale;
52
+
53
+ public ScaleTracker(float minScale, float maxScale) {
54
+ this.minScale = minScale;
55
+ this.maxScale = maxScale;
56
+ this.lastDispatchedScale = minScale;
57
+ }
58
+
59
+ public void setMaxScale(float maxScale) {
60
+ this.maxScale = maxScale;
61
+ }
62
+
63
+ /**
64
+ * @return the last value accepted by {@link #shouldDispatch(float)}, already clamped.
65
+ */
66
+ public float getScale() {
67
+ return lastDispatchedScale;
68
+ }
69
+
70
+ /**
71
+ * @param rawScale the scale read from the view matrix.
72
+ * @return true when the clamped scale differs meaningfully from the last accepted
73
+ * one, in which case it becomes the new last accepted value.
74
+ */
75
+ public boolean shouldDispatch(float rawScale) {
76
+ var clamped = Math.min(Math.max(rawScale, minScale), maxScale);
77
+ if (clamped == lastDispatchedScale) return false;
78
+
79
+ /*
80
+ * The limits themselves always go through, even when the step into them is
81
+ * smaller than the epsilon, so JavaScript ends a gesture holding the exact
82
+ * min/max rather than a value just short of it.
83
+ */
84
+ var isLimit = clamped == minScale || clamped == maxScale;
85
+ if (!isLimit && Math.abs(clamped - lastDispatchedScale) < SCALE_EPSILON) return false;
86
+
87
+ lastDispatchedScale = clamped;
88
+ return true;
89
+ }
90
+ }
@@ -33,9 +33,11 @@ import com.facebook.react.module.annotations.ReactModule;
33
33
  import com.facebook.react.uimanager.SimpleViewManager;
34
34
  import com.facebook.react.uimanager.ThemedReactContext;
35
35
  import com.facebook.react.uimanager.UIManagerHelper;
36
+ import com.facebook.react.uimanager.ViewManagerDelegate;
36
37
  import com.facebook.react.uimanager.annotations.ReactProp;
37
38
  import com.facebook.react.uimanager.events.Event;
38
39
  import com.facebook.react.uimanager.events.EventDispatcher;
40
+ import com.facebook.react.viewmanagers.RNPdfRendererViewManagerDelegate;
39
41
  import com.facebook.react.viewmanagers.RNPdfRendererViewManagerInterface;
40
42
  import com.github.douglasjunior.reactNativePdfRenderer.PdfRendererViewManagerImpl;
41
43
 
@@ -45,9 +47,17 @@ import java.util.Map;
45
47
  public class PdfRendererViewManager extends SimpleViewManager<PdfRendererRecyclerView> implements RNPdfRendererViewManagerInterface<PdfRendererRecyclerView>, PdfRendererRecyclerView.PdfRendererRecyclerViewListener {
46
48
 
47
49
  private final ReactApplicationContext mReactApplicationContext;
50
+ private final ViewManagerDelegate<PdfRendererRecyclerView> mDelegate;
48
51
 
49
52
  public PdfRendererViewManager(ReactApplicationContext reactApplicationContext) {
50
53
  this.mReactApplicationContext = reactApplicationContext;
54
+ this.mDelegate = new RNPdfRendererViewManagerDelegate<>(this);
55
+ }
56
+
57
+ @Nullable
58
+ @Override
59
+ protected ViewManagerDelegate<PdfRendererRecyclerView> getDelegate() {
60
+ return mDelegate;
51
61
  }
52
62
 
53
63
  @NonNull
@@ -90,6 +100,15 @@ public class PdfRendererViewManager extends SimpleViewManager<PdfRendererRecycle
90
100
  );
91
101
  }
92
102
 
103
+ @Override
104
+ public void onScaleChange(PdfRendererRecyclerView target, float scale) {
105
+ int surfaceId = UIManagerHelper.getSurfaceId(mReactApplicationContext);
106
+ sendEvent(
107
+ target,
108
+ PdfRendererViewManagerImpl.createOnScaleChangeEvent(surfaceId, target.getId(), scale)
109
+ );
110
+ }
111
+
93
112
  private void onError(PdfRendererRecyclerView target) {
94
113
  int surfaceId = UIManagerHelper.getSurfaceId(mReactApplicationContext);
95
114
  sendEvent(
@@ -103,4 +103,12 @@ public class PdfRendererViewManager extends SimpleViewManager<PdfRendererRecycle
103
103
  PdfRendererViewManagerImpl.createOnPageChangeEvent(surfaceId, target.getId(), position, total)
104
104
  );
105
105
  }
106
+
107
+ @Override
108
+ public void onScaleChange(PdfRendererRecyclerView target, float scale) {
109
+ int surfaceId = UIManagerHelper.getSurfaceId(target);
110
+ sendEvent(
111
+ PdfRendererViewManagerImpl.createOnScaleChangeEvent(surfaceId, target.getId(), scale)
112
+ );
113
+ }
106
114
  }
@@ -50,10 +50,23 @@ export type PdfRendererViewPropsType = {
50
50
  * @param totalPages total pages number
51
51
  */
52
52
  onPageChange?: (page: number, totalPages: number) => void;
53
+ /**
54
+ * (Android only)
55
+ *
56
+ * Invoked when the zoom scale changes, continuously while the pinch gesture
57
+ * is in progress.
58
+ *
59
+ * `1` is the unzoomed baseline: the page at its laid-out size, which is
60
+ * fit-to-width in multi-page mode and fit-to-center when `singlePage` is set.
61
+ * The value never exceeds `maxZoom`.
62
+ *
63
+ * @param scale current zoom scale
64
+ */
65
+ onScaleChange?: (scale: number) => void;
53
66
  /**
54
67
  * Invoked when an error occurs.
55
68
  */
56
69
  onError?: () => void;
57
70
  };
58
- declare const PdfRendererView: ({ testID, onPageChange, onError, style, source, singlePage, distanceBetweenPages, maxZoom, maxPageResolution, }: PdfRendererViewPropsType) => React.JSX.Element;
71
+ declare const PdfRendererView: ({ testID, onPageChange, onScaleChange, onError, style, source, singlePage, distanceBetweenPages, maxZoom, maxPageResolution, }: PdfRendererViewPropsType) => React.JSX.Element;
59
72
  export default PdfRendererView;
@@ -24,7 +24,7 @@ const styles = StyleSheet.create({
24
24
  flex: 1,
25
25
  },
26
26
  });
27
- const PdfRendererView = ({ testID = undefined, onPageChange, onError = undefined, style, source, singlePage = false, distanceBetweenPages = 16, maxZoom = 5, maxPageResolution = 2048, }) => {
27
+ const PdfRendererView = ({ testID = undefined, onPageChange, onScaleChange, onError = undefined, style, source, singlePage = false, distanceBetweenPages = 16, maxZoom = 5, maxPageResolution = 2048, }) => {
28
28
  const viewStyles = useMemo(() => [
29
29
  styles.default,
30
30
  style,
@@ -36,6 +36,9 @@ const PdfRendererView = ({ testID = undefined, onPageChange, onError = undefined
36
36
  const handlePageChange = useCallback((event) => {
37
37
  onPageChange?.(event.nativeEvent.position, event.nativeEvent.total);
38
38
  }, [onPageChange]);
39
+ const handleScaleChange = useCallback((event) => {
40
+ onScaleChange?.(event.nativeEvent.scale);
41
+ }, [onScaleChange]);
39
42
  const handleError = useCallback((event) => {
40
43
  if (!onError && __DEV__) {
41
44
  console.warn('react-native-pdf-renderer: An error occurred while rendering the PDF.', event.nativeEvent);
@@ -48,7 +51,7 @@ const PdfRendererView = ({ testID = undefined, onPageChange, onError = undefined
48
51
  singlePage,
49
52
  maxZoom,
50
53
  }), [source, singlePage, maxZoom]);
51
- return (React.createElement(PdfRendererNative, { testID: testID, maxPageResolution: maxPageResolution, distanceBetweenPages: distanceBetweenPages, style: viewStyles, params: params, onPageChange: handlePageChange, onError: handleError,
54
+ return (React.createElement(PdfRendererNative, { testID: testID, maxPageResolution: maxPageResolution, distanceBetweenPages: distanceBetweenPages, style: viewStyles, params: params, onPageChange: handlePageChange, onScaleChange: handleScaleChange, onError: handleError,
52
55
  // old architecture events for iOS, because iOS require unique names
53
56
  // @ts-ignore
54
57
  onRnPdfPageChange: handlePageChange, onRnPdfError: handleError }));
@@ -1 +1 @@
1
- {"version":3,"file":"PdfRendererView.js","sourceRoot":"","sources":["../src/PdfRendererView.tsx"],"names":[],"mappings":"AAAA,cAAc;AAEd,gDAAgD;AAEhD,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAE3D,iFAAiF;AACjF,kDAAkD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,CAC9B,CAAC;IAEF,OAAO,CACL,oBAAC,iBAAiB,IAChB,MAAM,EAAE,MAAM,EACd,iBAAiB,EAAE,iBAAiB,EACpC,oBAAoB,EAAE,oBAAoB,EAC1C,KAAK,EAAE,UAAU,EACjB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,gBAAgB,EAC9B,aAAa,EAAE,iBAAiB,EAChC,OAAO,EAAE,WAAW;QACpB,oEAAoE;QACpE,aAAa;QACb,iBAAiB,EAAE,gBAAgB,EACnC,YAAY,EAAE,WAAW,GACzB,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,eAAe,CAAC"}
@@ -1,20 +1,23 @@
1
- import type { HostComponent, ViewProps } from 'react-native';
2
- import { BubblingEventHandler, Float, Int32 } from 'react-native/Libraries/Types/CodegenTypes';
1
+ import type { CodegenTypes, HostComponent, ViewProps } from 'react-native';
3
2
  export type NativeParams = {
4
3
  source?: string;
5
4
  singlePage: boolean;
6
- maxZoom: Float;
5
+ maxZoom: CodegenTypes.Float;
7
6
  };
8
7
  type PageChangeEventPayload = {
9
- position: Int32;
10
- total: Int32;
8
+ position: CodegenTypes.Int32;
9
+ total: CodegenTypes.Int32;
10
+ };
11
+ type ScaleChangeEventPayload = {
12
+ scale: CodegenTypes.Float;
11
13
  };
12
14
  export interface NativeProps extends ViewProps {
13
- maxPageResolution: Float;
14
- distanceBetweenPages: Float;
15
+ maxPageResolution: CodegenTypes.Float;
16
+ distanceBetweenPages: CodegenTypes.Float;
15
17
  params: NativeParams;
16
- onPageChange: BubblingEventHandler<PageChangeEventPayload>;
17
- onError: BubblingEventHandler<{}>;
18
+ onPageChange: CodegenTypes.BubblingEventHandler<PageChangeEventPayload>;
19
+ onScaleChange: CodegenTypes.BubblingEventHandler<ScaleChangeEventPayload>;
20
+ onError: CodegenTypes.BubblingEventHandler<{}>;
18
21
  }
19
22
  declare const _default: HostComponent<NativeProps>;
20
23
  export default _default;
@@ -1,4 +1,4 @@
1
1
  // MIT License
2
- import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
2
+ import { codegenNativeComponent } from 'react-native';
3
3
  export default codegenNativeComponent('RNPdfRendererView');
4
4
  //# sourceMappingURL=RNPdfRendererViewNativeComponent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"RNPdfRendererViewNativeComponent.js","sourceRoot":"","sources":["../../src/specs/RNPdfRendererViewNativeComponent.ts"],"names":[],"mappings":"AAAA,cAAc;AA4Bd,OAAO,sBAAsB,MAAM,yDAAyD,CAAC;AAqB7F,eAAe,sBAAsB,CACnC,mBAAmB,CACU,CAAC"}
1
+ {"version":3,"file":"RNPdfRendererViewNativeComponent.js","sourceRoot":"","sources":["../../src/specs/RNPdfRendererViewNativeComponent.ts"],"names":[],"mappings":"AAAA,cAAc;AAuBd,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AA0BtD,eAAe,sBAAsB,CACnC,mBAAmB,CACU,CAAC"}
@@ -41,19 +41,18 @@ using namespace facebook::react;
41
41
  RNPDFView * _pdfView;
42
42
  }
43
43
 
44
- BOOL observerAdded = NO;
45
-
46
- -(instancetype)init
44
+ - (instancetype)initWithFrame:(CGRect)frame
47
45
  {
48
- if (!observerAdded) {
49
- observerAdded = YES;
50
- [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handlePageChange:) name:PDFViewPageChangedNotification object:nil];
51
- [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handleError:) name:RNPDFViewErrorNotification object:nil];
52
- }
53
- if(self = [super init]) {
46
+ if (self = [super initWithFrame:frame]) {
47
+ static const auto defaultProps = std::make_shared<const RNPdfRendererViewProps>();
48
+ _props = defaultProps;
49
+
54
50
  _pdfView = [RNPDFView new];
55
51
  _pdfView.backgroundColor = UIColor.clearColor;
56
52
  [self addSubview:_pdfView];
53
+
54
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handlePageChange:) name:PDFViewPageChangedNotification object:_pdfView];
55
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handleError:) name:RNPDFViewErrorNotification object:_pdfView];
57
56
  }
58
57
  return self;
59
58
  }
@@ -68,10 +67,7 @@ BOOL observerAdded = NO;
68
67
 
69
68
  - (void)dealloc
70
69
  {
71
- if (observerAdded) {
72
- observerAdded = NO;
73
- [NSNotificationCenter.defaultCenter removeObserver:self name:PDFViewPageChangedNotification object:nil];
74
- }
70
+ [NSNotificationCenter.defaultCenter removeObserver:self];
75
71
  }
76
72
 
77
73
  - (void) handleError:(NSNotification*) notification {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "react-native-pdf-renderer",
3
3
  "displayName": "React-Native Pdf Renderer",
4
- "version": "2.3.0",
4
+ "version": "3.0.0",
5
5
  "description": "⚛ A zoomable, blazing fast, zero dependencies, pure native, typed PDF Renderer for Android and iOS.",
6
6
  "main": "dist",
7
7
  "react-native": "src",
@@ -44,36 +44,26 @@
44
44
  }
45
45
  },
46
46
  "scripts": {
47
- "build": "tsc",
48
- "publish-script": "node scripts/publish.js"
47
+ "build": "tsc"
49
48
  },
50
49
  "peerDependencies": {
51
- "react-native": ">=0.71"
50
+ "react-native": ">=0.80"
52
51
  },
53
52
  "devDependencies": {
54
- "react": "19.0.0",
55
- "react-native": "0.79.4",
56
53
  "@babel/core": "^7.25.2",
57
- "@babel/preset-env": "^7.25.3",
58
- "@babel/runtime": "^7.25.0",
59
- "@react-native-community/cli": "18.0.0",
60
- "@react-native-community/cli-platform-android": "18.0.0",
61
- "@react-native-community/cli-platform-ios": "18.0.0",
62
- "@react-native/babel-preset": "0.79.4",
63
- "@react-native/eslint-config": "0.79.4",
64
- "@react-native/metro-config": "0.79.4",
65
- "@react-native/typescript-config": "0.79.4",
66
- "@types/jest": "^29.5.13",
67
- "@types/react": "^19.0.0",
68
- "@types/react-test-renderer": "^19.0.0",
54
+ "@react-native/babel-preset": "0.88.1",
55
+ "@react-native/eslint-config": "0.88.1",
56
+ "@react-native/typescript-config": "0.88.1",
57
+ "@types/react": "^19.2.0",
69
58
  "eslint": "^8.19.0",
70
- "jest": "^29.6.3",
71
59
  "prettier": "2.8.8",
72
- "react-test-renderer": "19.0.0",
73
- "typescript": "~5.8.3"
60
+ "react": "19.3.0",
61
+ "react-native": "0.88.1",
62
+ "typescript": "^6.0.3"
74
63
  },
75
64
  "engines": {
76
- "node": ">=18"
65
+ "node": ">= 22.11.0"
77
66
  },
67
+ "packageManager": "yarn@1.22.22",
78
68
  "types": "dist"
79
69
  }
@@ -80,6 +80,19 @@ export type PdfRendererViewPropsType = {
80
80
  * @param totalPages total pages number
81
81
  */
82
82
  onPageChange?: (page: number, totalPages: number) => void;
83
+ /**
84
+ * (Android only)
85
+ *
86
+ * Invoked when the zoom scale changes, continuously while the pinch gesture
87
+ * is in progress.
88
+ *
89
+ * `1` is the unzoomed baseline: the page at its laid-out size, which is
90
+ * fit-to-width in multi-page mode and fit-to-center when `singlePage` is set.
91
+ * The value never exceeds `maxZoom`.
92
+ *
93
+ * @param scale current zoom scale
94
+ */
95
+ onScaleChange?: (scale: number) => void;
83
96
  /**
84
97
  * Invoked when an error occurs.
85
98
  */
@@ -91,6 +104,10 @@ type OnPageChangeEventType = {
91
104
  total: number;
92
105
  };
93
106
 
107
+ type OnScaleChangeEventType = {
108
+ scale: number;
109
+ };
110
+
94
111
  const styles = StyleSheet.create({
95
112
  default: {
96
113
  backgroundColor: 'gray',
@@ -101,6 +118,7 @@ const styles = StyleSheet.create({
101
118
  const PdfRendererView = ({
102
119
  testID = undefined,
103
120
  onPageChange,
121
+ onScaleChange,
104
122
  onError = undefined,
105
123
  style,
106
124
  source,
@@ -128,6 +146,13 @@ const PdfRendererView = ({
128
146
  [onPageChange],
129
147
  );
130
148
 
149
+ const handleScaleChange = useCallback(
150
+ (event: NativeSyntheticEvent<OnScaleChangeEventType>) => {
151
+ onScaleChange?.(event.nativeEvent.scale);
152
+ },
153
+ [onScaleChange],
154
+ );
155
+
131
156
  const handleError = useCallback((event: NativeSyntheticEvent<{}>) => {
132
157
  if (!onError && __DEV__) {
133
158
  console.warn(
@@ -156,6 +181,7 @@ const PdfRendererView = ({
156
181
  style={viewStyles}
157
182
  params={params}
158
183
  onPageChange={handlePageChange}
184
+ onScaleChange={handleScaleChange}
159
185
  onError={handleError}
160
186
  // old architecture events for iOS, because iOS require unique names
161
187
  // @ts-ignore
@@ -20,31 +20,31 @@
20
20
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  // SOFTWARE.
22
22
 
23
- import type { HostComponent, ViewProps } from 'react-native';
24
- import {
25
- BubblingEventHandler,
26
- Float,
27
- Int32,
28
- } from 'react-native/Libraries/Types/CodegenTypes';
29
- import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
23
+ import type { CodegenTypes, HostComponent, ViewProps } from 'react-native';
24
+ import { codegenNativeComponent } from 'react-native';
30
25
 
31
26
  export type NativeParams = {
32
27
  source?: string;
33
28
  singlePage: boolean;
34
- maxZoom: Float;
29
+ maxZoom: CodegenTypes.Float;
35
30
  };
36
31
 
37
32
  type PageChangeEventPayload = {
38
- position: Int32;
39
- total: Int32;
33
+ position: CodegenTypes.Int32;
34
+ total: CodegenTypes.Int32;
35
+ };
36
+
37
+ type ScaleChangeEventPayload = {
38
+ scale: CodegenTypes.Float;
40
39
  };
41
40
 
42
41
  export interface NativeProps extends ViewProps {
43
- maxPageResolution: Float;
44
- distanceBetweenPages: Float;
42
+ maxPageResolution: CodegenTypes.Float;
43
+ distanceBetweenPages: CodegenTypes.Float;
45
44
  params: NativeParams;
46
- onPageChange: BubblingEventHandler<PageChangeEventPayload>;
47
- onError: BubblingEventHandler<{}>;
45
+ onPageChange: CodegenTypes.BubblingEventHandler<PageChangeEventPayload>;
46
+ onScaleChange: CodegenTypes.BubblingEventHandler<ScaleChangeEventPayload>;
47
+ onError: CodegenTypes.BubblingEventHandler<{}>;
48
48
  }
49
49
 
50
50
  export default codegenNativeComponent<NativeProps>(
package/.eslintignore DELETED
@@ -1,2 +0,0 @@
1
- /dist
2
- /node_modules
package/.gitattributes DELETED
@@ -1,2 +0,0 @@
1
- *.pbxproj -text
2
- Sample/** linguist-vendored