react-native-pdf 6.6.1 → 6.6.2

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/index.js ADDED
@@ -0,0 +1,466 @@
1
+ /**
2
+ * Copyright (c) 2017-present, Wonday (@wonday.org)
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the MIT-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ 'use strict';
10
+ import React, {Component} from 'react';
11
+ import PropTypes from 'prop-types';
12
+ import {
13
+ requireNativeComponent,
14
+ View,
15
+ Platform,
16
+ StyleSheet,
17
+ Image,
18
+ Text
19
+ } from 'react-native';
20
+
21
+ import ReactNativeBlobUtil from 'react-native-blob-util'
22
+ import {ViewPropTypes} from 'deprecated-react-native-prop-types';
23
+ const SHA1 = require('crypto-js/sha1');
24
+ import PdfView from './PdfView';
25
+
26
+ export default class Pdf extends Component {
27
+
28
+ static propTypes = {
29
+ ...ViewPropTypes,
30
+ source: PropTypes.oneOfType([
31
+ PropTypes.shape({
32
+ uri: PropTypes.string,
33
+ cache: PropTypes.bool,
34
+ cacheFileName: PropTypes.string,
35
+ expiration: PropTypes.number,
36
+ }),
37
+ // Opaque type returned by require('./test.pdf')
38
+ PropTypes.number,
39
+ ]).isRequired,
40
+ page: PropTypes.number,
41
+ scale: PropTypes.number,
42
+ minScale: PropTypes.number,
43
+ maxScale: PropTypes.number,
44
+ horizontal: PropTypes.bool,
45
+ spacing: PropTypes.number,
46
+ password: PropTypes.string,
47
+ renderActivityIndicator: PropTypes.func,
48
+ enableAntialiasing: PropTypes.bool,
49
+ enableAnnotationRendering: PropTypes.bool,
50
+ enablePaging: PropTypes.bool,
51
+ enableRTL: PropTypes.bool,
52
+ fitPolicy: PropTypes.number,
53
+ trustAllCerts: PropTypes.bool,
54
+ singlePage: PropTypes.bool,
55
+ onLoadComplete: PropTypes.func,
56
+ onPageChanged: PropTypes.func,
57
+ onError: PropTypes.func,
58
+ onPageSingleTap: PropTypes.func,
59
+ onScaleChanged: PropTypes.func,
60
+ onPressLink: PropTypes.func,
61
+
62
+ // Props that are not available in the earlier react native version, added to prevent crashed on android
63
+ accessibilityLabel: PropTypes.string,
64
+ importantForAccessibility: PropTypes.string,
65
+ renderToHardwareTextureAndroid: PropTypes.string,
66
+ testID: PropTypes.string,
67
+ onLayout: PropTypes.bool,
68
+ accessibilityLiveRegion: PropTypes.string,
69
+ accessibilityComponentType: PropTypes.string,
70
+ };
71
+
72
+ static defaultProps = {
73
+ password: "",
74
+ scale: 1,
75
+ minScale: 1,
76
+ maxScale: 3,
77
+ spacing: 10,
78
+ fitPolicy: 2, //fit both
79
+ horizontal: false,
80
+ page: 1,
81
+ enableAntialiasing: true,
82
+ enableAnnotationRendering: true,
83
+ enablePaging: false,
84
+ enableRTL: false,
85
+ trustAllCerts: true,
86
+ usePDFKit: true,
87
+ singlePage: false,
88
+ onLoadProgress: (percent) => {
89
+ },
90
+ onLoadComplete: (numberOfPages, path) => {
91
+ },
92
+ onPageChanged: (page, numberOfPages) => {
93
+ },
94
+ onError: (error) => {
95
+ },
96
+ onPageSingleTap: (page, x, y) => {
97
+ },
98
+ onScaleChanged: (scale) => {
99
+ },
100
+ onPressLink: (url) => {
101
+ },
102
+ };
103
+
104
+ constructor(props) {
105
+
106
+ super(props);
107
+ this.state = {
108
+ path: '',
109
+ isDownloaded: false,
110
+ progress: 0,
111
+ isSupportPDFKit: -1
112
+ };
113
+
114
+ this.lastRNBFTask = null;
115
+
116
+ }
117
+
118
+ componentDidUpdate(prevProps) {
119
+
120
+ const nextSource = Image.resolveAssetSource(this.props.source);
121
+ const curSource = Image.resolveAssetSource(prevProps.source);
122
+
123
+ if ((nextSource.uri !== curSource.uri)) {
124
+ // if has download task, then cancel it.
125
+ if (this.lastRNBFTask) {
126
+ this.lastRNBFTask.cancel(err => {
127
+ this._loadFromSource(this.props.source);
128
+ });
129
+ this.lastRNBFTask = null;
130
+ } else {
131
+ this._loadFromSource(this.props.source);
132
+ }
133
+ }
134
+ }
135
+
136
+ componentDidMount() {
137
+ this._mounted = true;
138
+ if (Platform.OS === "ios") {
139
+ const PdfViewManagerNative = require('react-native').NativeModules.PdfViewManager;
140
+ PdfViewManagerNative.supportPDFKit((isSupportPDFKit) => {
141
+ if (this._mounted) {
142
+ this.setState({isSupportPDFKit: isSupportPDFKit ? 1 : 0});
143
+ }
144
+ });
145
+ }
146
+ this._loadFromSource(this.props.source);
147
+ }
148
+
149
+ componentWillUnmount() {
150
+ this._mounted = false;
151
+ if (this.lastRNBFTask) {
152
+ this.lastRNBFTask.cancel(err => {
153
+ });
154
+ this.lastRNBFTask = null;
155
+ }
156
+
157
+ }
158
+
159
+ _loadFromSource = (newSource) => {
160
+
161
+ const source = Image.resolveAssetSource(newSource) || {};
162
+
163
+ let uri = source.uri || '';
164
+ // first set to initial state
165
+ if (this._mounted) {
166
+ this.setState({isDownloaded: false, path: '', progress: 0});
167
+ }
168
+ const filename = source.cacheFileName || SHA1(uri) + '.pdf';
169
+ const cacheFile = ReactNativeBlobUtil.fs.dirs.CacheDir + '/' + filename;
170
+
171
+ if (source.cache) {
172
+ ReactNativeBlobUtil.fs
173
+ .stat(cacheFile)
174
+ .then(stats => {
175
+ if (!Boolean(source.expiration) || (source.expiration * 1000 + stats.lastModified) > (new Date().getTime())) {
176
+ if (this._mounted) {
177
+ this.setState({path: cacheFile, isDownloaded: true});
178
+ }
179
+ } else {
180
+ // cache expirated then reload it
181
+ this._prepareFile(source);
182
+ }
183
+ })
184
+ .catch(() => {
185
+ this._prepareFile(source);
186
+ })
187
+
188
+ } else {
189
+ this._prepareFile(source);
190
+ }
191
+ };
192
+
193
+ _prepareFile = async (source) => {
194
+
195
+ try {
196
+ if (source.uri) {
197
+ let uri = source.uri || '';
198
+
199
+ const isNetwork = !!(uri && uri.match(/^https?:\/\//));
200
+ const isAsset = !!(uri && uri.match(/^bundle-assets:\/\//));
201
+ const isBase64 = !!(uri && uri.match(/^data:application\/pdf;base64/));
202
+
203
+ const filename = source.cacheFileName || SHA1(uri) + '.pdf';
204
+ const cacheFile = ReactNativeBlobUtil.fs.dirs.CacheDir + '/' + filename;
205
+
206
+ // delete old cache file
207
+ this._unlinkFile(cacheFile);
208
+
209
+ if (isNetwork) {
210
+ this._downloadFile(source, cacheFile);
211
+ } else if (isAsset) {
212
+ ReactNativeBlobUtil.fs
213
+ .cp(uri, cacheFile)
214
+ .then(() => {
215
+ if (this._mounted) {
216
+ this.setState({path: cacheFile, isDownloaded: true, progress: 1});
217
+ }
218
+ })
219
+ .catch(async (error) => {
220
+ this._unlinkFile(cacheFile);
221
+ this._onError(error);
222
+ })
223
+ } else if (isBase64) {
224
+ let data = uri.replace(/data:application\/pdf;base64,/i, '');
225
+ ReactNativeBlobUtil.fs
226
+ .writeFile(cacheFile, data, 'base64')
227
+ .then(() => {
228
+ if (this._mounted) {
229
+ this.setState({path: cacheFile, isDownloaded: true, progress: 1});
230
+ }
231
+ })
232
+ .catch(async (error) => {
233
+ this._unlinkFile(cacheFile);
234
+ this._onError(error)
235
+ });
236
+ } else {
237
+ if (this._mounted) {
238
+ this.setState({
239
+ path: uri.replace(/file:\/\//i, ''),
240
+ isDownloaded: true,
241
+ });
242
+ }
243
+ }
244
+ } else {
245
+ this._onError(new Error('no pdf source!'));
246
+ }
247
+ } catch (e) {
248
+ this._onError(e)
249
+ }
250
+
251
+
252
+ };
253
+
254
+ _downloadFile = async (source, cacheFile) => {
255
+
256
+ if (this.lastRNBFTask) {
257
+ this.lastRNBFTask.cancel(err => {
258
+ });
259
+ this.lastRNBFTask = null;
260
+ }
261
+
262
+ const tempCacheFile = cacheFile + '.tmp';
263
+ this._unlinkFile(tempCacheFile);
264
+
265
+ this.lastRNBFTask = ReactNativeBlobUtil.config({
266
+ // response data will be saved to this path if it has access right.
267
+ path: tempCacheFile,
268
+ trusty: this.props.trustAllCerts,
269
+ })
270
+ .fetch(
271
+ source.method ? source.method : 'GET',
272
+ source.uri,
273
+ source.headers ? source.headers : {},
274
+ source.body ? source.body : ""
275
+ )
276
+ // listen to download progress event
277
+ .progress((received, total) => {
278
+ this.props.onLoadProgress && this.props.onLoadProgress(received / total);
279
+ if (this._mounted) {
280
+ this.setState({progress: received / total});
281
+ }
282
+ });
283
+
284
+ this.lastRNBFTask
285
+ .then(async (res) => {
286
+
287
+ this.lastRNBFTask = null;
288
+
289
+ if (res && res.respInfo && res.respInfo.headers && !res.respInfo.headers["Content-Encoding"] && !res.respInfo.headers["Transfer-Encoding"] && res.respInfo.headers["Content-Length"]) {
290
+ const expectedContentLength = res.respInfo.headers["Content-Length"];
291
+ let actualContentLength;
292
+
293
+ try {
294
+ const fileStats = await ReactNativeBlobUtil.fs.stat(res.path());
295
+
296
+ if (!fileStats || !fileStats.size) {
297
+ throw new Error("FileNotFound:" + source.uri);
298
+ }
299
+
300
+ actualContentLength = fileStats.size;
301
+ } catch (error) {
302
+ throw new Error("DownloadFailed:" + source.uri);
303
+ }
304
+
305
+ if (expectedContentLength != actualContentLength) {
306
+ throw new Error("DownloadFailed:" + source.uri);
307
+ }
308
+ }
309
+
310
+ this._unlinkFile(cacheFile);
311
+ ReactNativeBlobUtil.fs
312
+ .cp(tempCacheFile, cacheFile)
313
+ .then(() => {
314
+ if (this._mounted) {
315
+ this.setState({path: cacheFile, isDownloaded: true, progress: 1});
316
+ }
317
+ this._unlinkFile(tempCacheFile);
318
+ })
319
+ .catch(async (error) => {
320
+ throw error;
321
+ });
322
+ })
323
+ .catch(async (error) => {
324
+ this._unlinkFile(tempCacheFile);
325
+ this._unlinkFile(cacheFile);
326
+ this._onError(error);
327
+ });
328
+
329
+ };
330
+
331
+ _unlinkFile = async (file) => {
332
+ try {
333
+ await ReactNativeBlobUtil.fs.unlink(file);
334
+ } catch (e) {
335
+
336
+ }
337
+ }
338
+
339
+ setNativeProps = nativeProps => {
340
+ if (this._root){
341
+ this._root.setNativeProps(nativeProps);
342
+ }
343
+ };
344
+
345
+ setPage( pageNumber ) {
346
+ if ( (pageNumber === null) || (isNaN(pageNumber)) ) {
347
+ throw new Error('Specified pageNumber is not a number');
348
+ }
349
+ this.setNativeProps({
350
+ page: pageNumber
351
+ });
352
+ }
353
+
354
+ _onChange = (event) => {
355
+
356
+ let message = event.nativeEvent.message.split('|');
357
+ //__DEV__ && console.log("onChange: " + message);
358
+ if (message.length > 0) {
359
+ if (message.length > 5) {
360
+ message[4] = message.splice(4).join('|');
361
+ }
362
+ if (message[0] === 'loadComplete') {
363
+ this.props.onLoadComplete && this.props.onLoadComplete(Number(message[1]), this.state.path, {
364
+ width: Number(message[2]),
365
+ height: Number(message[3]),
366
+ },
367
+ message[4]&&JSON.parse(message[4]));
368
+ } else if (message[0] === 'pageChanged') {
369
+ this.props.onPageChanged && this.props.onPageChanged(Number(message[1]), Number(message[2]));
370
+ } else if (message[0] === 'error') {
371
+ this._onError(new Error(message[1]));
372
+ } else if (message[0] === 'pageSingleTap') {
373
+ this.props.onPageSingleTap && this.props.onPageSingleTap(Number(message[1]), Number(message[2]), Number(message[3]));
374
+ } else if (message[0] === 'scaleChanged') {
375
+ this.props.onScaleChanged && this.props.onScaleChanged(Number(message[1]));
376
+ } else if (message[0] === 'linkPressed') {
377
+ this.props.onPressLink && this.props.onPressLink(message[1]);
378
+ }
379
+ }
380
+
381
+ };
382
+
383
+ _onError = (error) => {
384
+
385
+ this.props.onError && this.props.onError(error);
386
+
387
+ };
388
+
389
+ render() {
390
+ if (Platform.OS === "android" || Platform.OS === "ios" || Platform.OS === "windows") {
391
+ return (
392
+ <View style={[this.props.style,{overflow: 'hidden'}]}>
393
+ {!this.state.isDownloaded?
394
+ (<View
395
+ style={styles.progressContainer}
396
+ >
397
+ {this.props.renderActivityIndicator
398
+ ? this.props.renderActivityIndicator(this.state.progress)
399
+ : <Text>{`${(this.state.progress * 100).toFixed(2)}%`}</Text>}
400
+ </View>):(
401
+ Platform.OS === "android" || Platform.OS === "windows"?(
402
+ <PdfCustom
403
+ ref={component => (this._root = component)}
404
+ {...this.props}
405
+ style={[{flex:1,backgroundColor: '#EEE'}, this.props.style]}
406
+ path={this.state.path}
407
+ onChange={this._onChange}
408
+ />
409
+ ):(
410
+ this.props.usePDFKit && this.state.isSupportPDFKit === 1?(
411
+ <PdfCustom
412
+ ref={component => (this._root = component)}
413
+ {...this.props}
414
+ style={[{backgroundColor: '#EEE',overflow: 'hidden'}, this.props.style]}
415
+ path={this.state.path}
416
+ onChange={this._onChange}
417
+ />
418
+ ):(<PdfView
419
+ {...this.props}
420
+ style={[{backgroundColor: '#EEE',overflow: 'hidden'}, this.props.style]}
421
+ path={this.state.path}
422
+ onLoadComplete={this.props.onLoadComplete}
423
+ onPageChanged={this.props.onPageChanged}
424
+ onError={this._onError}
425
+ onPageSingleTap={this.props.onPageSingleTap}
426
+ onScaleChanged={this.props.onScaleChanged}
427
+ onPressLink={this.props.onPressLink}
428
+ />)
429
+ )
430
+ )}
431
+ </View>);
432
+ } else {
433
+ return (null);
434
+ }
435
+
436
+
437
+ }
438
+ }
439
+
440
+
441
+ if (Platform.OS === "android") {
442
+ var PdfCustom = requireNativeComponent('RCTPdf', Pdf, {
443
+ nativeOnly: {path: true, onChange: true},
444
+ })
445
+ } else if (Platform.OS === "ios") {
446
+ var PdfCustom = requireNativeComponent('RCTPdfView', Pdf, {
447
+ nativeOnly: {path: true, onChange: true},
448
+ })
449
+ } else if (Platform.OS === "windows") {
450
+ var PdfCustom = requireNativeComponent('RCTPdf', Pdf, {
451
+ nativeOnly: {path: true, onChange: true},
452
+ })
453
+ }
454
+
455
+
456
+ const styles = StyleSheet.create({
457
+ progressContainer: {
458
+ flex: 1,
459
+ justifyContent: 'center',
460
+ alignItems: 'center'
461
+ },
462
+ progressBar: {
463
+ width: 200,
464
+ height: 2
465
+ }
466
+ });
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "react-native-pdf",
3
- "version": "6.6.1",
3
+ "version": "6.6.2",
4
4
  "summary": "A react native PDF view component",
5
5
  "description": "A react native PDF view component, support ios and android platform",
6
6
  "main": "index.js",
7
+ "typings": "./index.d.ts",
7
8
  "repository": {
8
9
  "type": "git",
9
10
  "url": "git+https://github.com/wonday/react-native-pdf.git"
@@ -31,16 +32,12 @@
31
32
  "deprecated-react-native-prop-types": "^2.3.0"
32
33
  },
33
34
  "devDependencies": {
34
- "@types/react-native": "^0.68.0",
35
- "react-native": "^0.68.0",
36
- "typescript": "^4.7.4"
35
+ "prop-types": "^15.7.2"
37
36
  },
38
37
  "files": [
39
38
  "android/",
40
39
  "ios/",
41
40
  "windows/",
42
- "dist/",
43
- "react-native-pdf.podspec",
44
41
  "DoubleTapView.js",
45
42
  "index.d.ts",
46
43
  "index.js",
@@ -49,9 +46,7 @@
49
46
  "PdfPageView.js",
50
47
  "PdfView.js",
51
48
  "PdfViewFlatList.js",
52
- "PinchZoomView.js"
53
- ],
54
- "scripts": {
55
- "build": "rm -rf dist/ && tsc"
56
- }
57
- }
49
+ "PinchZoomView.js",
50
+ "react-native-pdf.podspec"
51
+ ]
52
+ }