react-native-pdf-renderer 1.5.0 → 1.6.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
@@ -39,6 +39,21 @@ npm i -S react-native-pdf-renderer
39
39
 
40
40
  Go to the folder **your-project/ios** and run `pod install`, and you're done.
41
41
 
42
+ ### Android specific (optional)
43
+
44
+ Customize the [`androidx.recyclerview:recyclerview`](https://developer.android.com/jetpack/androidx/releases/recyclerview) version by setting `ext` in your `android/build.gradle` file.
45
+
46
+ Example:
47
+
48
+ ```gradle
49
+ buildscript {
50
+ ext {
51
+ recyclerviewVersion = "1.2.1"
52
+ }
53
+ ...
54
+ }
55
+ ```
56
+
42
57
  ## Basic usage
43
58
 
44
59
  There is only one component that you need to use to render the PDF file.
@@ -47,19 +62,19 @@ There is only one component that you need to use to render the PDF file.
47
62
  import PdfRendererView from 'react-native-pdf-renderer';
48
63
 
49
64
  const App = () => {
50
- return (
51
- <SafeAreaView style={{flex: 1}}>
52
- <PdfRendererView
53
- style={{backgroundColor: 'red'}}
54
- source="file:///path/to/local/file.pdf"
55
- distanceBetweenPages={16}
56
- maxZoom={5}
57
- onPageChange={(current, total) => {
58
- console.log(current, total);
59
- }}
60
- />
61
- </SafeAreaView>
62
- );
65
+ return (
66
+ <SafeAreaView style={{flex: 1}}>
67
+ <PdfRendererView
68
+ style={{backgroundColor: 'red'}}
69
+ source="file:///path/to/local/file.pdf"
70
+ distanceBetweenPages={16}
71
+ maxZoom={5}
72
+ onPageChange={(current, total) => {
73
+ console.log(current, total);
74
+ }}
75
+ />
76
+ </SafeAreaView>
77
+ );
63
78
  }
64
79
 
65
80
  export default App;
@@ -103,9 +118,9 @@ If you need `borderRadius`, the best option is to wrap the `PdfRendererView` in
103
118
 
104
119
  ```jsx
105
120
  <View style={{ flex: 1, borderRadius: 24, overflow: 'hidden' }}>
106
- <PdfRendererView
107
- // ...
108
- />
121
+ <PdfRendererView
122
+ // ...
123
+ />
109
124
  </View>
110
125
  ```
111
126
 
@@ -1,20 +1,56 @@
1
+ def safeAppExtGet(prop, fallback) {
2
+ def appProject = rootProject.allprojects.find { it.plugins.hasPlugin('com.android.application') }
3
+ appProject?.ext?.has(prop) ? appProject.ext.get(prop) : fallback
4
+ }
5
+
6
+ def resolveReactNativeDirectory() {
7
+ def reactNativeLocation = safeAppExtGet("REACT_NATIVE_NODE_MODULES_DIR", null)
8
+ if (reactNativeLocation != null) {
9
+ return file(reactNativeLocation)
10
+ }
11
+
12
+ // monorepo workaround
13
+ // react-native can be hoisted or in project's own node_modules
14
+ def reactNativeFromProjectNodeModules = file("${rootProject.projectDir}/../node_modules/react-native")
15
+ if (reactNativeFromProjectNodeModules.exists()) {
16
+ return reactNativeFromProjectNodeModules
17
+ }
18
+
19
+ def reactNativeFromNodeModulesWithReanimated = file("${projectDir}/../../react-native")
20
+ if (reactNativeFromNodeModulesWithReanimated.exists()) {
21
+ return reactNativeFromNodeModulesWithReanimated
22
+ }
23
+
24
+ throw new GradleException(
25
+ "Unable to resolve react-native location in node_modules. You should project extension property (in `app/build.gradle`) `REACT_NATIVE_NODE_MODULES_DIR` with path to react-native."
26
+ )
27
+ }
28
+
29
+ def reactNativeRootDir = resolveReactNativeDirectory()
30
+
31
+ def reactProperties = new Properties()
32
+ file("$reactNativeRootDir/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }
33
+
34
+ def REACT_NATIVE_VERSION = reactProperties.getProperty("VERSION_NAME")
35
+ def REACT_NATIVE_MINOR_VERSION = REACT_NATIVE_VERSION.startsWith("0.0.0-") ? 1000 : REACT_NATIVE_VERSION.split("\\.")[1].toInteger()
36
+
1
37
  buildscript {
2
- ext.safeExtGet = {prop, fallback ->
38
+ ext.safeExtGet = { prop, fallback ->
3
39
  rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
4
40
  }
41
+ ext.IS_ROOT = project == rootProject
5
42
 
6
43
  // The Android Gradle plugin is only required when opening the android folder stand-alone.
7
44
  // This avoids unnecessary downloads and potential conflicts when the library is included as a
8
45
  // module dependency in an application project.
9
- if (project == rootProject) {
46
+
47
+ if (IS_ROOT) {
10
48
  repositories {
11
49
  google()
12
50
  mavenCentral()
13
51
  }
14
-
15
52
  dependencies {
16
- //noinspection GradleDependency
17
- classpath("com.android.tools.build:gradle:4.2.2")
53
+ classpath "com.android.tools.build:gradle:7.3.1"
18
54
  }
19
55
  }
20
56
  }
@@ -22,14 +58,12 @@ buildscript {
22
58
  apply plugin: 'com.android.library'
23
59
 
24
60
  android {
25
- compileSdkVersion safeExtGet('compileSdkVersion', 30)
26
- //noinspection GradleDependency
27
- buildToolsVersion safeExtGet('buildToolsVersion', '30.0.2')
28
-
61
+ namespace "com.github.douglasjunior.reactNativePdfRenderer"
62
+ compileSdkVersion safeExtGet("compileSdkVersion", 33)
29
63
  defaultConfig {
30
64
  minSdkVersion safeExtGet('minSdkVersion', 21)
31
65
  //noinspection OldTargetApi
32
- targetSdkVersion safeExtGet('targetSdkVersion', 30)
66
+ targetSdkVersion safeExtGet('targetSdkVersion', 33)
33
67
  }
34
68
  lintOptions {
35
69
  abortOnError false
@@ -37,26 +71,29 @@ android {
37
71
  }
38
72
 
39
73
  repositories {
40
- repositories {
41
- mavenCentral()
42
- mavenLocal()
74
+ mavenCentral()
75
+ mavenLocal()
76
+ if (REACT_NATIVE_MINOR_VERSION < 71) {
43
77
  maven {
44
78
  // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
45
- url("$rootDir/../node_modules/react-native/android")
79
+ url "$reactNativeRootDir/android"
46
80
  }
47
81
  maven {
48
82
  // Android JSC is installed from npm
49
- url("$rootDir/../node_modules/jsc-android/dist")
83
+ url "$reactNativeRootDir/../jsc-android/dist"
50
84
  }
51
-
52
- google()
53
- maven { url 'https://www.jitpack.io' }
54
85
  }
86
+ google()
55
87
  }
56
88
 
57
89
  dependencies {
58
- //noinspection GradleDynamicVersion
59
- implementation "com.facebook.react:react-native:${safeExtGet('reactNativeVersion', '+')}"
90
+ if (REACT_NATIVE_MINOR_VERSION >= 71) {
91
+ implementation "com.facebook.react:react-android${IS_ROOT ? ':+' : ''}"
92
+ // version substituted by RNGP
93
+ } else {
94
+ // noinspection GradleDynamicVersion
95
+ implementation "com.facebook.react:react-native:+" // From node_modules
96
+ }
60
97
 
61
98
  implementation "androidx.recyclerview:recyclerview:${safeExtGet('recyclerViewVersion', '1.2.1')}"
62
99
  }
@@ -0,0 +1,3 @@
1
+ <manifest>
2
+
3
+ </manifest>
@@ -0,0 +1,50 @@
1
+ // MIT License
2
+
3
+ // Copyright (c) 2023 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;
24
+
25
+ import androidx.annotation.NonNull;
26
+
27
+ import com.facebook.react.ReactPackage;
28
+ import com.facebook.react.bridge.NativeModule;
29
+ import com.facebook.react.bridge.ReactApplicationContext;
30
+ import com.facebook.react.uimanager.ViewManager;
31
+ import com.github.douglasjunior.reactNativePdfRenderer.modules.PdfRendererViewManager;
32
+
33
+ import java.util.Collections;
34
+ import java.util.List;
35
+
36
+ public class PdfRendererPackage implements ReactPackage {
37
+ @NonNull
38
+ @Override
39
+ public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactApplicationContext) {
40
+ return Collections.emptyList();
41
+ }
42
+
43
+ @NonNull
44
+ @Override
45
+ public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactApplicationContext) {
46
+ return Collections.singletonList(
47
+ new PdfRendererViewManager(reactApplicationContext)
48
+ );
49
+ }
50
+ }
@@ -0,0 +1,63 @@
1
+ // MIT License
2
+
3
+ // Copyright (c) 2023 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
+ import java.util.HashSet;
26
+ import java.util.Set;
27
+
28
+ public class ObservableZoom {
29
+ private final Set<ZoomChangeListener> listeners = new HashSet<>();
30
+ private float zoom;
31
+
32
+ public ObservableZoom(int initialZoom) {
33
+ this.zoom = initialZoom;
34
+ }
35
+
36
+ public void addListener(ZoomChangeListener listener) {
37
+ this.listeners.add(listener);
38
+ }
39
+
40
+ public void removeListener(ZoomChangeListener zoomListener) {
41
+ this.listeners.remove(zoomListener);
42
+ }
43
+
44
+ private void notifyListeners() {
45
+ for (ZoomChangeListener listener : listeners) {
46
+ listener.onZoomChange(this.zoom);
47
+ }
48
+ }
49
+
50
+ public float getZoom() {
51
+ return zoom;
52
+ }
53
+
54
+ public void setZoom(float newZoom) {
55
+ if (newZoom == this.zoom) return;
56
+ this.zoom = newZoom;
57
+ notifyListeners();
58
+ }
59
+
60
+ public interface ZoomChangeListener {
61
+ void onZoomChange(float newZoom);
62
+ }
63
+ }
@@ -0,0 +1,514 @@
1
+ // MIT License
2
+
3
+ // Copyright (c) 2023 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
+ import android.annotation.SuppressLint;
26
+ import android.content.Context;
27
+ import android.content.res.Resources;
28
+ import android.graphics.Bitmap;
29
+ import android.graphics.Canvas;
30
+ import android.graphics.Color;
31
+ import android.graphics.Matrix;
32
+ import android.graphics.pdf.PdfRenderer;
33
+ import android.os.ParcelFileDescriptor;
34
+ import android.text.TextUtils;
35
+ import android.util.Log;
36
+ import android.util.TypedValue;
37
+ import android.view.GestureDetector;
38
+ import android.view.MotionEvent;
39
+ import android.view.ScaleGestureDetector;
40
+ import android.view.ViewGroup;
41
+ import android.widget.ImageView;
42
+
43
+ import androidx.annotation.NonNull;
44
+ import androidx.core.view.ViewCompat;
45
+ import androidx.recyclerview.widget.LinearLayoutManager;
46
+ import androidx.recyclerview.widget.RecyclerView;
47
+
48
+ import com.facebook.react.bridge.Arguments;
49
+ import com.facebook.react.bridge.ReactApplicationContext;
50
+ import com.facebook.react.uimanager.events.RCTEventEmitter;
51
+
52
+ import java.io.File;
53
+ import java.io.IOException;
54
+
55
+ @SuppressLint({"ViewConstructor", "NotifyDataSetChanged"})
56
+ public class PdfRendererRecyclerView extends RecyclerView {
57
+ private final ViewGroup mParent;
58
+ private final GestureDetector mGestureDetector;
59
+ private final int mMinZoom = 1;
60
+ private final ReactApplicationContext mReactApplicationContext;
61
+ private final ScaleGestureDetector mScaleDetector;
62
+ private final Matrix mMatrix;
63
+ private final ObservableZoom mZoomObserver;
64
+ private final LayoutManager mLayoutManager;
65
+ private boolean mRequestedLayout = false;
66
+ private float mMaxZoom = 5;
67
+ private float mMaxPageResolution;
68
+ private float mDistanceBetweenPages = 0;
69
+ private int mWidth;
70
+ private int mHeight;
71
+ private int mCurrentItemPosition = -1;
72
+ private boolean mSinglePage;
73
+
74
+ public PdfRendererRecyclerView(@NonNull ReactApplicationContext context, ViewGroup parent) {
75
+ super(context);
76
+
77
+ mZoomObserver = new ObservableZoom(mMinZoom);
78
+
79
+ mLayoutManager = new LayoutManager(context);
80
+ mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
81
+
82
+ var adapter = new PdfRendererAdapter();
83
+
84
+ this.setLayoutManager(mLayoutManager);
85
+ this.setAdapter(adapter);
86
+ this.addOnScrollListener(new OnScrollListener() {
87
+ @Override
88
+ public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
89
+ dispatchPageChangeEvent();
90
+ }
91
+ });
92
+
93
+ mReactApplicationContext = context;
94
+ mParent = parent;
95
+ mMatrix = new Matrix();
96
+ mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
97
+ mGestureDetector = new GestureDetector(context, new GestureListener());
98
+ }
99
+
100
+ public void setDistanceBetweenPages(float distanceBetweenPages) {
101
+ mDistanceBetweenPages = TypedValue.applyDimension(
102
+ TypedValue.COMPLEX_UNIT_DIP,
103
+ distanceBetweenPages,
104
+ Resources.getSystem().getDisplayMetrics()
105
+ );
106
+ }
107
+
108
+ public void setMaxPageResolution(float maxPageResolution) {
109
+ this.mMaxPageResolution = maxPageResolution;
110
+ }
111
+
112
+ public void setMaxZoom(float maxZoom) {
113
+ this.mMaxZoom = maxZoom;
114
+ }
115
+
116
+ public void closeAdapter() {
117
+ try {
118
+ var adapter = (PdfRendererAdapter) getAdapter();
119
+ assert adapter != null;
120
+ adapter.close();
121
+ adapter.notifyDataSetChanged();
122
+ } catch (Exception ex) {
123
+ Log.e("PdfRendererRecyclerView", "Error closing adapter", ex);
124
+ }
125
+ }
126
+
127
+ public void updateSource(String source) throws IOException {
128
+ mCurrentItemPosition = -1;
129
+ var adapter = (PdfRendererAdapter) getAdapter();
130
+ if (adapter == null) return;
131
+ adapter.close();
132
+ adapter.updateSource(source);
133
+ adapter.notifyDataSetChanged();
134
+ post(this::dispatchPageChangeEvent);
135
+ }
136
+
137
+ private void dispatchPageChangeEvent() {
138
+ var newPosition = mLayoutManager.findLastCompletelyVisibleItemPosition();
139
+ if (newPosition < 0) newPosition = mLayoutManager.findLastVisibleItemPosition();
140
+
141
+ if (newPosition != mCurrentItemPosition) {
142
+ mCurrentItemPosition = newPosition;
143
+
144
+ var adapter = (PdfRendererAdapter) getAdapter();
145
+ if (adapter == null) return;
146
+
147
+ var event = Arguments.createMap();
148
+ event.putInt("position", newPosition);
149
+ event.putInt("total", adapter.getPageCount());
150
+
151
+ mReactApplicationContext
152
+ .getJSModule(RCTEventEmitter.class)
153
+ .receiveEvent(mParent.getId(), "pageChange", event);
154
+ }
155
+ }
156
+
157
+ @Override
158
+ protected void dispatchDraw(@NonNull Canvas canvas) {
159
+ canvas.save();
160
+ canvas.concat(mMatrix);
161
+ try {
162
+ super.dispatchDraw(canvas);
163
+ } catch (Exception ex) {
164
+ Log.e("PdfRendererRecyclerView", "Error dispatching draw", ex);
165
+ }
166
+ canvas.restore();
167
+ }
168
+
169
+ @Override
170
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
171
+ mWidth = MeasureSpec.getSize(widthMeasureSpec);
172
+ mHeight = MeasureSpec.getSize(heightMeasureSpec);
173
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec);
174
+ }
175
+
176
+ @Override
177
+ protected void onSizeChanged(int w, int h, int oldw, int oldh) {
178
+ super.onSizeChanged(w, h, oldw, oldh);
179
+ var scale = mWidth > 0 && mHeight > 0
180
+ ? Math.max(w / mWidth, h / mHeight)
181
+ : 1;
182
+ mMatrix.setScale(scale, scale);
183
+ mMatrix.postTranslate((w - scale * mWidth) / 2f, (h - scale * mHeight) / 2f);
184
+ }
185
+
186
+ private boolean isScrollingInsideZoomedArea() {
187
+ var values = new float[9];
188
+ mMatrix.getValues(values);
189
+
190
+ var scaleY = Math.min(Math.max(values[Matrix.MSCALE_Y], mMinZoom), mMaxZoom);
191
+ var posY = values[Matrix.MTRANS_Y];
192
+
193
+ var maxPosY = mHeight - mHeight * scaleY;
194
+
195
+ return posY < 0 && posY > maxPosY;
196
+ }
197
+
198
+ @Override
199
+ @SuppressLint("ClickableViewAccessibility")
200
+ public boolean onTouchEvent(MotionEvent e) {
201
+ mScaleDetector.onTouchEvent(e);
202
+ mGestureDetector.onTouchEvent(e);
203
+
204
+ /*
205
+ * Disables the RecyclerView scroll when scrolling inside zoomed area
206
+ * https://github.com/douglasjunior/react-native-pdf-renderer/issues/3
207
+ */
208
+ if (isScrollingInsideZoomedArea()) {
209
+ return true;
210
+ }
211
+
212
+ return super.onTouchEvent(e);
213
+ }
214
+
215
+ @Override
216
+ public boolean onInterceptTouchEvent(MotionEvent ev) {
217
+ try {
218
+ return super.onInterceptTouchEvent(ev);
219
+ } catch (IllegalArgumentException ex) {
220
+ Log.e("PdfRendererRecyclerView", "Error intercepting touch event", ex);
221
+ }
222
+ return false;
223
+ }
224
+
225
+ public void forceRequestLayout() {
226
+ mRequestedLayout = false;
227
+ requestLayout();
228
+ }
229
+
230
+ private void validateMatrixLimits() {
231
+ var values = new float[9];
232
+ mMatrix.getValues(values);
233
+
234
+ var scaleX = Math.min(Math.max(values[Matrix.MSCALE_X], mMinZoom), mMaxZoom);
235
+ var posX = values[Matrix.MTRANS_X];
236
+
237
+ var scaleY = Math.min(Math.max(values[Matrix.MSCALE_Y], mMinZoom), mMaxZoom);
238
+ var posY = values[Matrix.MTRANS_Y];
239
+
240
+ var maxPosX = mWidth - mWidth * scaleX;
241
+ var maxPosY = mHeight - mHeight * scaleY;
242
+
243
+ if (posX > 0.0f)
244
+ posX = 0.0f;
245
+ else if (posX < maxPosX)
246
+ posX = maxPosX;
247
+
248
+ if (posY > 0.0f)
249
+ posY = 0.0f;
250
+ else if (posY < maxPosY)
251
+ posY = maxPosY;
252
+
253
+ values[Matrix.MSCALE_X] = scaleX;
254
+ values[Matrix.MTRANS_X] = posX;
255
+ values[Matrix.MSCALE_Y] = scaleY;
256
+ values[Matrix.MTRANS_Y] = posY;
257
+
258
+ mMatrix.setValues(values);
259
+ }
260
+
261
+ /**
262
+ * Fix a problem with React Native layout
263
+ * https://stackoverflow.com/a/49381907/2826279
264
+ */
265
+ @SuppressLint("WrongCall")
266
+ @Override
267
+ public void requestLayout() {
268
+ super.requestLayout();
269
+ if (!mRequestedLayout) {
270
+ mRequestedLayout = true;
271
+ this.post(() -> {
272
+ onLayout(false, getLeft(), getTop(), getRight(), getBottom());
273
+ });
274
+ }
275
+ }
276
+
277
+ public void setSinglePage(boolean singlePage) {
278
+ this.mSinglePage = singlePage;
279
+ }
280
+
281
+ private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
282
+ @Override
283
+ public boolean onScale(ScaleGestureDetector detector) {
284
+ var values = new float[9];
285
+ mMatrix.getValues(values);
286
+
287
+ var zoom = values[Matrix.MSCALE_X];
288
+ var factor = detector.getScaleFactor();
289
+
290
+ if (zoom >= mMaxZoom && factor > 1) {
291
+ return false;
292
+ }
293
+
294
+ mMatrix.postScale(factor, factor, getWidth() / 2f, getHeight() / 2f);
295
+ validateMatrixLimits();
296
+ ViewCompat.postInvalidateOnAnimation(PdfRendererRecyclerView.this);
297
+
298
+ return true;
299
+ }
300
+
301
+ @Override
302
+ public void onScaleEnd(@NonNull ScaleGestureDetector detector) {
303
+ super.onScaleEnd(detector);
304
+
305
+ var values = new float[9];
306
+ mMatrix.getValues(values);
307
+ var zoom = values[Matrix.MSCALE_X];
308
+
309
+ mZoomObserver.setZoom(zoom);
310
+ }
311
+ }
312
+
313
+ private class GestureListener extends GestureDetector.SimpleOnGestureListener {
314
+ @Override
315
+ public boolean onScroll(MotionEvent e1, MotionEvent e2, float dX, float dY) {
316
+ mMatrix.postTranslate(-dX, -dY);
317
+ validateMatrixLimits();
318
+ ViewCompat.postInvalidateOnAnimation(PdfRendererRecyclerView.this);
319
+ return true;
320
+ }
321
+
322
+ @Override
323
+ public boolean onDoubleTap(@NonNull MotionEvent e) {
324
+ if (e.getPointerCount() > 1) {
325
+ return false;
326
+ }
327
+
328
+ var values = new float[9];
329
+ mMatrix.getValues(values);
330
+
331
+ var currentZoom = values[Matrix.MSCALE_X];
332
+ var newZoom = currentZoom > mMinZoom ? mMinZoom : mMaxZoom;
333
+ var centerX = getWidth() / 2f;
334
+ var centerY = getHeight() / 2f;
335
+
336
+ mMatrix.setScale(newZoom, newZoom, centerX, centerY);
337
+ mMatrix.postTranslate(centerX - e.getX(), centerY - e.getY());
338
+
339
+ validateMatrixLimits();
340
+
341
+ ViewCompat.postInvalidateOnAnimation(PdfRendererRecyclerView.this);
342
+
343
+ mZoomObserver.setZoom(newZoom);
344
+ return true;
345
+ }
346
+ }
347
+
348
+ class PdfRendererAdapter extends Adapter<PdfRendererAdapter.ViewHolder> {
349
+
350
+ private ParcelFileDescriptor mFileDescriptor;
351
+ private PdfRenderer mPdfRenderer;
352
+
353
+ public void updateSource(String source) throws IOException {
354
+ if (TextUtils.isEmpty(source)) return;
355
+ var file = new File(source.replace("file://", ""));
356
+ mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
357
+ mPdfRenderer = new PdfRenderer(mFileDescriptor);
358
+ }
359
+
360
+ public void close() throws IOException {
361
+ if (mPdfRenderer != null) mPdfRenderer.close();
362
+ if (mFileDescriptor != null) mFileDescriptor.close();
363
+ mPdfRenderer = null;
364
+ mFileDescriptor = null;
365
+ }
366
+
367
+ @NonNull
368
+ @Override
369
+ public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
370
+ var imageView = new ImageView(parent.getContext());
371
+ imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
372
+ imageView.setBackgroundColor(Color.WHITE);
373
+ var params = new LayoutParams(LayoutParams.MATCH_PARENT, 0);
374
+ imageView.setLayoutParams(params);
375
+ return new ViewHolder(imageView);
376
+ }
377
+
378
+ @Override
379
+ public void onViewDetachedFromWindow(@NonNull ViewHolder holder) {
380
+ super.onViewDetachedFromWindow(holder);
381
+ holder.detachFromWindow();
382
+ }
383
+
384
+ @Override
385
+ public void onViewAttachedToWindow(@NonNull ViewHolder holder) {
386
+ super.onViewAttachedToWindow(holder);
387
+ holder.attachFromWindow();
388
+ }
389
+
390
+ @Override
391
+ public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
392
+ if (mPdfRenderer == null) return;
393
+ holder.update(position, mZoomObserver.getZoom());
394
+ }
395
+
396
+ @Override
397
+ public int getItemCount() {
398
+ if (mPdfRenderer == null) return 0;
399
+ if (mSinglePage) {
400
+ return Math.min(mPdfRenderer.getPageCount(), 1);
401
+ }
402
+ return mPdfRenderer.getPageCount();
403
+ }
404
+
405
+ public int getPageCount() {
406
+ if (mPdfRenderer == null) return 0;
407
+ return mPdfRenderer.getPageCount();
408
+ }
409
+
410
+ public class ViewHolder extends RecyclerView.ViewHolder {
411
+ private ObservableZoom.ZoomChangeListener zoomListener;
412
+
413
+ public ViewHolder(ImageView imageView) {
414
+ super(imageView);
415
+ }
416
+
417
+ public ImageView getImageView() {
418
+ return (ImageView) this.itemView;
419
+ }
420
+
421
+ private @NonNull Bitmap createBitmap(float newZoom, int pageWidth, int pageHeight) {
422
+ // We need to take account of these points to avoid low quality image on large screen:
423
+ // - target DPI resolution
424
+ // - PDF print default resolution (72dpi)
425
+ // see https://stackoverflow.com/a/32327174/2826279
426
+ var scaledPageWidth = Math.round(getResources().getDisplayMetrics().densityDpi * pageWidth * newZoom / 72);
427
+ var scaledPageHeight = Math.round(getResources().getDisplayMetrics().densityDpi * pageHeight * newZoom / 72);
428
+
429
+ float scalingFactor = Math.min(
430
+ mMaxPageResolution / scaledPageWidth,
431
+ mMaxPageResolution / scaledPageHeight
432
+ );
433
+
434
+ float zoomFactor = Math.min(newZoom, scalingFactor);
435
+
436
+ var bitmap = Bitmap.createBitmap(
437
+ Math.round(scaledPageWidth * zoomFactor),
438
+ Math.round(scaledPageHeight * zoomFactor),
439
+ Bitmap.Config.ARGB_8888
440
+ );
441
+ // Fill the bitmap with white color by default to prevent issues with transparent PDFs
442
+ bitmap.eraseColor(Color.WHITE);
443
+ return bitmap;
444
+ }
445
+
446
+ public void update(int position, float newZoom) {
447
+ var page = mPdfRenderer.openPage(position);
448
+ var pageWidth = page.getWidth();
449
+ var pageHeight = page.getHeight();
450
+ var bitmap = createBitmap(newZoom, pageWidth, pageHeight);
451
+
452
+ page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
453
+
454
+ var imageView = getImageView();
455
+ imageView.setImageBitmap(bitmap);
456
+
457
+ var lp = (LayoutParams) imageView.getLayoutParams();
458
+ lp.width = LayoutParams.MATCH_PARENT;
459
+
460
+ if (mSinglePage) {
461
+ lp.height = LayoutParams.MATCH_PARENT;
462
+ lp.setMargins(0, 0, 0, 0);
463
+ } else {
464
+ lp.height = Math.round(((float) mWidth / (float) pageWidth) * (float) pageHeight);
465
+ lp.setMargins(0, 0, 0, (int) mDistanceBetweenPages);
466
+ }
467
+ imageView.setLayoutParams(lp);
468
+
469
+ page.close();
470
+ }
471
+
472
+ public void detachFromWindow() {
473
+ if (zoomListener != null) {
474
+ mZoomObserver.removeListener(zoomListener);
475
+ zoomListener = null;
476
+ }
477
+ }
478
+
479
+ public void attachFromWindow() {
480
+ detachFromWindow();
481
+ zoomListener = newZoom -> {
482
+ var position = getLayoutPosition();
483
+ if (position == NO_POSITION) return;
484
+ if (position < mLayoutManager.findFirstVisibleItemPosition()
485
+ || position > mLayoutManager.findLastVisibleItemPosition()) return;
486
+ update(position, newZoom);
487
+ };
488
+ mZoomObserver.addListener(zoomListener);
489
+ }
490
+ }
491
+ }
492
+
493
+ class LayoutManager extends LinearLayoutManager {
494
+ public LayoutManager(Context context) {
495
+ super(context);
496
+ }
497
+
498
+ @Override
499
+ public int scrollVerticallyBy(int dy, Recycler recycler, State state) {
500
+ /*
501
+ * Reduces the scroll speed when zoomed
502
+ * https://github.com/douglasjunior/react-native-pdf-renderer/issues/3
503
+ */
504
+
505
+ var values = new float[9];
506
+ mMatrix.getValues(values);
507
+
508
+ var scaleY = values[Matrix.MSCALE_Y];
509
+ var dyWithScale = Math.round(dy / scaleY);
510
+
511
+ return super.scrollVerticallyBy(dyWithScale, recycler, state);
512
+ }
513
+ }
514
+ }
@@ -0,0 +1,118 @@
1
+ // MIT License
2
+
3
+ // Copyright (c) 2023 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
+ import android.view.View;
26
+ import android.view.ViewGroup;
27
+ import android.widget.LinearLayout;
28
+
29
+ import androidx.annotation.NonNull;
30
+ import androidx.annotation.Nullable;
31
+
32
+ import com.facebook.react.bridge.ReactApplicationContext;
33
+ import com.facebook.react.bridge.ReadableMap;
34
+ import com.facebook.react.common.MapBuilder;
35
+ import com.facebook.react.uimanager.SimpleViewManager;
36
+ import com.facebook.react.uimanager.ThemedReactContext;
37
+ import com.facebook.react.uimanager.annotations.ReactProp;
38
+
39
+ import java.io.IOException;
40
+ import java.util.Map;
41
+
42
+ public class PdfRendererViewManager extends SimpleViewManager<ViewGroup> {
43
+ private final ReactApplicationContext mReactApplicationContext;
44
+
45
+ public PdfRendererViewManager(ReactApplicationContext reactApplicationContext) {
46
+ this.mReactApplicationContext = reactApplicationContext;
47
+ }
48
+
49
+ @NonNull
50
+ @Override
51
+ public String getName() {
52
+ return "RNPdfRendererView";
53
+ }
54
+
55
+ @NonNull
56
+ @Override
57
+ protected ViewGroup createViewInstance(@NonNull ThemedReactContext themedReactContext) {
58
+ var layout = new LinearLayout(themedReactContext);
59
+ layout.setOrientation(LinearLayout.VERTICAL);
60
+
61
+ var params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
62
+
63
+ var recyclerView = new PdfRendererRecyclerView(mReactApplicationContext, layout);
64
+ recyclerView.setLayoutParams(params);
65
+
66
+ layout.addView(recyclerView);
67
+ layout.setClipToOutline(true);
68
+
69
+ return layout;
70
+ }
71
+
72
+ @Nullable
73
+ @Override
74
+ public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {
75
+ var map = super.getExportedCustomBubblingEventTypeConstants();
76
+ if (map == null) map = MapBuilder.of();
77
+ map.put("pageChange", MapBuilder.of(
78
+ "phasedRegistrationNames",
79
+ MapBuilder.of("bubbled", "onPageChange")
80
+ ));
81
+ return map;
82
+ }
83
+
84
+ @ReactProp(name = "params")
85
+ public void setParams(ViewGroup layout, @Nullable ReadableMap params) throws IOException {
86
+ if (params == null) return;
87
+
88
+ var recyclerView = (PdfRendererRecyclerView) layout.getChildAt(0);
89
+
90
+ var source = params.getString("source");
91
+ var singlePage = params.hasKey("singlePage") && params.getBoolean("singlePage");
92
+ var maxZoom = params.hasKey("maxZoom") ? Double.valueOf(params.getDouble("maxZoom")).floatValue() : 5;
93
+
94
+ if (source != null) {
95
+ recyclerView.updateSource(source);
96
+ } else {
97
+ recyclerView.closeAdapter();
98
+ }
99
+
100
+ recyclerView.setSinglePage(singlePage);
101
+ recyclerView.setMaxZoom(maxZoom);
102
+ recyclerView.setOverScrollMode(singlePage ? View.OVER_SCROLL_NEVER : View.OVER_SCROLL_IF_CONTENT_SCROLLS);
103
+
104
+ recyclerView.forceRequestLayout();
105
+ }
106
+
107
+ @ReactProp(name = "distanceBetweenPages")
108
+ public void setDistanceBetweenPages(ViewGroup layout, @Nullable float distanceBetweenPages) {
109
+ var recyclerView = (PdfRendererRecyclerView) layout.getChildAt(0);
110
+ recyclerView.setDistanceBetweenPages(distanceBetweenPages);
111
+ }
112
+
113
+ @ReactProp(name = "maxPageResolution")
114
+ public void setMaxPageResolution(ViewGroup layout, @Nullable float maxPageResolution) {
115
+ var recyclerView = (PdfRendererRecyclerView) layout.getChildAt(0);
116
+ recyclerView.setMaxPageResolution(maxPageResolution);
117
+ }
118
+ }
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": "1.5.0",
4
+ "version": "1.6.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
  "license": "MIT",