├── .circleci
└── config.yml
├── .editorconfig
├── .eslintignore
├── .eslintrc.json
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── stale.yml
├── .gitignore
├── .prettierrc.js
├── .watchmanconfig
├── CONTRIBUTING.md
├── LICENSE
├── PULL_REQUEST_TEMPLATE.md
├── README.md
├── RNPDF.podspec
├── ReactNativeViewPDF.xcodeproj
└── project.pbxproj
├── ReactNativeViewPDF
├── RNPDFConstants.h
├── RNPDFConstants.m
├── RNPDFView.h
├── RNPDFView.m
├── RNPDFViewManager.h
└── RNPDFViewManager.m
├── android
├── build.gradle
├── gradle.properties
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── rumax
│ └── reactnative
│ └── pdfviewer
│ ├── AsyncDownload.java
│ ├── Errors.java
│ ├── PDFView.java
│ ├── PDFViewManager.java
│ └── PDFViewPackage.java
├── babel.config.js
├── demo
├── .buckconfig
├── .eslintrc.js
├── .gitignore
├── .prettierrc.js
├── .watchmanconfig
├── App.tsx
├── Gemfile
├── _bundle
│ └── config
├── _ruby-version
├── android
│ ├── app
│ │ ├── _BUCK
│ │ ├── build.gradle
│ │ ├── build_defs.bzl
│ │ ├── debug.keystore
│ │ ├── proguard-rules.pro
│ │ └── src
│ │ │ ├── debug
│ │ │ ├── AndroidManifest.xml
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── demo
│ │ │ │ └── ReactNativeFlipper.java
│ │ │ └── main
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── assets
│ │ │ └── assets-pdf.pdf
│ │ │ ├── java
│ │ │ └── com
│ │ │ │ └── demo
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── MainApplication.java
│ │ │ │ └── newarchitecture
│ │ │ │ ├── MainApplicationReactNativeHost.java
│ │ │ │ ├── components
│ │ │ │ └── MainComponentsRegistry.java
│ │ │ │ └── modules
│ │ │ │ └── MainApplicationTurboModuleManagerDelegate.java
│ │ │ ├── jni
│ │ │ ├── Android.mk
│ │ │ ├── MainApplicationModuleProvider.cpp
│ │ │ ├── MainApplicationModuleProvider.h
│ │ │ ├── MainApplicationTurboModuleManagerDelegate.cpp
│ │ │ ├── MainApplicationTurboModuleManagerDelegate.h
│ │ │ ├── MainComponentsRegistry.cpp
│ │ │ ├── MainComponentsRegistry.h
│ │ │ └── OnLoad.cpp
│ │ │ └── res
│ │ │ ├── drawable
│ │ │ └── rn_edit_text_material.xml
│ │ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ └── values
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ └── settings.gradle
├── app.json
├── babel.config.js
├── index.js
├── ios
│ ├── Podfile
│ ├── Podfile.lock
│ ├── _xcode.env
│ ├── demo.xcodeproj
│ │ ├── project.pbxproj
│ │ └── xcshareddata
│ │ │ └── xcschemes
│ │ │ └── demo.xcscheme
│ ├── demo.xcworkspace
│ │ └── contents.xcworkspacedata
│ ├── demo
│ │ ├── AppDelegate.h
│ │ ├── AppDelegate.mm
│ │ ├── Images.xcassets
│ │ │ ├── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ │ └── Contents.json
│ │ ├── Info.plist
│ │ ├── LaunchScreen.storyboard
│ │ └── main.m
│ ├── demoTests
│ │ ├── Info.plist
│ │ └── demoTests.m
│ └── test-pdf.pdf
├── metro.config.js
├── package.json
├── res
│ ├── android_pdf.gif
│ └── ios_pdf.gif
├── src
│ ├── App.tsx
│ ├── Button.tsx
│ ├── base64.json
│ ├── resources.ts
│ └── styles.ts
├── tsconfig.json
└── utils
│ └── server.js
├── jest.config.js
├── metro.config.js
├── package.json
├── src
├── __tests__
│ ├── __snapshots__
│ │ └── index.tsx.snap
│ └── index.tsx
└── index.tsx
└── tsconfig.json
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | docker:
5 | - image: circleci/node:14
6 | steps:
7 | - checkout
8 | - run: npm install
9 | - run: npm run lint
10 | - run: npm run check-types
11 | - run: npm run test
12 | - run: npm run test-coverage
13 | - run: npm run test-coverage-report
14 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig is awesome: http://EditorConfig.org
2 |
3 | # top-most EditorConfig file
4 | root = true
5 |
6 | [*]
7 | charset = utf-8
8 | end_of_line = lf
9 | insert_final_newline = true
10 |
11 | [**/{.js,.ts{x},package.json}]
12 | indent_style = space
13 | indent_size = 2
14 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | demo/**/*
2 | lib/**/*
3 | preprocessor.js
4 |
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "browser": true,
4 | "es2021": true,
5 | "es6": true,
6 | "jasmine": true
7 | },
8 | "extends": [
9 | "plugin:react/recommended",
10 | "airbnb"
11 | ],
12 | "globals": {
13 | "jest": false,
14 | "__DEV__": false
15 | },
16 | "settings": {
17 | "import/resolver": {
18 | "node": {
19 | "extensions": [".js", ".jsx", ".ts", ".tsx"]
20 | }
21 | }
22 | },
23 | "parser": "@typescript-eslint/parser",
24 | "parserOptions": {
25 | "ecmaFeatures": {
26 | "jsx": true
27 | },
28 | "ecmaVersion": 12,
29 | "sourceType": "module"
30 | },
31 | "plugins": [
32 | "react",
33 | "@typescript-eslint"
34 | ],
35 | "rules": {
36 | "import/no-extraneous-dependencies": 0,
37 | "react/destructuring-assignment": 0,
38 | "operator-linebreak": 0,
39 | "react/sort-comp": 0,
40 | "no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 0 }],
41 | "no-underscore-dangle": 0,
42 | "class-methods-use-this": 0,
43 | "import/extensions": 0,
44 | "no-plusplus": 0,
45 | "no-await-in-loop": 0,
46 | "max-classes-per-file": 0,
47 | "global-require": 0,
48 | "react/jsx-filename-extension": 0,
49 | "react/require-default-props": 0,
50 | "no-use-before-define": 0,
51 | "react/jsx-props-no-spreading": 0,
52 | "react/static-property-placement": 0,
53 | "@typescript-eslint/no-use-before-define": ["error"]
54 | },
55 | "overrides": [
56 | {
57 | "files": ["*.ts", "*.tsx"],
58 | "parser": "@typescript-eslint/parser",
59 | "rules": {
60 | "@typescript-eslint/no-unused-vars": "warn",
61 | "@typescript-eslint/explicit-function-return-type": "error",
62 | "@typescript-eslint/consistent-type-imports": [
63 | 2,
64 | { "prefer": "type-imports" }
65 | ]
66 | }
67 | }
68 | ]
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 |
5 | ---
6 |
7 | **Describe the bug**
8 | A clear and concise description of what the bug is.
9 |
10 | **To Reproduce**
11 |
12 | - [ ] I checked the demo project and cannot reproduce the issue
13 | - [ ] I checked the demo project and the issue exists
14 |
15 | Steps to reproduce the behavior:
16 | 1. Render PDF with '...'
17 | 2. Other actions '...'
18 | 3. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Smartphone (please complete the following information):**
27 | - Device: [e.g. iPhone6]
28 | - OS: [e.g. iOS8.1]
29 | - Version [e.g. 22]
30 |
31 | **Additional context**
32 | Add any other context about the problem here.
33 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 |
5 | ---
6 |
7 | **Is your feature request related to a problem? Please describe.**
8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
9 |
10 | **Describe the solution you'd like**
11 | A clear and concise description of what you want to happen.
12 |
13 | **Describe alternatives you've considered**
14 | A clear and concise description of any alternative solutions or features you've considered.
15 |
16 | **Additional context**
17 | Add any other context or screenshots about the feature request here.
18 |
--------------------------------------------------------------------------------
/.github/stale.yml:
--------------------------------------------------------------------------------
1 | # Number of days of inactivity before an issue becomes stale
2 | daysUntilStale: 30
3 | # Number of days of inactivity before a stale issue is closed
4 | daysUntilClose: 5
5 | # Issues with these labels will never be considered stale
6 | exemptLabels:
7 | - pinned
8 | - security
9 | # Label to use when marking an issue as stale
10 | staleLabel: wontfix
11 | # Comment to post when marking an issue as stale. Set to `false` to disable
12 | markComment: >
13 | This issue has been automatically marked as stale because it has not had
14 | recent activity. It will be closed if no further activity occurs. Thank you
15 | for your contributions.
16 | # Comment to post when closing a stale issue. Set to `false` to disable
17 | closeComment: false
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # NPM
2 | react-native-view-pdf-*.tgz
3 | react-native-view-pdf.tgz
4 | package/
5 |
6 | package-lock.json
7 | yarn.lock
8 |
9 | # jest
10 | coverage
11 |
12 | # generated
13 | lib/
14 |
15 | # OSX
16 | #
17 | .DS_Store
18 |
19 | # node.js
20 | #
21 | node_modules/
22 | npm-debug.log
23 | yarn-error.log
24 |
25 |
26 | # Xcode
27 | #
28 | build/
29 | *.pbxuser
30 | !default.pbxuser
31 | *.mode1v3
32 | !default.mode1v3
33 | *.mode2v3
34 | !default.mode2v3
35 | *.perspectivev3
36 | !default.perspectivev3
37 | xcuserdata
38 | *.xccheckout
39 | *.moved-aside
40 | DerivedData
41 | *.hmap
42 | *.ipa
43 | *.xcuserstate
44 | project.xcworkspace
45 |
46 |
47 | # Android
48 | #
49 | build/
50 | .gradle
51 |
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | bracketSpacing: true,
3 | jsxBracketSameLine: true,
4 | singleQuote: true,
5 | trailingComma: 'all',
6 | arrowParens: 'avoid',
7 | };
8 |
--------------------------------------------------------------------------------
/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to react-native-PDFView
2 |
3 | :+1::tada: Thanks for taking the time to contribute! :tada::+1:
4 |
5 | ## Styleguides
6 |
7 | ### Git Commit Messages
8 |
9 | * Use the present tense ("Add feature" not "Added feature")
10 | * Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
11 | * Limit the first line to 72 characters or less
12 | * Reference issues and pull requests liberally after the first line
13 | * When only changing documentation, include `[ci skip]` in the commit title
14 | * Consider starting the commit message with an applicable emoji:
15 | * :art: `:art:` when improving the format/structure of the code
16 | * :racehorse: `:racehorse:` when improving performance
17 | * :non-potable_water: `:non-potable_water:` when plugging memory leaks
18 | * :memo: `:memo:` when writing docs
19 | * :lollipop: `:lollipop:` when fixing Android
20 | * :apple: `:apple:` when fixing iOS
21 | * :bug: `:bug:` when fixing a bug
22 | * :fire: `:fire:` when removing code or files
23 | * :green_heart: `:green_heart:` when fixing the CI build
24 | * :white_check_mark: `:white_check_mark:` when adding tests
25 | * :lock: `:lock:` when dealing with security
26 | * :arrow_up: `:arrow_up:` when upgrading dependencies
27 | * :arrow_down: `:arrow_down:` when downgrading dependencies
28 | * :shirt: `:shirt:` when removing linter warnings
29 |
30 | ### JavaScript Styleguide
31 |
32 | * All JavaScript must adhere to [JavaScript Standard Style](https://standardjs.com/).
33 |
34 | ### Java Styleguide
35 |
36 | ### Objective-C
37 |
38 | ### Documentation Styleguide
39 |
40 | * Use [Markdown](https://daringfireball.net/projects/markdown).
41 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 - present Maksym Rusynyk
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 |
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ### Description of changes
2 |
3 | ### I did Exploratory testing:
4 | - [ ] android
5 | - [ ] ios
6 |
7 | ### Can it be published to NPM?
8 | - [ ] Breaking change
9 | - [ ] Documentation is updated
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-native-view-pdf
2 |
3 | [](https://app.codacy.com/app/rumax/react-native-PDFView?utm_source=github.com&utm_medium=referral&utm_content=rumax/react-native-PDFView&utm_campaign=Badge_Grade_Dashboard)
4 | [](https://github.com/rumax/react-native-PDFView)
5 | [](https://badge.fury.io/js/react-native-view-pdf)
6 | [](https://circleci.com/gh/rumax/react-native-PDFView)
7 | [](https://codecov.io/gh/rumax/react-native-PDFView)
8 | [](http://makeapullrequest.com)
9 |
10 | Library for displaying [PDF documents](https://acrobat.adobe.com/us/en/acrobat/about-adobe-pdf.html) in [react-native](http://facebook.github.io/react-native/)
11 |
12 | - android - uses [Android PdfViewer](https://github.com/barteksc/AndroidPdfViewer). Targets minSdkVersion 21 (required by [setClipToOutline](https://developer.android.com/reference/android/view/View.html#setClipToOutline%28boolean%29)) and above. By default stable version `2.8.2` is used. It's also possible to override it and use `3.1.0-beta.1` (this version allows to handle links, etc. and will be used when Android PdfViewer stable version is released). To change the version, define it in your build file:
13 |
14 | ```
15 | buildscript {
16 | ext {
17 | ...
18 | pdfViewerVersion = "3.1.0-beta.1"
19 | }
20 | ...
21 | }
22 | ```
23 |
24 | Barteksc PdfViewer uses JCenter, which should be [read-only indefinitely](https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/), but in case the host project does not use it, there is a possibility to use [mhiew/AndroidPdfViewer](https://github.com/mhiew/AndroidPdfViewer)
25 | which is a fork published on mavenCentral. To use it, define the following configuration in your gradle script:
26 |
27 | ```
28 | buildscript {
29 | ext {
30 | ...
31 | pdfViewerVersion = "3.2.0-beta.1"
32 | pdfViewerRepo = "com.github.mhiew"
33 | }
34 | ...
35 | }
36 | ```
37 |
38 | - ios - uses [WKWebView](https://developer.apple.com/documentation/webkit/wkwebview).
39 | Targets iOS9.0 and above
40 |
41 | - zero NPM dependencies
42 |
43 | ## Getting started
44 |
45 | `$ npm install react-native-view-pdf --save`
46 |
47 | ## Linking
48 |
49 | From [RN 0.60](https://github.com/facebook/react-native/releases/tag/v0.60.0) there is no need to link - [Native Modules are now Autolinked](https://facebook.github.io/react-native/blog/2019/07/03/version-60)
50 |
51 | ### Mostly automatic installation
52 |
53 | `$ react-native link`
54 |
55 | If it doesn't work follow the [official react native documentation](https://facebook.github.io/react-native/docs/linking-libraries-ios)
56 |
57 | ##### Using CocoaPods
58 |
59 | In your Xcode project directory open Podfile and add the following line:
60 |
61 | ```
62 | pod 'RNPDF', :path => '../node_modules/react-native-view-pdf'
63 | ```
64 |
65 | And install:
66 |
67 | ```
68 | pod install
69 | ```
70 |
71 | #### Android
72 |
73 | 1. Open up `android/app/src/main/java/[...]/MainApplication.java`
74 | - Add `import com.rumax.reactnative.pdfviewer.PDFViewPackage;` to the imports at the top of the file
75 | - Add `new PDFViewPackage()` to the list returned by the `getPackages()` method
76 | 2. Append the following lines to `android/settings.gradle`:
77 | ```
78 | include ':react-native-view-pdf'
79 | project(':react-native-view-pdf').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-view-pdf/android')
80 | ```
81 | 3. Insert the following lines inside the dependencies block in `android/app/build.gradle`:
82 | ```
83 | compile project(':react-native-view-pdf')
84 | ```
85 |
86 | ##### Note for Android
87 | The Android project tries to retrieve the following properties:
88 | - compileSdkVersion
89 | - buildToolsVersion
90 | - minSdkVersion
91 | - targetSdkVersion
92 |
93 | from the `ext` object if you have one defined in your Android's project root (you can read more about it [here](https://docs.gradle.org/current/userguide/writing_build_scripts.html#example_using_extra_properties)). If not, it falls back to its current versions (check [the gradle file](./android/build.gradle) for additional information).
94 |
95 | #### Windows
96 | [ReactWindows](https://github.com/ReactWindows/react-native)
97 |
98 | N/A
99 |
100 | ## Demo
101 |
102 | Android | iOS
103 | ------- | ---
104 |  | 
105 |
106 |
107 | ### Quick Start
108 |
109 | ```
110 | // With Flow type annotations (https://flow.org/)
111 | import PDFView from 'react-native-view-pdf';
112 | // Without Flow type annotations
113 | // import PDFView from 'react-native-view-pdf/lib/index';
114 |
115 | const resources = {
116 | file: Platform.OS === 'ios' ? 'downloadedDocument.pdf' : '/sdcard/Download/downloadedDocument.pdf',
117 | url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
118 | base64: 'JVBERi0xLjMKJcfs...',
119 | };
120 |
121 | export default class App extends React.Component {
122 | render() {
123 | const resourceType = 'url';
124 |
125 | return (
126 |
127 | {/* Some Controls to change PDF resource */}
128 | console.log(`PDF rendered from ${resourceType}`)}
134 | onError={(error) => console.log('Cannot render PDF', error)}
135 | />
136 |
137 | );
138 | }
139 | }
140 | ```
141 |
142 | Use the [demo](https://github.com/rumax/react-native-PDFView/tree/master/demo) project to:
143 |
144 | - Test the component on both android and iOS
145 | - Render PDF using URL, BASE64 data or local file
146 | - Handle error state
147 |
148 | ### Props
149 |
150 | Name | Android | iOS | Description
151 | ---- | ------- | --- | -----------
152 | resource | ✓ | ✓ | A resource to render. It's possible to render PDF from `file`, `url` (should be [encoded](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI)) or `base64`
153 | resourceType | ✓ | ✓ | Should correspond to resource and can be: `file`, `url` or `base64`
154 | fileFrom | ✗ | ✓ | *iOS ONLY:* In case if `resourceType` is set to `file`, there are different way to search for it on [iOS file system](https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html). Currently `documentsDirectory`, `libraryDirectory`, `cachesDirectory`, `tempDirectory` and `bundle` are supported.
155 | onLoad | ✓ | ✓ | Callback that is triggered when loading is completed
156 | onError | ✓ | ✓ | Callback that is triggered when loading has failed. And error is provided as a function parameter
157 | style | ✓ | ✓ | A [style](https://facebook.github.io/react-native/docs/style)
158 | fadeInDuration | ✓ | ✓ | Fade in duration (in ms, defaults to 0.0) to smoothly fade the webview into view when pdf loading is completed
159 | enableAnnotations | ✓ | ✗ | *Android ONLY:* Boolean to enable Android view annotations (default is false).
160 | urlProps | ✓ | ✓ | Extended properties for `url` type that allows to specify HTTP Method, HTTP headers and HTTP body
161 | onPageChanged | ✓ | ✗ | Callback that is invoked when page is changed. Provides `active page` and `total pages` information
162 | onScrolled | ✓ | ✓ | Callback that is invoked when PDF is scrolled. Provides `offset` value in a range between 0 and 1. *Currently only 0 and 1 are supported*.
163 |
164 | ### Methods
165 |
166 | #### `reload`
167 |
168 | Allows to reload the PDF document. This can be useful in such cases as network issues, document is expired, etc. To reload the document you will need a `ref` to the component:
169 |
170 | ```js
171 | ...
172 |
173 | render() {
174 | return (
175 | this._pdfRed = ref} />
178 | );
179 | }
180 | ```
181 |
182 | And trigger it by calling `reloadPDF`:
183 |
184 | ```js
185 | reloadPDF = async () => {
186 | const pdfRef = this._pdfRef;
187 |
188 | if (!pdfRef) {
189 | return;
190 | }
191 |
192 | try {
193 | await pdfRef.reload();
194 | } catch (err) {
195 | console.err(err.message);
196 | }
197 | }
198 | ```
199 |
200 | Or check the [demo project](https://github.com/rumax/react-native-PDFView/tree/master/demo) which also includes this functionality.
201 |
202 |
203 | ### Development tips
204 |
205 | On android for the `file` type it is required to request permissions to
206 | read/write. You can get more information in [PermissionsAndroid](https://facebook.github.io/react-native/docs/permissionsandroid)
207 | section from react native or [Request App Permissions ](https://developer.android.com/training/permissions/requesting) from android
208 | documentation. [Demo](https://github.com/rumax/react-native-PDFView/tree/master/demo)
209 | project provides an example how to implement it using Java, check the [MainActivity.java](https://github.com/rumax/react-native-PDFView/blob/b84913df174d3b638d2d820a66ed4e6605d56860/demo/android/app/src/main/java/com/demo/MainActivity.java#L12) and [AndroidManifest.xml](https://github.com/rumax/react-native-PDFView/blob/b84913df174d3b638d2d820a66ed4e6605d56860/demo/android/app/src/main/AndroidManifest.xml#L6) files.
210 |
211 | Before trying `file` type in [demo project](https://github.com/rumax/react-native-PDFView/tree/master/demo), open `sdcard/Download` folder in `Device File Explorer` and store some `downloadedDocument.pdf` document that you want to render.
212 |
213 | On iOS, when using resource `file` you can specify where to look for the file with `fileFrom`. If you do not pass any value, the component will lookup in two places. First, it will attempt to locate the file in the Bundle. If it cannot locate it there, it will search the Documents directory. For more information on the iOS filesystem access at runtime of an application please refer [the official documentation](https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html).
214 | Note here that the resource will always need to be a relative path from the Documents directory for example and also do NOT put the scheme in the path (so no `file://.....`).
215 |
216 | You can find an example of both usage of the Bundle and Documents directory for rendering a pdf from `file` on iOS in the demo project.
217 |
218 | In [demo](https://github.com/rumax/react-native-PDFView/tree/master/demo) project you can also run the simple server to serve PDF file. To do this navigate to `demo/utils/` and start the server
219 | `node server.js`. (*Do not forget to set proper IP adress of the server
220 | in `demo/App.js`*)
221 |
222 | ## License
223 |
224 | [MIT](https://opensource.org/licenses/MIT)
225 |
226 | ## Authors
227 | - [sanderfrenken](https://github.com/sanderfrenken)
228 | - [rumax](https://github.com/rumax)
229 |
230 | ### Other information
231 |
232 | - Generated with [react-native-create-library](https://github.com/frostney/react-native-create-library)
233 | - Zero JavaScript dependency. Which means that you do not bring other dependencies to your project
234 | - If you think that something is missing or would like to propose new feature, please, discuss it with authors
235 | - Please, feel free to ⭐️ the project. This gives us a confidence that you like it and we did a great job by publishing and supporting it 🤩
236 | - [If you are using ProGuard, add following rule to proguard config file:](https://github.com/barteksc/AndroidPdfViewer#proguard)
237 |
238 | ```
239 | -keep class com.shockwave.**
240 | ```
241 |
--------------------------------------------------------------------------------
/RNPDF.podspec:
--------------------------------------------------------------------------------
1 | require 'json'
2 |
3 | package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
4 |
5 | Pod::Spec.new do |s|
6 |
7 | s.name = 'RNPDF'
8 | s.version = package['version'].gsub(/v|-beta/, '')
9 | s.summary = package['description']
10 | s.author = package['author']
11 | s.license = package['license']
12 | s.homepage = package['homepage']
13 | s.source = { :git => 'https://github.com/rumax/react-native-PDFView.git', :tag => "v#{s.version}"}
14 | s.platform = :ios, '7.0'
15 | s.preserve_paths = '*.js'
16 |
17 | s.dependency 'React'
18 |
19 | s.source_files = 'ReactNativeViewPDF/*.{h,m}'
20 | s.public_header_files = ['ReactNativeViewPDF/*.h']
21 |
22 | end
--------------------------------------------------------------------------------
/ReactNativeViewPDF.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 48;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 5318AA192052B83E009FB5F2 /* RNPDFView.m in Sources */ = {isa = PBXBuildFile; fileRef = 5318AA132052B83D009FB5F2 /* RNPDFView.m */; };
11 | 5318AA1A2052B83E009FB5F2 /* RNPDFViewManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 5318AA162052B83E009FB5F2 /* RNPDFViewManager.m */; };
12 | 5318AA1B2052B83E009FB5F2 /* RNPDFConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 5318AA182052B83E009FB5F2 /* RNPDFConstants.m */; };
13 | /* End PBXBuildFile section */
14 |
15 | /* Begin PBXCopyFilesBuildPhase section */
16 | 5318AA052052B7FC009FB5F2 /* CopyFiles */ = {
17 | isa = PBXCopyFilesBuildPhase;
18 | buildActionMask = 2147483647;
19 | dstPath = "include/$(PRODUCT_NAME)";
20 | dstSubfolderSpec = 16;
21 | files = (
22 | );
23 | runOnlyForDeploymentPostprocessing = 0;
24 | };
25 | /* End PBXCopyFilesBuildPhase section */
26 |
27 | /* Begin PBXFileReference section */
28 | 5318AA072052B7FC009FB5F2 /* libReactNativeViewPDF.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libReactNativeViewPDF.a; sourceTree = BUILT_PRODUCTS_DIR; };
29 | 5318AA132052B83D009FB5F2 /* RNPDFView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNPDFView.m; sourceTree = ""; };
30 | 5318AA142052B83D009FB5F2 /* RNPDFView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNPDFView.h; sourceTree = ""; };
31 | 5318AA152052B83E009FB5F2 /* RNPDFViewManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNPDFViewManager.h; sourceTree = ""; };
32 | 5318AA162052B83E009FB5F2 /* RNPDFViewManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNPDFViewManager.m; sourceTree = ""; };
33 | 5318AA172052B83E009FB5F2 /* RNPDFConstants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNPDFConstants.h; sourceTree = ""; };
34 | 5318AA182052B83E009FB5F2 /* RNPDFConstants.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNPDFConstants.m; sourceTree = ""; };
35 | /* End PBXFileReference section */
36 |
37 | /* Begin PBXFrameworksBuildPhase section */
38 | 5318AA042052B7FC009FB5F2 /* Frameworks */ = {
39 | isa = PBXFrameworksBuildPhase;
40 | buildActionMask = 2147483647;
41 | files = (
42 | );
43 | runOnlyForDeploymentPostprocessing = 0;
44 | };
45 | /* End PBXFrameworksBuildPhase section */
46 |
47 | /* Begin PBXGroup section */
48 | 5318A9FE2052B7FC009FB5F2 = {
49 | isa = PBXGroup;
50 | children = (
51 | 5318AA092052B7FC009FB5F2 /* ReactNativeViewPDF */,
52 | 5318AA082052B7FC009FB5F2 /* Products */,
53 | );
54 | sourceTree = "";
55 | };
56 | 5318AA082052B7FC009FB5F2 /* Products */ = {
57 | isa = PBXGroup;
58 | children = (
59 | 5318AA072052B7FC009FB5F2 /* libReactNativeViewPDF.a */,
60 | );
61 | name = Products;
62 | sourceTree = "";
63 | };
64 | 5318AA092052B7FC009FB5F2 /* ReactNativeViewPDF */ = {
65 | isa = PBXGroup;
66 | children = (
67 | 5318AA172052B83E009FB5F2 /* RNPDFConstants.h */,
68 | 5318AA182052B83E009FB5F2 /* RNPDFConstants.m */,
69 | 5318AA142052B83D009FB5F2 /* RNPDFView.h */,
70 | 5318AA132052B83D009FB5F2 /* RNPDFView.m */,
71 | 5318AA152052B83E009FB5F2 /* RNPDFViewManager.h */,
72 | 5318AA162052B83E009FB5F2 /* RNPDFViewManager.m */,
73 | );
74 | path = ReactNativeViewPDF;
75 | sourceTree = "";
76 | };
77 | /* End PBXGroup section */
78 |
79 | /* Begin PBXNativeTarget section */
80 | 5318AA062052B7FC009FB5F2 /* ReactNativeViewPDF */ = {
81 | isa = PBXNativeTarget;
82 | buildConfigurationList = 5318AA102052B7FC009FB5F2 /* Build configuration list for PBXNativeTarget "ReactNativeViewPDF" */;
83 | buildPhases = (
84 | 5318AA032052B7FC009FB5F2 /* Sources */,
85 | 5318AA042052B7FC009FB5F2 /* Frameworks */,
86 | 5318AA052052B7FC009FB5F2 /* CopyFiles */,
87 | );
88 | buildRules = (
89 | );
90 | dependencies = (
91 | );
92 | name = ReactNativeViewPDF;
93 | productName = ReactNativeViewPDF;
94 | productReference = 5318AA072052B7FC009FB5F2 /* libReactNativeViewPDF.a */;
95 | productType = "com.apple.product-type.library.static";
96 | };
97 | /* End PBXNativeTarget section */
98 |
99 | /* Begin PBXProject section */
100 | 5318A9FF2052B7FC009FB5F2 /* Project object */ = {
101 | isa = PBXProject;
102 | attributes = {
103 | LastUpgradeCheck = 0900;
104 | ORGANIZATIONNAME = "sander frenken";
105 | TargetAttributes = {
106 | 5318AA062052B7FC009FB5F2 = {
107 | CreatedOnToolsVersion = 9.0;
108 | ProvisioningStyle = Automatic;
109 | };
110 | };
111 | };
112 | buildConfigurationList = 5318AA022052B7FC009FB5F2 /* Build configuration list for PBXProject "ReactNativeViewPDF" */;
113 | compatibilityVersion = "Xcode 8.0";
114 | developmentRegion = en;
115 | hasScannedForEncodings = 0;
116 | knownRegions = (
117 | en,
118 | );
119 | mainGroup = 5318A9FE2052B7FC009FB5F2;
120 | productRefGroup = 5318AA082052B7FC009FB5F2 /* Products */;
121 | projectDirPath = "";
122 | projectRoot = "";
123 | targets = (
124 | 5318AA062052B7FC009FB5F2 /* ReactNativeViewPDF */,
125 | );
126 | };
127 | /* End PBXProject section */
128 |
129 | /* Begin PBXSourcesBuildPhase section */
130 | 5318AA032052B7FC009FB5F2 /* Sources */ = {
131 | isa = PBXSourcesBuildPhase;
132 | buildActionMask = 2147483647;
133 | files = (
134 | 5318AA192052B83E009FB5F2 /* RNPDFView.m in Sources */,
135 | 5318AA1B2052B83E009FB5F2 /* RNPDFConstants.m in Sources */,
136 | 5318AA1A2052B83E009FB5F2 /* RNPDFViewManager.m in Sources */,
137 | );
138 | runOnlyForDeploymentPostprocessing = 0;
139 | };
140 | /* End PBXSourcesBuildPhase section */
141 |
142 | /* Begin XCBuildConfiguration section */
143 | 5318AA0E2052B7FC009FB5F2 /* Debug */ = {
144 | isa = XCBuildConfiguration;
145 | buildSettings = {
146 | ALWAYS_SEARCH_USER_PATHS = NO;
147 | CLANG_ANALYZER_NONNULL = YES;
148 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
149 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
150 | CLANG_CXX_LIBRARY = "libc++";
151 | CLANG_ENABLE_MODULES = YES;
152 | CLANG_ENABLE_OBJC_ARC = YES;
153 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
154 | CLANG_WARN_BOOL_CONVERSION = YES;
155 | CLANG_WARN_COMMA = YES;
156 | CLANG_WARN_CONSTANT_CONVERSION = YES;
157 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
158 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
159 | CLANG_WARN_EMPTY_BODY = YES;
160 | CLANG_WARN_ENUM_CONVERSION = YES;
161 | CLANG_WARN_INFINITE_RECURSION = YES;
162 | CLANG_WARN_INT_CONVERSION = YES;
163 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
164 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
165 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
166 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
167 | CLANG_WARN_STRICT_PROTOTYPES = YES;
168 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
169 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
170 | CLANG_WARN_UNREACHABLE_CODE = YES;
171 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
172 | CODE_SIGN_IDENTITY = "iPhone Developer";
173 | COPY_PHASE_STRIP = NO;
174 | DEBUG_INFORMATION_FORMAT = dwarf;
175 | ENABLE_STRICT_OBJC_MSGSEND = YES;
176 | ENABLE_TESTABILITY = YES;
177 | GCC_C_LANGUAGE_STANDARD = gnu11;
178 | GCC_DYNAMIC_NO_PIC = NO;
179 | GCC_NO_COMMON_BLOCKS = YES;
180 | GCC_OPTIMIZATION_LEVEL = 0;
181 | GCC_PREPROCESSOR_DEFINITIONS = (
182 | "DEBUG=1",
183 | "$(inherited)",
184 | );
185 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
186 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
187 | GCC_WARN_UNDECLARED_SELECTOR = YES;
188 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
189 | GCC_WARN_UNUSED_FUNCTION = YES;
190 | GCC_WARN_UNUSED_VARIABLE = YES;
191 | IPHONEOS_DEPLOYMENT_TARGET = 9.0;
192 | MTL_ENABLE_DEBUG_INFO = YES;
193 | ONLY_ACTIVE_ARCH = YES;
194 | SDKROOT = iphoneos;
195 | };
196 | name = Debug;
197 | };
198 | 5318AA0F2052B7FC009FB5F2 /* Release */ = {
199 | isa = XCBuildConfiguration;
200 | buildSettings = {
201 | ALWAYS_SEARCH_USER_PATHS = NO;
202 | CLANG_ANALYZER_NONNULL = YES;
203 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
204 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
205 | CLANG_CXX_LIBRARY = "libc++";
206 | CLANG_ENABLE_MODULES = YES;
207 | CLANG_ENABLE_OBJC_ARC = YES;
208 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
209 | CLANG_WARN_BOOL_CONVERSION = YES;
210 | CLANG_WARN_COMMA = YES;
211 | CLANG_WARN_CONSTANT_CONVERSION = YES;
212 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
213 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
214 | CLANG_WARN_EMPTY_BODY = YES;
215 | CLANG_WARN_ENUM_CONVERSION = YES;
216 | CLANG_WARN_INFINITE_RECURSION = YES;
217 | CLANG_WARN_INT_CONVERSION = YES;
218 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
219 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
220 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
221 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
222 | CLANG_WARN_STRICT_PROTOTYPES = YES;
223 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
224 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
225 | CLANG_WARN_UNREACHABLE_CODE = YES;
226 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
227 | CODE_SIGN_IDENTITY = "iPhone Developer";
228 | COPY_PHASE_STRIP = NO;
229 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
230 | ENABLE_NS_ASSERTIONS = NO;
231 | ENABLE_STRICT_OBJC_MSGSEND = YES;
232 | GCC_C_LANGUAGE_STANDARD = gnu11;
233 | GCC_NO_COMMON_BLOCKS = YES;
234 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
235 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
236 | GCC_WARN_UNDECLARED_SELECTOR = YES;
237 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
238 | GCC_WARN_UNUSED_FUNCTION = YES;
239 | GCC_WARN_UNUSED_VARIABLE = YES;
240 | IPHONEOS_DEPLOYMENT_TARGET = 9.0;
241 | MTL_ENABLE_DEBUG_INFO = NO;
242 | SDKROOT = iphoneos;
243 | VALIDATE_PRODUCT = YES;
244 | };
245 | name = Release;
246 | };
247 | 5318AA112052B7FC009FB5F2 /* Debug */ = {
248 | isa = XCBuildConfiguration;
249 | buildSettings = {
250 | CODE_SIGN_STYLE = Automatic;
251 | OTHER_LDFLAGS = "-ObjC";
252 | PRODUCT_NAME = "$(TARGET_NAME)";
253 | SKIP_INSTALL = YES;
254 | TARGETED_DEVICE_FAMILY = "1,2";
255 | };
256 | name = Debug;
257 | };
258 | 5318AA122052B7FC009FB5F2 /* Release */ = {
259 | isa = XCBuildConfiguration;
260 | buildSettings = {
261 | CODE_SIGN_STYLE = Automatic;
262 | OTHER_LDFLAGS = "-ObjC";
263 | PRODUCT_NAME = "$(TARGET_NAME)";
264 | SKIP_INSTALL = YES;
265 | TARGETED_DEVICE_FAMILY = "1,2";
266 | };
267 | name = Release;
268 | };
269 | /* End XCBuildConfiguration section */
270 |
271 | /* Begin XCConfigurationList section */
272 | 5318AA022052B7FC009FB5F2 /* Build configuration list for PBXProject "ReactNativeViewPDF" */ = {
273 | isa = XCConfigurationList;
274 | buildConfigurations = (
275 | 5318AA0E2052B7FC009FB5F2 /* Debug */,
276 | 5318AA0F2052B7FC009FB5F2 /* Release */,
277 | );
278 | defaultConfigurationIsVisible = 0;
279 | defaultConfigurationName = Release;
280 | };
281 | 5318AA102052B7FC009FB5F2 /* Build configuration list for PBXNativeTarget "ReactNativeViewPDF" */ = {
282 | isa = XCConfigurationList;
283 | buildConfigurations = (
284 | 5318AA112052B7FC009FB5F2 /* Debug */,
285 | 5318AA122052B7FC009FB5F2 /* Release */,
286 | );
287 | defaultConfigurationIsVisible = 0;
288 | defaultConfigurationName = Release;
289 | };
290 | /* End XCConfigurationList section */
291 | };
292 | rootObject = 5318A9FF2052B7FC009FB5F2 /* Project object */;
293 | }
294 |
--------------------------------------------------------------------------------
/ReactNativeViewPDF/RNPDFConstants.h:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | extern NSString * const UTF_8;
4 | extern NSString * const UTF_16;
5 | extern NSString * const RESOURCE_TYPE_URL;
6 | extern NSString * const RESOURCE_TYPE_BASE64;
7 | extern NSString * const RESOURCE_TYPE_FILE;
8 | extern NSString * const MIMETYPE_PDF;
9 | extern NSString *const HTTP_METHOD_GET;
10 |
11 | // Url Props
12 | extern NSString * const URL_PROPS_METHOD_KEY;
13 | extern NSString * const URL_PROPS_HEADERS_KEY;
14 | extern NSString * const URL_PROPS_BODY_KEY;
15 |
16 | // Supported protocols
17 | extern NSString * const HTTP_PROTOCOL;
18 | extern NSString * const HTTPS_PROTOCOL;
19 | extern NSString * const FILE_PROTOCOL;
20 |
21 | // Error types
22 | extern NSString * const ERROR_UNSUPPORTED_TYPE;
23 | extern NSString * const ERROR_NETWORK_ERROR;
24 | extern NSString * const ERROR_ONLOADING;
25 | extern NSString * const ERROR_REQUIRED_INPUT_NOT_SET;
26 | extern NSString * const ERROR_INVALID_REACT_TAG;
27 |
28 | // Error messages
29 | extern NSString * const ERROR_MESSAGE_KEY;
30 | extern NSString * const ERROR_MESSAGE_TITLE;
31 | extern NSString * const ERROR_MESSAGE_BASE64_NIL;
32 | extern NSString * const ERROR_MESSAGE_FILENOTFOUND;
33 |
--------------------------------------------------------------------------------
/ReactNativeViewPDF/RNPDFConstants.m:
--------------------------------------------------------------------------------
1 | #import "RNPDFConstants.h"
2 |
3 | NSString *const UTF_8 = @"utf-8";
4 | NSString *const UTF_16 = @"utf-16";
5 | NSString *const RESOURCE_TYPE_URL = @"url";
6 | NSString *const RESOURCE_TYPE_BASE64 = @"base64";
7 | NSString *const RESOURCE_TYPE_FILE = @"file";
8 | NSString *const MIMETYPE_PDF = @"application/pdf";
9 | NSString *const HTTP_METHOD_GET = @"GET";
10 |
11 | // Url Props
12 | NSString *const URL_PROPS_METHOD_KEY = @"method";
13 | NSString *const URL_PROPS_HEADERS_KEY = @"headers";
14 | NSString *const URL_PROPS_BODY_KEY = @"body";
15 |
16 | // Supported protocols
17 | NSString *const HTTP_PROTOCOL = @"http";
18 | NSString *const HTTPS_PROTOCOL = @"https";
19 | NSString *const FILE_PROTOCOL = @"file";
20 |
21 | // Error types
22 | NSString *const ERROR_UNSUPPORTED_TYPE = @"Unsupported resourceType";
23 | NSString *const ERROR_NETWORK_ERROR = @"Network error";
24 | NSString *const ERROR_ONLOADING = @"Error occured while loading content in webview";
25 | NSString *const ERROR_REQUIRED_INPUT_NOT_SET = @"Validation failed. Confirm resource and resourceType have a value";
26 | NSString *const ERROR_INVALID_REACT_TAG = @"Invalid react tag";
27 |
28 | // Error messages
29 | NSString *const ERROR_MESSAGE_KEY = @"message";
30 | NSString *const ERROR_MESSAGE_TITLE = @"title";
31 | NSString *const ERROR_MESSAGE_BASE64_NIL = @"Converted Base64 data is nil";
32 | NSString *const ERROR_MESSAGE_FILENOTFOUND = @"PDF file not found";
33 |
--------------------------------------------------------------------------------
/ReactNativeViewPDF/RNPDFView.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import "RNPDFConstants.h"
3 | #import
4 |
5 | @interface RNPDFView : RCTView
6 |
7 | @property (nonatomic, copy) NSString *resource;
8 | @property (nonatomic, copy) NSString *resourceType;
9 | @property (nonatomic, copy) NSString *fileFrom;
10 | @property (nonatomic, copy) NSString *textEncoding;
11 | @property (nonatomic, copy) NSDictionary *urlProps;
12 | @property (nonatomic) NSTimeInterval fadeInDuration;
13 | @property (nonatomic, copy) RCTDirectEventBlock onLoad;
14 | @property (nonatomic, copy) RCTDirectEventBlock onError;
15 | @property (nonatomic, copy) RCTDirectEventBlock onScrolled;
16 |
17 | - (BOOL)isRequiredInputSet;
18 | - (BOOL)isSupportedResourceType;
19 | - (BOOL)isURLResource;
20 | - (BOOL)isBase64Resource;
21 |
22 | - (void)reload;
23 |
24 | @end
25 |
--------------------------------------------------------------------------------
/ReactNativeViewPDF/RNPDFView.m:
--------------------------------------------------------------------------------
1 | #import "RNPDFView.h"
2 |
3 | @implementation RNPDFView
4 | {
5 | WKWebView *webview;
6 | NSString *currentResource;
7 | NSString *currentResourceType;
8 | NSString *currentFileFrom;
9 | bool didLoadOnce; // Needed as on init, didSetProps is called as well, leading to layoutSubviews being called twice
10 | bool ignoreScrollEvent;
11 | float lastOffset;
12 | }
13 |
14 | - (void)didSetProps:(NSArray *)changedProps {
15 | if (didLoadOnce) {
16 | [self layoutSubviews];
17 | }
18 | }
19 |
20 | - (instancetype)init {
21 | self = [super init];
22 | lastOffset = 0;
23 | ignoreScrollEvent = true;
24 | if ( self ) {
25 | [self setBackgroundColor: [UIColor clearColor]];
26 |
27 | webview = [[WKWebView alloc] initWithFrame: self.frame];
28 | [webview setNavigationDelegate: self];
29 | [webview.scrollView setDelegate: self];
30 | [self addSubview: webview];
31 | }
32 | return self;
33 | }
34 |
35 | - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
36 | if (ignoreScrollEvent) {
37 | return;
38 | }
39 | // currently only offset 0 and 1 are supported
40 | if (lastOffset != 0 && scrollView.contentOffset.y <= 0.0){
41 | lastOffset = 0;
42 | [self reportOnScroll];
43 | } else if (lastOffset != 1 && scrollView.contentOffset.y >=
44 | (scrollView.contentSize.height - scrollView.frame.size.height)){
45 | lastOffset = 1;
46 | [self reportOnScroll];
47 | }
48 |
49 | }
50 |
51 | - (void)reportOnScroll {
52 | if (_onScrolled) {
53 | _onScrolled(@{ @"offset": [NSNumber numberWithFloat:(float) lastOffset] });
54 | }
55 | }
56 |
57 | - (void)reload {
58 | [self renderContent];
59 | }
60 |
61 | - (void)layoutSubviews {
62 | [super layoutSubviews];
63 |
64 | webview.frame = self.bounds;
65 | didLoadOnce = true;
66 |
67 | if (![self isNewInput]) {
68 | return;
69 | }
70 |
71 | [self renderContent];
72 | }
73 |
74 | - (void)renderContent {
75 | [webview setAlpha: 0.0];
76 |
77 | if (![self isRequiredInputSet]) {
78 | return;
79 | }
80 |
81 | [self updateInput];
82 |
83 | if (![self isSupportedResourceType]) {
84 | [self throwError: ERROR_UNSUPPORTED_TYPE withMessage: [NSString stringWithFormat: @"resourceType: %@ not recognized", _resourceType]];
85 | return;
86 | }
87 |
88 | ignoreScrollEvent = true;
89 |
90 | if ([self isURLResource]) {
91 | NSURLRequest *request = [self createRequest];
92 | if (request) {
93 | [webview loadRequest: request];
94 | }
95 | } else if ([self isFileResource]) {
96 | NSURL *fileURL = [self getFileURL];
97 | if (fileURL == nil) {
98 | [self throwError: ERROR_ONLOADING withMessage: ERROR_MESSAGE_FILENOTFOUND];
99 | return;
100 | }
101 |
102 | [webview loadFileURL: fileURL allowingReadAccessToURL: fileURL];
103 | } else {
104 | NSString *characterEncodingName = [_textEncoding isEqual: UTF_16] ? UTF_16 : UTF_8;
105 | NSData *base64Decoded = [[NSData alloc] initWithBase64EncodedString: _resource options: NSDataBase64DecodingIgnoreUnknownCharacters];
106 | if (base64Decoded != nil) {
107 | [webview loadData: base64Decoded MIMEType: MIMETYPE_PDF characterEncodingName: characterEncodingName baseURL: [[NSURL alloc] init]];
108 | } else {
109 | [self throwError: ERROR_ONLOADING withMessage: ERROR_MESSAGE_BASE64_NIL];
110 | }
111 | }
112 | }
113 |
114 | - (NSURL *)getFileURL {
115 | NSURL *url;
116 | if ([currentFileFrom isEqualToString:@"bundle"]) {
117 | url = [self fileFromBundleURL];
118 | } else if ([currentFileFrom isEqualToString:@"documentsDirectory"]) {
119 | url = [self fileFromDirectoryURL:NSDocumentDirectory];
120 | } else if ([currentFileFrom isEqualToString:@"libraryDirectory"]) {
121 | url = [self fileFromDirectoryURL:NSLibraryDirectory];
122 | } else if ([currentFileFrom isEqualToString:@"cachesDirectory"]) {
123 | url = [self fileFromDirectoryURL:NSCachesDirectory];
124 | } else if ([currentFileFrom isEqualToString:@"tempDirectory"]) {
125 | url = [self fileFromDirectoryPath:NSTemporaryDirectory()];
126 | } else { // default is search
127 | url = [self fileFromBundleURL];
128 | if (url == nil) {
129 | // default directory is Documents
130 | url = [self fileFromDirectoryURL:NSDocumentDirectory];
131 | }
132 | }
133 |
134 | return url;
135 | }
136 |
137 | - (NSMutableURLRequest *)createRequest {
138 | NSURL *URL = [NSURL URLWithString: _resource];
139 | NSString *scheme = URL.scheme;
140 |
141 | if ([HTTP_PROTOCOL caseInsensitiveCompare: scheme] != NSOrderedSame &&
142 | [HTTPS_PROTOCOL caseInsensitiveCompare: scheme] != NSOrderedSame &&
143 | [FILE_PROTOCOL caseInsensitiveCompare: scheme] != NSOrderedSame) {
144 | [self throwError: ERROR_ONLOADING withMessage: [NSString stringWithFormat:@"Protocol %@ is not supported", scheme]];
145 | return nil;
146 | }
147 |
148 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: URL
149 | cachePolicy: NSURLRequestUseProtocolCachePolicy
150 | timeoutInterval: 60.0];
151 | if (_urlProps != nil) {
152 | [self enrichRequestWithUrlProps: request];
153 | }
154 |
155 | return request;
156 | }
157 |
158 | - (void)enrichRequestWithUrlProps: (NSMutableURLRequest *) request {
159 | NSString* method = [_urlProps objectForKey: URL_PROPS_METHOD_KEY];
160 | NSString* body = [_urlProps objectForKey: URL_PROPS_BODY_KEY];
161 | NSDictionary* headers = [_urlProps objectForKey: URL_PROPS_HEADERS_KEY];
162 |
163 | if (method != nil) {
164 | [request setHTTPMethod: method];
165 | }
166 | if (body != nil) {
167 | [request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
168 | }
169 | if (headers != nil) {
170 | for (id key in headers) {
171 | [request setValue: [headers objectForKey: key] forHTTPHeaderField: key];
172 | }
173 | }
174 | }
175 |
176 | - (void)updateInput {
177 | currentResourceType = _resourceType;
178 | currentResource = _resource;
179 | currentFileFrom = _fileFrom;
180 | }
181 |
182 | - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
183 |
184 | if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
185 | NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
186 |
187 | if (![self isResponseSuccess:response]) {
188 | decisionHandler(WKNavigationResponsePolicyCancel);
189 | [self throwError: ERROR_NETWORK_ERROR withMessage: [NSString stringWithFormat: @"resource %@ in unreachable, statusCode %ld", _resource, response.statusCode]];
190 | return;
191 | }
192 | }
193 | decisionHandler(WKNavigationResponsePolicyAllow);
194 | }
195 |
196 | - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
197 | [UIView animateWithDuration: _fadeInDuration animations: ^(void) {
198 | [webview setAlpha: 1.0];
199 | }];
200 |
201 | if (_onLoad) {
202 | _onLoad(nil);
203 | }
204 |
205 | ignoreScrollEvent = false;
206 | }
207 |
208 | - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
209 | [self throwError: ERROR_ONLOADING withMessage: error.localizedDescription];
210 | }
211 |
212 | - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
213 | [self throwError: ERROR_ONLOADING withMessage: error.localizedDescription];
214 | }
215 |
216 | - (NSURL *)fileFromBundleURL {
217 | NSString *resourcePath = [_resource stringByReplacingOccurrencesOfString: @".pdf" withString: @""]; // Remove pdf extension from path if present
218 | if (![[NSBundle mainBundle] pathForResource: resourcePath ofType: @"pdf"]) {
219 | return nil;
220 | } else {
221 | return [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource: resourcePath ofType: @"pdf"]];
222 | }
223 | }
224 |
225 | - (NSURL *)fileFromDirectoryURL:(NSSearchPathDirectory)directory {
226 | NSString *directoryPath = [NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES) lastObject];
227 |
228 | return [self fileFromDirectoryPath:directoryPath];
229 | }
230 |
231 | - (NSURL *)fileFromDirectoryPath:(NSString *)directoryPath {
232 | if (directoryPath == nil) {
233 | return nil;
234 | }
235 | NSString *filePath = [directoryPath stringByAppendingPathComponent: _resource];
236 | if(![[NSFileManager defaultManager] fileExistsAtPath: filePath]) {
237 | return nil;
238 | }
239 | return [NSURL fileURLWithPath: filePath];
240 | }
241 |
242 | - (BOOL)isRequiredInputSet {
243 | if ([_resource length] == 0 || [_resourceType length] == 0) {
244 | NSString* errorMessage = [NSString stringWithFormat: @"resource: %@. resourceType: %@.", _resource, _resourceType];
245 | [self throwError: ERROR_REQUIRED_INPUT_NOT_SET withMessage: errorMessage];
246 | return NO;
247 | }
248 | return YES;
249 | }
250 |
251 | - (BOOL)isNewInput {
252 | return ![_resource isEqualToString: currentResource] ||
253 | ![_resourceType isEqualToString: currentResourceType] ||
254 | ![_resourceType isEqualToString: currentFileFrom];
255 | }
256 |
257 | - (BOOL)isSupportedResourceType {
258 | return [self isURLResource] || [self isBase64Resource] || [self isFileResource];
259 | }
260 |
261 | - (BOOL)isURLResource {
262 | return [_resourceType isEqualToString: RESOURCE_TYPE_URL];
263 | }
264 |
265 | - (BOOL)isBase64Resource {
266 | return [_resourceType isEqualToString: RESOURCE_TYPE_BASE64];
267 | }
268 |
269 | - (BOOL)isFileResource {
270 | return [_resourceType isEqualToString: RESOURCE_TYPE_FILE];
271 | }
272 |
273 | - (BOOL)isResponseSuccess: (NSHTTPURLResponse *)response {
274 | return response.statusCode >= 200 && response.statusCode <= 299;
275 | }
276 |
277 | - (void)throwError: (NSString *)title withMessage:(NSString *)message {
278 | if (_onError) {
279 | _onError(@{
280 | ERROR_MESSAGE_KEY: message,
281 | ERROR_MESSAGE_TITLE: title,
282 | });
283 | }
284 | }
285 |
286 | @end
287 |
--------------------------------------------------------------------------------
/ReactNativeViewPDF/RNPDFViewManager.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 | #import "RNPDFView.h"
4 |
5 | @interface RNPDFViewManager : RCTViewManager
6 |
7 | @property (nonatomic) RNPDFView *pdfView;
8 |
9 | @end
10 |
--------------------------------------------------------------------------------
/ReactNativeViewPDF/RNPDFViewManager.m:
--------------------------------------------------------------------------------
1 | #import "RNPDFViewManager.h"
2 | #import
3 |
4 | @implementation RNPDFViewManager
5 |
6 | RCT_EXPORT_MODULE(PDFView)
7 |
8 | RCT_CUSTOM_VIEW_PROPERTY(resource, NSString, RNPDFView) {
9 | [view setResource: json ? [RCTConvert NSString: json] : nil];
10 | }
11 |
12 | RCT_CUSTOM_VIEW_PROPERTY(resourceType, NSString, RNPDFView) {
13 | [view setResourceType: json ? [RCTConvert NSString: json] : nil];
14 | }
15 |
16 | RCT_CUSTOM_VIEW_PROPERTY(fileFrom, NSString, RNPDFView) {
17 | [view setFileFrom: json ? [RCTConvert NSString: json] : nil];
18 | }
19 |
20 | RCT_CUSTOM_VIEW_PROPERTY(textEncoding, NSString, RNPDFView) {
21 | [view setTextEncoding: json ? [RCTConvert NSString: json] : UTF_8];
22 | }
23 |
24 | RCT_CUSTOM_VIEW_PROPERTY(urlProps, NSDictionary, RNPDFView) {
25 | [view setUrlProps: json ? [RCTConvert NSDictionary: json] : nil];
26 | }
27 |
28 | RCT_CUSTOM_VIEW_PROPERTY(fadeInDuration, NSTimeInterval, RNPDFView) {
29 | [view setFadeInDuration: json ? [RCTConvert NSTimeInterval: json] : 0.0];
30 | }
31 |
32 | RCT_EXPORT_VIEW_PROPERTY(onLoad, RCTDirectEventBlock)
33 | RCT_EXPORT_VIEW_PROPERTY(onError, RCTDirectEventBlock)
34 | RCT_EXPORT_VIEW_PROPERTY(onScrolled, RCTDirectEventBlock)
35 |
36 | RCT_EXPORT_METHOD(reload: (nonnull NSNumber *)reactTag resolver: (RCTPromiseResolveBlock)resolve rejecter: (RCTPromiseRejectBlock)reject) {
37 | dispatch_async(dispatch_get_main_queue(), ^{
38 | RNPDFView *pdfView = (RNPDFView *)[self.bridge.uiManager viewForReactTag: reactTag];
39 | if (!pdfView) {
40 | reject(ERROR_INVALID_REACT_TAG, [NSString stringWithFormat: @"ReactTag passed: %@", reactTag], nil);
41 | return;
42 | }
43 | [pdfView reload];
44 | resolve(nil);
45 | });
46 | }
47 |
48 | - (instancetype)init {
49 | self = [super init];
50 | return self;
51 | }
52 |
53 | - (UIView *)view {
54 | self.pdfView = [[RNPDFView alloc] init];
55 | return self.pdfView;
56 | }
57 |
58 | + (BOOL)requiresMainQueueSetup {
59 | return YES;
60 | }
61 |
62 | @end
63 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | def safeExtGet(prop, fallback = null) {
2 | if (rootProject.ext.has(prop)) {
3 | return rootProject.ext[prop]
4 | }
5 | if (project.properties[prop]) {
6 | return project.properties[prop]
7 | }
8 | return fallback
9 | }
10 |
11 | apply plugin: 'com.android.library'
12 |
13 |
14 | android {
15 | compileSdkVersion safeExtGet('compileSdkVersion')
16 | buildToolsVersion safeExtGet('buildToolsVersion')
17 |
18 | defaultConfig {
19 | minSdkVersion safeExtGet('minSdkVersion')
20 | targetSdkVersion safeExtGet('targetSdkVersion')
21 | }
22 | lintOptions {
23 | abortOnError false
24 | }
25 | compileOptions {
26 | sourceCompatibility JavaVersion.VERSION_1_8
27 | targetCompatibility JavaVersion.VERSION_1_8
28 | }
29 | }
30 |
31 | dependencies {
32 | def pdfViewerVersion = safeExtGet('pdfViewerVersion', '2.8.2')
33 | def pdfViewerRepo = safeExtGet('pdfViewerRepo', 'com.github.barteksc')
34 |
35 | //noinspection GradleDynamicVersion
36 | implementation "com.facebook.react:react-native:+"
37 | implementation "$pdfViewerRepo:android-pdf-viewer:$pdfViewerVersion"
38 | }
39 |
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | buildToolsVersion = 28.0.3
2 | compileSdkVersion = 28
3 | minSdkVersion = 21
4 | targetSdkVersion = 28
5 | pdfViewer = 2.8.2
6 |
--------------------------------------------------------------------------------
/android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
--------------------------------------------------------------------------------
/android/src/main/java/com/rumax/reactnative/pdfviewer/AsyncDownload.java:
--------------------------------------------------------------------------------
1 | package com.rumax.reactnative.pdfviewer;
2 |
3 | /*
4 | * Created by Maksym Rusynyk on 06/03/2018.
5 | *
6 | * This source code is licensed under the MIT license
7 | */
8 |
9 | import android.content.Context;
10 | import android.net.Uri;
11 | import android.os.AsyncTask;
12 |
13 | import com.facebook.react.bridge.ReadableMap;
14 | import com.facebook.react.bridge.ReadableMapKeySetIterator;
15 | import com.facebook.react.bridge.ReadableType;
16 |
17 | import java.io.BufferedInputStream;
18 | import java.io.File;
19 | import java.io.FileOutputStream;
20 | import java.io.IOException;
21 | import java.io.InputStream;
22 | import java.io.OutputStream;
23 | import java.net.HttpURLConnection;
24 | import java.net.URL;
25 |
26 | class AsyncDownload extends AsyncTask {
27 | public static final String HTTP = "http";
28 | public static final String HTTPS = "https";
29 | public static final String CONTENT = "content";
30 | private static final int BUFF_SIZE = 8192;
31 | private static final String PROP_METHOD = "method";
32 | private static final String PROP_BODY = "body";
33 | private static final String PROP_HEADERS = "headers";
34 | private final ReadableMap urlProps;
35 | private Context context;
36 | private TaskCompleted listener;
37 | private File file;
38 | private String url;
39 | private Exception exception;
40 |
41 | AsyncDownload(Context context, String url, File file, ReadableMap urlProps, TaskCompleted listener) {
42 | this.context = context;
43 | this.listener = listener;
44 | this.file = file;
45 | this.url = url;
46 | this.urlProps = urlProps;
47 | }
48 |
49 | @Override
50 | protected void onPreExecute() {
51 | super.onPreExecute();
52 | exception = null;
53 | }
54 |
55 | private void copyAndFlush(InputStream input, OutputStream output) throws IOException {
56 | int count;
57 | byte data[] = new byte[BUFF_SIZE];
58 |
59 | while ((count = input.read(data)) != -1) {
60 | output.write(data, 0, count);
61 | }
62 |
63 | output.flush();
64 | }
65 |
66 | private Void handleContentUri(Uri uri) {
67 | try (
68 | InputStream input = context.getContentResolver().openInputStream(uri);
69 | OutputStream output = new FileOutputStream(file)
70 | ) {
71 | copyAndFlush(input, output);
72 | } catch (Exception e) {
73 | exception = e;
74 | }
75 | return null;
76 | }
77 |
78 | @Override
79 | protected Void doInBackground(Void... params) {
80 | Uri uri = Uri.parse(this.url);
81 | String scheme = uri.getScheme();
82 |
83 | if (this.url.equalsIgnoreCase("") || scheme == null) {
84 | exception = new IOException("Invalid or empty url provided");
85 | return null;
86 | }
87 |
88 | if (scheme.equalsIgnoreCase(CONTENT)) {
89 | return handleContentUri(uri);
90 | }
91 |
92 | URL url;
93 | HttpURLConnection connection;
94 |
95 | try {
96 | url = new URL(this.url);
97 | String protocol = url.getProtocol();
98 | if (!protocol.equalsIgnoreCase(HTTP) && !protocol.equalsIgnoreCase(HTTPS)) {
99 | exception = new IOException("Protocol \"" + protocol + "\" is not supported");
100 | return null;
101 | }
102 | connection = (HttpURLConnection) url.openConnection();
103 | enrichWithUrlProps(connection);
104 | connection.connect();
105 | } catch (Exception e) {
106 | exception = e;
107 | return null;
108 | }
109 |
110 | try (
111 | InputStream input = new BufferedInputStream(connection.getInputStream(), BUFF_SIZE);
112 | OutputStream output = new FileOutputStream(file)
113 | ) {
114 | copyAndFlush(input, output);
115 | } catch (IOException e) {
116 | exception = e;
117 | }
118 |
119 | return null;
120 | }
121 |
122 | @Override
123 | protected void onPostExecute(Void param) {
124 | listener.onComplete(exception);
125 | }
126 |
127 | private void enrichWithUrlProps(HttpURLConnection connection) throws IOException {
128 | if (urlProps == null) {
129 | return;
130 | }
131 | setRequestMethod(connection);
132 | setRequestHeaders(connection);
133 | setRequestBody(connection);
134 | }
135 |
136 | private void setRequestMethod(HttpURLConnection connection) throws IOException {
137 | String method = "GET";
138 |
139 | if (urlProps.hasKey(PROP_METHOD)) {
140 | if (urlProps.getType(PROP_METHOD) != ReadableType.String) {
141 | throw new IOException("Invalid method type. String is expected");
142 | }
143 | method = urlProps.getString(PROP_METHOD);
144 | }
145 |
146 | connection.setRequestMethod(method);
147 | }
148 |
149 | private void setRequestHeaders(HttpURLConnection connection) throws IOException {
150 | if (!urlProps.hasKey(PROP_HEADERS)) {
151 | return;
152 | }
153 |
154 | ReadableMap headers = urlProps.getMap(PROP_HEADERS);
155 |
156 | if (headers == null) {
157 | return;
158 | }
159 |
160 | ReadableMapKeySetIterator iterator = headers.keySetIterator();
161 |
162 | while (iterator.hasNextKey()) {
163 | String key = iterator.nextKey();
164 |
165 | if (headers.getType(key) == ReadableType.String) {
166 | connection.setRequestProperty(key, headers.getString(key));
167 | } else {
168 | throw new IOException("Invalid header key type. String is expected for " + key);
169 | }
170 | }
171 | }
172 |
173 | private void setRequestBody(HttpURLConnection connection) throws IOException {
174 | if (!urlProps.hasKey(PROP_BODY)) {
175 | return;
176 | }
177 |
178 | if (urlProps.getType(PROP_BODY) != ReadableType.String) {
179 | throw new IOException("Invalid body type. String is expected");
180 | }
181 |
182 | String body = urlProps.getString(PROP_BODY);
183 |
184 | if (body.getBytes().length > 0) {
185 | connection.setDoOutput(true);
186 | connection.setRequestProperty("Content-Length", "" + body.getBytes().length);
187 | try (OutputStream writer = connection.getOutputStream()) {
188 | writer.write(body.getBytes());
189 | writer.flush();
190 | }
191 | }
192 | }
193 |
194 | public interface TaskCompleted {
195 | void onComplete(Exception ex);
196 | }
197 | }
198 |
--------------------------------------------------------------------------------
/android/src/main/java/com/rumax/reactnative/pdfviewer/Errors.java:
--------------------------------------------------------------------------------
1 | package com.rumax.reactnative.pdfviewer;
2 |
3 | public enum Errors {
4 | E_NO_RESOURCE("source is not defined"),
5 | E_NO_RESOURCE_TYPE("resourceType is not defined"),
6 | E_INVALID_RESOURCE_TYPE("resourceType is Invalid"),
7 | E_INVALID_BASE64("data is not in valid Base64 scheme"),
8 | E_DELETE_FILE("Cannot delete downloaded file");
9 |
10 | private final String code;
11 |
12 | Errors(String code) {
13 | this.code = code;
14 | }
15 |
16 | public String getCode() {
17 | return code;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/android/src/main/java/com/rumax/reactnative/pdfviewer/PDFView.java:
--------------------------------------------------------------------------------
1 | package com.rumax.reactnative.pdfviewer;
2 |
3 | /*
4 | * Created by Maksym Rusynyk on 06/03/2018.
5 | *
6 | * This source code is licensed under the MIT license
7 | */
8 |
9 | import android.content.res.AssetManager;
10 | import android.util.Base64;
11 | import android.view.animation.AlphaAnimation;
12 | import android.view.animation.DecelerateInterpolator;
13 |
14 | import com.facebook.react.bridge.Arguments;
15 | import com.facebook.react.bridge.ReactContext;
16 | import com.facebook.react.bridge.ReadableMap;
17 | import com.facebook.react.bridge.WritableMap;
18 | import com.facebook.react.uimanager.ThemedReactContext;
19 | import com.facebook.react.uimanager.events.RCTEventEmitter;
20 | import com.github.barteksc.pdfviewer.listener.OnErrorListener;
21 | import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
22 | import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
23 | import com.github.barteksc.pdfviewer.listener.OnPageScrollListener;
24 |
25 | import java.io.File;
26 | import java.io.FileInputStream;
27 | import java.io.IOException;
28 | import java.io.InputStream;
29 |
30 | public class PDFView extends com.github.barteksc.pdfviewer.PDFView implements
31 | OnErrorListener,
32 | OnPageChangeListener,
33 | OnPageScrollListener,
34 | OnLoadCompleteListener {
35 | public final static String EVENT_ON_LOAD = "onLoad";
36 | public final static String EVENT_ON_ERROR = "onError";
37 | public final static String EVENT_ON_PAGE_CHANGED = "onPageChanged";
38 | public final static String EVENT_ON_SCROLLED = "onScrolled";
39 | private ThemedReactContext context;
40 | private String resource;
41 | private File downloadedFile;
42 | private AsyncDownload downloadTask = null;
43 | private String resourceType = null;
44 | private Configurator configurator = null;
45 | private boolean sourceChanged = true;
46 | private ReadableMap urlProps;
47 | private int fadeInDuration = 0;
48 | private boolean enableAnnotations = false;
49 | private float lastPositionOffset = 0;
50 |
51 | public PDFView(ThemedReactContext context) {
52 | super(context, null);
53 | this.context = context;
54 | }
55 |
56 | @Override
57 | public void loadComplete(int numberOfPages) {
58 | AlphaAnimation fadeIn = new AlphaAnimation(0, 1);
59 | fadeIn.setInterpolator(new DecelerateInterpolator());
60 | fadeIn.setDuration(fadeInDuration);
61 | this.setAlpha(1);
62 | this.startAnimation(fadeIn);
63 |
64 | reactNativeMessageEvent(EVENT_ON_LOAD, null);
65 | }
66 |
67 | @Override
68 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
69 | super.onLayout(changed, left, top, right, bottom);
70 | this.setClipToOutline(true);
71 | }
72 |
73 | @Override
74 | public void onError(Throwable t) {
75 | reactNativeMessageEvent(EVENT_ON_ERROR, "error: " + t.getMessage());
76 | }
77 |
78 | @Override
79 | public void onPageChanged(int page, int pageCount) {
80 | WritableMap event = Arguments.createMap();
81 | event.putInt("page", page);
82 | event.putInt("pageCount", pageCount);
83 | reactNativeEvent(EVENT_ON_PAGE_CHANGED, event);
84 | }
85 |
86 | @Override
87 | public void onPageScrolled(int page, float positionOffset) {
88 | if (lastPositionOffset != positionOffset && (positionOffset == 0 || positionOffset == 1)) {
89 | // Only 0 and 1 are currently supported
90 | lastPositionOffset = positionOffset;
91 | WritableMap event = Arguments.createMap();
92 | event.putDouble("offset", positionOffset);
93 | reactNativeEvent(EVENT_ON_SCROLLED, event);
94 | }
95 | }
96 |
97 | private void reactNativeMessageEvent(String eventName, String message) {
98 | WritableMap event = Arguments.createMap();
99 | event.putString("message", message);
100 | reactNativeEvent(eventName, event);
101 | }
102 |
103 | private void reactNativeEvent(String eventName, WritableMap event) {
104 | ReactContext reactContext = (ReactContext) this.getContext();
105 | reactContext
106 | .getJSModule(RCTEventEmitter.class)
107 | .receiveEvent(this.getId(), eventName, event);
108 | }
109 |
110 | private void setupAndLoad() {
111 | lastPositionOffset = 0;
112 | this.setAlpha(0);
113 | configurator
114 | .defaultPage(0)
115 | .swipeHorizontal(false)
116 | .onLoad(this)
117 | .onError(this)
118 | .onPageChange(this)
119 | .onPageScroll(this)
120 | .spacing(10)
121 | .enableAnnotationRendering(enableAnnotations)
122 | .load();
123 | sourceChanged = false;
124 | }
125 |
126 | private void renderFromFile(String filePath) {
127 | InputStream input;
128 |
129 | try {
130 | if (filePath.startsWith("/")) { // absolute path, using FS
131 | input = new FileInputStream(new File(filePath));
132 | } else { // from assets
133 | AssetManager assetManager = context.getAssets();
134 | input = assetManager.open(filePath, AssetManager.ACCESS_BUFFER);
135 | }
136 |
137 | configurator = this.fromStream(input);
138 | setupAndLoad();
139 | } catch (IOException e) {
140 | onError(e);
141 | }
142 | }
143 |
144 | private void renderFromBase64() {
145 | try {
146 | byte[] bytes = Base64.decode(resource, 0);
147 | configurator = this.fromBytes(bytes);
148 | setupAndLoad();
149 | } catch (IllegalArgumentException e) {
150 | onError(new IOException(Errors.E_INVALID_BASE64.getCode()));
151 | }
152 | }
153 |
154 | private void renderFromUrl() {
155 | File dir = context.getCacheDir();
156 | try {
157 | downloadedFile = File.createTempFile("pdfDocument", "pdf", dir);
158 | } catch (IOException e) {
159 | onError(e);
160 | return;
161 | }
162 |
163 | downloadTask = new AsyncDownload(context, resource, downloadedFile, urlProps, new AsyncDownload.TaskCompleted() {
164 | @Override
165 | public void onComplete(Exception ex) {
166 | if (ex == null) {
167 | renderFromFile(downloadedFile.getAbsolutePath());
168 | } else {
169 | cleanDownloadedFile();
170 | onError(ex);
171 | }
172 | }
173 | });
174 | downloadTask.execute();
175 | }
176 |
177 | public void render() {
178 | cleanup();
179 |
180 | if (resource == null) {
181 | onError(new IOException(Errors.E_NO_RESOURCE.getCode()));
182 | return;
183 | }
184 |
185 | if (resourceType == null) {
186 | onError(new IOException(Errors.E_NO_RESOURCE_TYPE.getCode()));
187 | return;
188 | }
189 |
190 | if (!sourceChanged) {
191 | return;
192 | }
193 |
194 | switch (resourceType) {
195 | case "url":
196 | renderFromUrl();
197 | break;
198 | case "base64":
199 | renderFromBase64();
200 | break;
201 | case "file":
202 | renderFromFile(resource);
203 | break;
204 | default:
205 | onError(new IOException(Errors.E_INVALID_RESOURCE_TYPE.getCode() + resourceType));
206 | break;
207 | }
208 | }
209 |
210 | private void cleanup() {
211 | if (downloadTask != null) {
212 | downloadTask.cancel(true);
213 | }
214 | cleanDownloadedFile();
215 | }
216 |
217 | private void cleanDownloadedFile() {
218 | if (downloadedFile != null) {
219 | if (!downloadedFile.delete()) {
220 | onError(new IOException(Errors.E_DELETE_FILE.getCode()));
221 | }
222 | downloadedFile = null;
223 | }
224 | }
225 |
226 | private static boolean isDifferent(String str1, String str2) {
227 | if (str1 == null || str2 == null) {
228 | return true;
229 | }
230 |
231 | return !str1.equals(str2);
232 | }
233 |
234 | public void setResource(String resource) {
235 | if (isDifferent(resource, this.resource)) {
236 | sourceChanged = true;
237 | }
238 | this.resource = resource;
239 | }
240 |
241 | public void setResourceType(String resourceType) {
242 | if (isDifferent(resourceType, this.resourceType)) {
243 | sourceChanged = true;
244 | }
245 | this.resourceType = resourceType;
246 | }
247 |
248 | public void onDrop() {
249 | cleanup();
250 | sourceChanged = true;
251 | }
252 |
253 | public void setUrlProps(ReadableMap props) {
254 | this.urlProps = props;
255 | }
256 |
257 | public void setFadeInDuration(int duration) {
258 | this.fadeInDuration = duration;
259 | }
260 |
261 | public void setEnableAnnotations(boolean enableAnnotations) {
262 | this.enableAnnotations = enableAnnotations;
263 | }
264 |
265 | public void reload() {
266 | sourceChanged = true;
267 | render();
268 | }
269 | }
270 |
--------------------------------------------------------------------------------
/android/src/main/java/com/rumax/reactnative/pdfviewer/PDFViewManager.java:
--------------------------------------------------------------------------------
1 | package com.rumax.reactnative.pdfviewer;
2 |
3 | /*
4 | * Created by Maksym Rusynyk on 06/03/2018.
5 | *
6 | * This source code is licensed under the MIT license
7 | */
8 |
9 | import com.facebook.react.bridge.ReactApplicationContext;
10 | import com.facebook.react.bridge.ReadableArray;
11 | import com.facebook.react.bridge.ReadableMap;
12 | import com.facebook.react.common.MapBuilder;
13 | import com.facebook.react.uimanager.SimpleViewManager;
14 | import com.facebook.react.uimanager.ThemedReactContext;
15 | import com.facebook.react.uimanager.annotations.ReactProp;
16 |
17 | import java.util.Map;
18 |
19 | import javax.annotation.Nullable;
20 |
21 | public class PDFViewManager extends SimpleViewManager {
22 | private static final String REACT_CLASS = "PDFView";
23 | private final static String EVENT_BUBBLED = "bubbled";
24 | private static final int COMMAND_RELOAD = 1;
25 |
26 | @SuppressWarnings("unused")
27 | PDFViewManager(ReactApplicationContext context) {}
28 |
29 | @Nullable @Override
30 | public Map getExportedCustomBubblingEventTypeConstants() {
31 | return MapBuilder.builder()
32 | .put(
33 | PDFView.EVENT_ON_LOAD,
34 | MapBuilder.of(
35 | "phasedRegistrationNames",
36 | MapBuilder.of(EVENT_BUBBLED, PDFView.EVENT_ON_LOAD)
37 | )
38 | )
39 | .put(
40 | PDFView.EVENT_ON_ERROR,
41 | MapBuilder.of(
42 | "phasedRegistrationNames",
43 | MapBuilder.of(EVENT_BUBBLED, PDFView.EVENT_ON_ERROR)
44 | )
45 | )
46 | .put(
47 | PDFView.EVENT_ON_PAGE_CHANGED,
48 | MapBuilder.of(
49 | "phasedRegistrationNames",
50 | MapBuilder.of(EVENT_BUBBLED, PDFView.EVENT_ON_PAGE_CHANGED)
51 | )
52 | )
53 | .put(
54 | PDFView.EVENT_ON_SCROLLED,
55 | MapBuilder.of(
56 | "phasedRegistrationNames",
57 | MapBuilder.of(EVENT_BUBBLED, PDFView.EVENT_ON_SCROLLED)
58 | )
59 | )
60 | .build();
61 | }
62 |
63 | @Override
64 | public String getName() {
65 | return REACT_CLASS;
66 | }
67 |
68 | @Override
69 | public PDFView createViewInstance(ThemedReactContext context) {
70 | return new PDFView(context);
71 | }
72 |
73 | @Override
74 | public void onDropViewInstance(PDFView pdfView) {
75 | pdfView.onDrop();
76 | }
77 |
78 | @ReactProp(name = "resource")
79 | public void setResource(PDFView pdfView, String resource) {
80 | pdfView.setResource(resource);
81 | }
82 |
83 | @ReactProp(name = "resourceType")
84 | public void setResourceType(PDFView pdfView, String resourceType) {
85 | pdfView.setResourceType(resourceType);
86 | }
87 |
88 | @ReactProp(name = "fileFrom")
89 | public void setFileFrom(PDFView pdfView, String fileFrom) {
90 | // iOS specific, ignoring
91 | }
92 |
93 | @ReactProp(name = "textEncoding")
94 | public void setTextEncoding(PDFView pdfView, String textEncoding) {
95 | // iOS specific, ignoring
96 | }
97 |
98 | @ReactProp(name = "urlProps")
99 | public void setUrlProps(PDFView pdfView, final ReadableMap props) {
100 | pdfView.setUrlProps(props);
101 | }
102 |
103 | @ReactProp(name = "fadeInDuration")
104 | public void setFadeInDuration(PDFView pdfView, int duration) {
105 | pdfView.setFadeInDuration(duration);
106 | }
107 |
108 | @ReactProp(name = "enableAnnotations")
109 | public void setEnableAnnotations(PDFView pdfView, boolean enableAnnotations) {
110 | pdfView.setEnableAnnotations(enableAnnotations);
111 | }
112 |
113 | @Override
114 | public void onAfterUpdateTransaction(PDFView pdfView) {
115 | super.onAfterUpdateTransaction(pdfView);
116 | pdfView.render();
117 | }
118 |
119 | @Override
120 | public Map getCommandsMap() {
121 | return MapBuilder.of("reload", COMMAND_RELOAD);
122 | }
123 |
124 | @Override
125 | public void receiveCommand(final PDFView view, int command, final ReadableArray args) {
126 | switch (command) {
127 | case COMMAND_RELOAD: {
128 | view.reload();
129 | break;
130 | }
131 | default: {
132 | break;
133 | }
134 | }
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/android/src/main/java/com/rumax/reactnative/pdfviewer/PDFViewPackage.java:
--------------------------------------------------------------------------------
1 | package com.rumax.reactnative.pdfviewer;
2 |
3 | /*
4 | * Copyright (c) <2018>
5 | *
6 | * This source code is licensed under the MIT license
7 | */
8 |
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.react.bridge.NativeModule;
11 | import com.facebook.react.bridge.ReactApplicationContext;
12 | import com.facebook.react.uimanager.ViewManager;
13 |
14 | import java.util.Collections;
15 | import java.util.List;
16 |
17 | public class PDFViewPackage implements ReactPackage {
18 | @Override
19 | public List createNativeModules(ReactApplicationContext reactContext) {
20 | return Collections.emptyList();
21 | }
22 |
23 | @SuppressWarnings("rawtypes")
24 | public List createViewManagers(ReactApplicationContext reactContext) {
25 | return Collections.singletonList(new PDFViewManager(reactContext));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/demo/.buckconfig:
--------------------------------------------------------------------------------
1 |
2 | [android]
3 | target = Google Inc.:Google APIs:23
4 |
5 | [maven_repositories]
6 | central = https://repo1.maven.org/maven2
7 |
--------------------------------------------------------------------------------
/demo/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | extends: '@react-native-community',
4 | parser: '@typescript-eslint/parser',
5 | plugins: ['@typescript-eslint'],
6 | overrides: [
7 | {
8 | files: ['*.ts', '*.tsx'],
9 | rules: {
10 | '@typescript-eslint/no-shadow': ['error'],
11 | 'no-shadow': 'off',
12 | 'no-undef': 'off',
13 | },
14 | },
15 | ],
16 | };
17 |
--------------------------------------------------------------------------------
/demo/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # Xcode
6 | #
7 | build/
8 | *.pbxuser
9 | !default.pbxuser
10 | *.mode1v3
11 | !default.mode1v3
12 | *.mode2v3
13 | !default.mode2v3
14 | *.perspectivev3
15 | !default.perspectivev3
16 | xcuserdata
17 | *.xccheckout
18 | *.moved-aside
19 | DerivedData
20 | *.hmap
21 | *.ipa
22 | *.xcuserstate
23 | ios/.xcode.env.local
24 |
25 | # Android/IntelliJ
26 | #
27 | build/
28 | .idea
29 | .gradle
30 | local.properties
31 | *.iml
32 | *.hprof
33 |
34 | # node.js
35 | #
36 | node_modules/
37 | npm-debug.log
38 | yarn-error.log
39 |
40 | # BUCK
41 | buck-out/
42 | \.buckd/
43 | *.keystore
44 | !debug.keystore
45 |
46 | # fastlane
47 | #
48 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
49 | # screenshots whenever they are needed.
50 | # For more information about the recommended setup visit:
51 | # https://docs.fastlane.tools/best-practices/source-control/
52 |
53 | **/fastlane/report.xml
54 | **/fastlane/Preview.html
55 | **/fastlane/screenshots
56 | **/fastlane/test_output
57 |
58 | # Bundle artifact
59 | *.jsbundle
60 |
61 | # Ruby / CocoaPods
62 | /ios/Pods/
63 | /vendor/bundle/
64 |
--------------------------------------------------------------------------------
/demo/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | arrowParens: 'avoid',
3 | bracketSameLine: true,
4 | bracketSpacing: true,
5 | singleQuote: true,
6 | trailingComma: 'all',
7 | };
8 |
--------------------------------------------------------------------------------
/demo/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/demo/App.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Sample React Native App
3 | * https://github.com/facebook/react-native
4 | *
5 | * Generated with the TypeScript template
6 | * https://github.com/react-native-community/react-native-template-typescript
7 | *
8 | * @format
9 | */
10 |
11 | import React, {type PropsWithChildren} from 'react';
12 | import {
13 | SafeAreaView,
14 | ScrollView,
15 | StatusBar,
16 | StyleSheet,
17 | Text,
18 | useColorScheme,
19 | View,
20 | } from 'react-native';
21 |
22 | import {
23 | Colors,
24 | DebugInstructions,
25 | Header,
26 | LearnMoreLinks,
27 | ReloadInstructions,
28 | } from 'react-native/Libraries/NewAppScreen';
29 |
30 | const Section: React.FC<
31 | PropsWithChildren<{
32 | title: string;
33 | }>
34 | > = ({children, title}) => {
35 | const isDarkMode = useColorScheme() === 'dark';
36 | return (
37 |
38 |
45 | {title}
46 |
47 |
54 | {children}
55 |
56 |
57 | );
58 | };
59 |
60 | const App = () => {
61 | const isDarkMode = useColorScheme() === 'dark';
62 |
63 | const backgroundStyle = {
64 | backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
65 | };
66 |
67 | return (
68 |
69 |
70 |
73 |
74 |
78 |
79 | Edit App.tsx to change this
80 | screen and then come back to see your edits.
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | Read the docs to discover what to do next:
90 |
91 |
92 |
93 |
94 |
95 | );
96 | };
97 |
98 | const styles = StyleSheet.create({
99 | sectionContainer: {
100 | marginTop: 32,
101 | paddingHorizontal: 24,
102 | },
103 | sectionTitle: {
104 | fontSize: 24,
105 | fontWeight: '600',
106 | },
107 | sectionDescription: {
108 | marginTop: 8,
109 | fontSize: 18,
110 | fontWeight: '400',
111 | },
112 | highlight: {
113 | fontWeight: '700',
114 | },
115 | });
116 |
117 | export default App;
118 |
--------------------------------------------------------------------------------
/demo/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
4 | ruby '2.7.5'
5 |
6 | gem 'cocoapods', '~> 1.11', '>= 1.11.2'
7 |
--------------------------------------------------------------------------------
/demo/_bundle/config:
--------------------------------------------------------------------------------
1 | BUNDLE_PATH: "vendor/bundle"
2 | BUNDLE_FORCE_RUBY_PLATFORM: 1
3 |
--------------------------------------------------------------------------------
/demo/_ruby-version:
--------------------------------------------------------------------------------
1 | 2.7.5
2 |
--------------------------------------------------------------------------------
/demo/android/app/_BUCK:
--------------------------------------------------------------------------------
1 | # To learn about Buck see [Docs](https://buckbuild.com/).
2 | # To run your application with Buck:
3 | # - install Buck
4 | # - `npm start` - to start the packager
5 | # - `cd android`
6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
8 | # - `buck install -r android/app` - compile, install and run application
9 | #
10 |
11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets")
12 |
13 | lib_deps = []
14 |
15 | create_aar_targets(glob(["libs/*.aar"]))
16 |
17 | create_jar_targets(glob(["libs/*.jar"]))
18 |
19 | android_library(
20 | name = "all-libs",
21 | exported_deps = lib_deps,
22 | )
23 |
24 | android_library(
25 | name = "app-code",
26 | srcs = glob([
27 | "src/main/java/**/*.java",
28 | ]),
29 | deps = [
30 | ":all-libs",
31 | ":build_config",
32 | ":res",
33 | ],
34 | )
35 |
36 | android_build_config(
37 | name = "build_config",
38 | package = "com.demo",
39 | )
40 |
41 | android_resource(
42 | name = "res",
43 | package = "com.demo",
44 | res = "src/main/res",
45 | )
46 |
47 | android_binary(
48 | name = "app",
49 | keystore = "//android/keystores:debug",
50 | manifest = "src/main/AndroidManifest.xml",
51 | package_type = "debug",
52 | deps = [
53 | ":app-code",
54 | ],
55 | )
56 |
--------------------------------------------------------------------------------
/demo/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 |
5 | /**
6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
7 | * and bundleReleaseJsAndAssets).
8 | * These basically call `react-native bundle` with the correct arguments during the Android build
9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
10 | * bundle directly from the development server. Below you can see all the possible configurations
11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
12 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
13 | *
14 | * project.ext.react = [
15 | * // the name of the generated asset file containing your JS bundle
16 | * bundleAssetName: "index.android.bundle",
17 | *
18 | * // the entry file for bundle generation. If none specified and
19 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is
20 | * // default. Can be overridden with ENTRY_FILE environment variable.
21 | * entryFile: "index.android.js",
22 | *
23 | * // https://reactnative.dev/docs/performance#enable-the-ram-format
24 | * bundleCommand: "ram-bundle",
25 | *
26 | * // whether to bundle JS and assets in debug mode
27 | * bundleInDebug: false,
28 | *
29 | * // whether to bundle JS and assets in release mode
30 | * bundleInRelease: true,
31 | *
32 | * // whether to bundle JS and assets in another build variant (if configured).
33 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
34 | * // The configuration property can be in the following formats
35 | * // 'bundleIn${productFlavor}${buildType}'
36 | * // 'bundleIn${buildType}'
37 | * // bundleInFreeDebug: true,
38 | * // bundleInPaidRelease: true,
39 | * // bundleInBeta: true,
40 | *
41 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
42 | * // for example: to disable dev mode in the staging build type (if configured)
43 | * devDisabledInStaging: true,
44 | * // The configuration property can be in the following formats
45 | * // 'devDisabledIn${productFlavor}${buildType}'
46 | * // 'devDisabledIn${buildType}'
47 | *
48 | * // the root of your project, i.e. where "package.json" lives
49 | * root: "../../",
50 | *
51 | * // where to put the JS bundle asset in debug mode
52 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
53 | *
54 | * // where to put the JS bundle asset in release mode
55 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
56 | *
57 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
58 | * // require('./image.png')), in debug mode
59 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
60 | *
61 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
62 | * // require('./image.png')), in release mode
63 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
64 | *
65 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
66 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
67 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
68 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
69 | * // for example, you might want to remove it from here.
70 | * inputExcludes: ["android/**", "ios/**"],
71 | *
72 | * // override which node gets called and with what additional arguments
73 | * nodeExecutableAndArgs: ["node"],
74 | *
75 | * // supply additional arguments to the packager
76 | * extraPackagerArgs: []
77 | * ]
78 | */
79 |
80 | project.ext.react = [
81 | enableHermes: false, // clean and rebuild if changing
82 | ]
83 |
84 | apply from: "../../node_modules/react-native/react.gradle"
85 |
86 | /**
87 | * Set this to true to create two separate APKs instead of one:
88 | * - An APK that only works on ARM devices
89 | * - An APK that only works on x86 devices
90 | * The advantage is the size of the APK is reduced by about 4MB.
91 | * Upload all the APKs to the Play Store and people will download
92 | * the correct one based on the CPU architecture of their device.
93 | */
94 | def enableSeparateBuildPerCPUArchitecture = false
95 |
96 | /**
97 | * Run Proguard to shrink the Java bytecode in release builds.
98 | */
99 | def enableProguardInReleaseBuilds = false
100 |
101 | /**
102 | * The preferred build flavor of JavaScriptCore.
103 | *
104 | * For example, to use the international variant, you can use:
105 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
106 | *
107 | * The international variant includes ICU i18n library and necessary data
108 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
109 | * give correct results when using with locales other than en-US. Note that
110 | * this variant is about 6MiB larger per architecture than default.
111 | */
112 | def jscFlavor = 'org.webkit:android-jsc:+'
113 |
114 | /**
115 | * Whether to enable the Hermes VM.
116 | *
117 | * This should be set on project.ext.react and that value will be read here. If it is not set
118 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
119 | * and the benefits of using Hermes will therefore be sharply reduced.
120 | */
121 | def enableHermes = project.ext.react.get("enableHermes", false);
122 |
123 | /**
124 | * Architectures to build native code for.
125 | */
126 | def reactNativeArchitectures() {
127 | def value = project.getProperties().get("reactNativeArchitectures")
128 | return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
129 | }
130 |
131 | android {
132 | ndkVersion rootProject.ext.ndkVersion
133 |
134 | compileSdkVersion rootProject.ext.compileSdkVersion
135 |
136 | defaultConfig {
137 | applicationId "com.demo"
138 | minSdkVersion rootProject.ext.minSdkVersion
139 | targetSdkVersion rootProject.ext.targetSdkVersion
140 | versionCode 1
141 | versionName "1.0"
142 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
143 |
144 | if (isNewArchitectureEnabled()) {
145 | // We configure the NDK build only if you decide to opt-in for the New Architecture.
146 | externalNativeBuild {
147 | ndkBuild {
148 | arguments "APP_PLATFORM=android-21",
149 | "APP_STL=c++_shared",
150 | "NDK_TOOLCHAIN_VERSION=clang",
151 | "GENERATED_SRC_DIR=$buildDir/generated/source",
152 | "PROJECT_BUILD_DIR=$buildDir",
153 | "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
154 | "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
155 | "NODE_MODULES_DIR=$rootDir/../node_modules"
156 | cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
157 | cppFlags "-std=c++17"
158 | // Make sure this target name is the same you specify inside the
159 | // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
160 | targets "demo_appmodules"
161 | }
162 | }
163 | if (!enableSeparateBuildPerCPUArchitecture) {
164 | ndk {
165 | abiFilters (*reactNativeArchitectures())
166 | }
167 | }
168 | }
169 | }
170 |
171 | if (isNewArchitectureEnabled()) {
172 | // We configure the NDK build only if you decide to opt-in for the New Architecture.
173 | externalNativeBuild {
174 | ndkBuild {
175 | path "$projectDir/src/main/jni/Android.mk"
176 | }
177 | }
178 | def reactAndroidProjectDir = project(':ReactAndroid').projectDir
179 | def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
180 | dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
181 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
182 | into("$buildDir/react-ndk/exported")
183 | }
184 | def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
185 | dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
186 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
187 | into("$buildDir/react-ndk/exported")
188 | }
189 | afterEvaluate {
190 | // If you wish to add a custom TurboModule or component locally,
191 | // you should uncomment this line.
192 | // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
193 | preDebugBuild.dependsOn(packageReactNdkDebugLibs)
194 | preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
195 |
196 | // Due to a bug inside AGP, we have to explicitly set a dependency
197 | // between configureNdkBuild* tasks and the preBuild tasks.
198 | // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
199 | configureNdkBuildRelease.dependsOn(preReleaseBuild)
200 | configureNdkBuildDebug.dependsOn(preDebugBuild)
201 | reactNativeArchitectures().each { architecture ->
202 | tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
203 | dependsOn("preDebugBuild")
204 | }
205 | tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
206 | dependsOn("preReleaseBuild")
207 | }
208 | }
209 | }
210 | }
211 |
212 | splits {
213 | abi {
214 | reset()
215 | enable enableSeparateBuildPerCPUArchitecture
216 | universalApk false // If true, also generate a universal APK
217 | include (*reactNativeArchitectures())
218 | }
219 | }
220 | signingConfigs {
221 | debug {
222 | storeFile file('debug.keystore')
223 | storePassword 'android'
224 | keyAlias 'androiddebugkey'
225 | keyPassword 'android'
226 | }
227 | }
228 | buildTypes {
229 | debug {
230 | signingConfig signingConfigs.debug
231 | }
232 | release {
233 | // Caution! In production, you need to generate your own keystore file.
234 | // see https://reactnative.dev/docs/signed-apk-android.
235 | signingConfig signingConfigs.debug
236 | minifyEnabled enableProguardInReleaseBuilds
237 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
238 | }
239 | }
240 |
241 | packagingOptions {
242 | pickFirst "lib/armeabi-v7a/libc++_shared.so"
243 | pickFirst "lib/arm64-v8a/libc++_shared.so"
244 | pickFirst "lib/x86/libc++_shared.so"
245 | pickFirst "lib/x86_64/libc++_shared.so"
246 | }
247 |
248 | // applicationVariants are e.g. debug, release
249 | applicationVariants.all { variant ->
250 | variant.outputs.each { output ->
251 | // For each separate APK per architecture, set a unique version code as described here:
252 | // https://developer.android.com/studio/build/configure-apk-splits.html
253 | // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
254 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
255 | def abi = output.getFilter(OutputFile.ABI)
256 | if (abi != null) { // null for the universal-debug, universal-release variants
257 | output.versionCodeOverride =
258 | defaultConfig.versionCode * 1000 + versionCodes.get(abi)
259 | }
260 |
261 | }
262 | }
263 | }
264 |
265 | dependencies {
266 | implementation fileTree(dir: "libs", include: ["*.jar"])
267 |
268 | //noinspection GradleDynamicVersion
269 | implementation "com.facebook.react:react-native:+" // From node_modules
270 |
271 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
272 |
273 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
274 | exclude group:'com.facebook.fbjni'
275 | }
276 |
277 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
278 | exclude group:'com.facebook.flipper'
279 | exclude group:'com.squareup.okhttp3', module:'okhttp'
280 | }
281 |
282 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
283 | exclude group:'com.facebook.flipper'
284 | }
285 |
286 | if (enableHermes) {
287 | //noinspection GradleDynamicVersion
288 | implementation("com.facebook.react:hermes-engine:+") { // From node_modules
289 | exclude group:'com.facebook.fbjni'
290 | }
291 | } else {
292 | implementation jscFlavor
293 | }
294 | }
295 |
296 | if (isNewArchitectureEnabled()) {
297 | // If new architecture is enabled, we let you build RN from source
298 | // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
299 | // This will be applied to all the imported transtitive dependency.
300 | configurations.all {
301 | resolutionStrategy.dependencySubstitution {
302 | substitute(module("com.facebook.react:react-native"))
303 | .using(project(":ReactAndroid"))
304 | .because("On New Architecture we're building React Native from source")
305 | substitute(module("com.facebook.react:hermes-engine"))
306 | .using(project(":ReactAndroid:hermes-engine"))
307 | .because("On New Architecture we're building Hermes from source")
308 | }
309 | }
310 | }
311 |
312 | // Run this once to be able to run the application with BUCK
313 | // puts all compile dependencies into folder libs for BUCK to use
314 | task copyDownloadableDepsToLibs(type: Copy) {
315 | from configurations.implementation
316 | into 'libs'
317 | }
318 |
319 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
320 |
321 | def isNewArchitectureEnabled() {
322 | // To opt-in for the New Architecture, you can either:
323 | // - Set `newArchEnabled` to true inside the `gradle.properties` file
324 | // - Invoke gradle with `-newArchEnabled=true`
325 | // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
326 | return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
327 | }
328 |
--------------------------------------------------------------------------------
/demo/android/app/build_defs.bzl:
--------------------------------------------------------------------------------
1 | """Helper definitions to glob .aar and .jar targets"""
2 |
3 | def create_aar_targets(aarfiles):
4 | for aarfile in aarfiles:
5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
6 | lib_deps.append(":" + name)
7 | android_prebuilt_aar(
8 | name = name,
9 | aar = aarfile,
10 | )
11 |
12 | def create_jar_targets(jarfiles):
13 | for jarfile in jarfiles:
14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
15 | lib_deps.append(":" + name)
16 | prebuilt_jar(
17 | name = name,
18 | binary_jar = jarfile,
19 | )
20 |
--------------------------------------------------------------------------------
/demo/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/debug.keystore
--------------------------------------------------------------------------------
/demo/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
--------------------------------------------------------------------------------
/demo/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/demo/android/app/src/debug/java/com/demo/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Meta Platforms, Inc. and affiliates.
3 | *
4 | *
This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.demo;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
22 | import com.facebook.react.ReactInstanceEventListener;
23 | import com.facebook.react.ReactInstanceManager;
24 | import com.facebook.react.bridge.ReactContext;
25 | import com.facebook.react.modules.network.NetworkingModule;
26 | import okhttp3.OkHttpClient;
27 |
28 | public class ReactNativeFlipper {
29 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
30 | if (FlipperUtils.shouldEnableFlipper(context)) {
31 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
32 |
33 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
34 | client.addPlugin(new ReactFlipperPlugin());
35 | client.addPlugin(new DatabasesFlipperPlugin(context));
36 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
37 | client.addPlugin(CrashReporterPlugin.getInstance());
38 |
39 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
40 | NetworkingModule.setCustomClientBuilder(
41 | new NetworkingModule.CustomClientBuilder() {
42 | @Override
43 | public void apply(OkHttpClient.Builder builder) {
44 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
45 | }
46 | });
47 | client.addPlugin(networkFlipperPlugin);
48 | client.start();
49 |
50 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
51 | // Hence we run if after all native modules have been initialized
52 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
53 | if (reactContext == null) {
54 | reactInstanceManager.addReactInstanceEventListener(
55 | new ReactInstanceEventListener() {
56 | @Override
57 | public void onReactContextInitialized(ReactContext reactContext) {
58 | reactInstanceManager.removeReactInstanceEventListener(this);
59 | reactContext.runOnNativeModulesQueueThread(
60 | new Runnable() {
61 | @Override
62 | public void run() {
63 | client.addPlugin(new FrescoFlipperPlugin());
64 | }
65 | });
66 | }
67 | });
68 | } else {
69 | client.addPlugin(new FrescoFlipperPlugin());
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/demo/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
14 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/demo/android/app/src/main/assets/assets-pdf.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/assets/assets-pdf.pdf
--------------------------------------------------------------------------------
/demo/android/app/src/main/java/com/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.demo;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.pm.PackageManager;
6 | import android.os.Bundle;
7 |
8 | import androidx.core.app.ActivityCompat;
9 |
10 | import com.facebook.react.ReactActivity;
11 | import com.facebook.react.ReactActivityDelegate;
12 | import com.facebook.react.ReactRootView;
13 |
14 | public class MainActivity extends ReactActivity {
15 | private static final int REQUEST_EXTERNAL_STORAGE = 1;
16 | private static String[] PERMISSIONS_STORAGE = {
17 | Manifest.permission.READ_EXTERNAL_STORAGE,
18 | Manifest.permission.WRITE_EXTERNAL_STORAGE
19 | };
20 |
21 | /**
22 | * Returns the name of the main component registered from JavaScript. This is used to schedule
23 | * rendering of the component.
24 | */
25 | @Override
26 | protected String getMainComponentName() {
27 | return "demo";
28 | }
29 |
30 | /**
31 | * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and
32 | * you can specify the renderer you wish to use - the new renderer (Fabric) or the old renderer
33 | * (Paper).
34 | */
35 | @Override
36 | protected ReactActivityDelegate createReactActivityDelegate() {
37 | return new MainActivityDelegate(this, getMainComponentName());
38 | }
39 |
40 | @Override
41 | public void onCreate (Bundle savedInstanceState) {
42 | super.onCreate(savedInstanceState);
43 | verifyStoragePermissions(this);
44 | }
45 |
46 | /**
47 | * Checks if the app has permission
48 | * @param activity
49 | */
50 | public static void verifyStoragePermissions(Activity activity) {
51 | // Check if we have write permission
52 | int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
53 |
54 | if (permission != PackageManager.PERMISSION_GRANTED) {
55 | // No permission, prompt the user
56 | ActivityCompat.requestPermissions(
57 | activity,
58 | PERMISSIONS_STORAGE,
59 | REQUEST_EXTERNAL_STORAGE
60 | );
61 | }
62 | }
63 |
64 | public static class MainActivityDelegate extends ReactActivityDelegate {
65 | public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
66 | super(activity, mainComponentName);
67 | }
68 |
69 | @Override
70 | protected ReactRootView createRootView() {
71 | ReactRootView reactRootView = new ReactRootView(getContext());
72 | // If you opted-in for the New Architecture, we enable the Fabric Renderer.
73 | reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
74 | return reactRootView;
75 | }
76 |
77 | @Override
78 | protected boolean isConcurrentRootEnabled() {
79 | // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18).
80 | // More on this on https://reactjs.org/blog/2022/03/29/react-v18.html
81 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/demo/android/app/src/main/java/com/demo/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.demo;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactApplication;
7 | import com.facebook.react.ReactInstanceManager;
8 | import com.facebook.react.ReactNativeHost;
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.react.config.ReactFeatureFlags;
11 | import com.facebook.soloader.SoLoader;
12 | import com.demo.newarchitecture.MainApplicationReactNativeHost;
13 | import java.lang.reflect.InvocationTargetException;
14 | import java.util.List;
15 |
16 | public class MainApplication extends Application implements ReactApplication {
17 |
18 | private final ReactNativeHost mReactNativeHost =
19 | new ReactNativeHost(this) {
20 | @Override
21 | public boolean getUseDeveloperSupport() {
22 | return BuildConfig.DEBUG;
23 | }
24 |
25 | @Override
26 | protected List getPackages() {
27 | @SuppressWarnings("UnnecessaryLocalVariable")
28 | List packages = new PackageList(this).getPackages();
29 | // Packages that cannot be autolinked yet can be added manually here, for example:
30 | // packages.add(new MyReactNativePackage());
31 | return packages;
32 | }
33 |
34 | @Override
35 | protected String getJSMainModuleName() {
36 | return "index";
37 | }
38 | };
39 |
40 | private final ReactNativeHost mNewArchitectureNativeHost =
41 | new MainApplicationReactNativeHost(this);
42 |
43 | @Override
44 | public ReactNativeHost getReactNativeHost() {
45 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
46 | return mNewArchitectureNativeHost;
47 | } else {
48 | return mReactNativeHost;
49 | }
50 | }
51 |
52 | @Override
53 | public void onCreate() {
54 | super.onCreate();
55 | // If you opted-in for the New Architecture, we enable the TurboModule system
56 | ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
57 | SoLoader.init(this, /* native exopackage */ false);
58 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
59 | }
60 |
61 | /**
62 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like
63 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
64 | *
65 | * @param context
66 | * @param reactInstanceManager
67 | */
68 | private static void initializeFlipper(
69 | Context context, ReactInstanceManager reactInstanceManager) {
70 | if (BuildConfig.DEBUG) {
71 | try {
72 | /*
73 | We use reflection here to pick up the class that initializes Flipper,
74 | since Flipper library is not available in release mode
75 | */
76 | Class> aClass = Class.forName("com.demo.ReactNativeFlipper");
77 | aClass
78 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
79 | .invoke(null, context, reactInstanceManager);
80 | } catch (ClassNotFoundException e) {
81 | e.printStackTrace();
82 | } catch (NoSuchMethodException e) {
83 | e.printStackTrace();
84 | } catch (IllegalAccessException e) {
85 | e.printStackTrace();
86 | } catch (InvocationTargetException e) {
87 | e.printStackTrace();
88 | }
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/demo/android/app/src/main/java/com/demo/newarchitecture/MainApplicationReactNativeHost.java:
--------------------------------------------------------------------------------
1 | package com.demo.newarchitecture;
2 |
3 | import android.app.Application;
4 | import androidx.annotation.NonNull;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactInstanceManager;
7 | import com.facebook.react.ReactNativeHost;
8 | import com.facebook.react.ReactPackage;
9 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
10 | import com.facebook.react.bridge.JSIModulePackage;
11 | import com.facebook.react.bridge.JSIModuleProvider;
12 | import com.facebook.react.bridge.JSIModuleSpec;
13 | import com.facebook.react.bridge.JSIModuleType;
14 | import com.facebook.react.bridge.JavaScriptContextHolder;
15 | import com.facebook.react.bridge.ReactApplicationContext;
16 | import com.facebook.react.bridge.UIManager;
17 | import com.facebook.react.fabric.ComponentFactory;
18 | import com.facebook.react.fabric.CoreComponentsRegistry;
19 | import com.facebook.react.fabric.FabricJSIModuleProvider;
20 | import com.facebook.react.fabric.ReactNativeConfig;
21 | import com.facebook.react.uimanager.ViewManagerRegistry;
22 | import com.demo.BuildConfig;
23 | import com.demo.newarchitecture.components.MainComponentsRegistry;
24 | import com.demo.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate;
25 | import java.util.ArrayList;
26 | import java.util.List;
27 |
28 | /**
29 | * A {@link ReactNativeHost} that helps you load everything needed for the New Architecture, both
30 | * TurboModule delegates and the Fabric Renderer.
31 | *
32 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
33 | * `newArchEnabled` property). Is ignored otherwise.
34 | */
35 | public class MainApplicationReactNativeHost extends ReactNativeHost {
36 | public MainApplicationReactNativeHost(Application application) {
37 | super(application);
38 | }
39 |
40 | @Override
41 | public boolean getUseDeveloperSupport() {
42 | return BuildConfig.DEBUG;
43 | }
44 |
45 | @Override
46 | protected List getPackages() {
47 | List packages = new PackageList(this).getPackages();
48 | // Packages that cannot be autolinked yet can be added manually here, for example:
49 | // packages.add(new MyReactNativePackage());
50 | // TurboModules must also be loaded here providing a valid TurboReactPackage implementation:
51 | // packages.add(new TurboReactPackage() { ... });
52 | // If you have custom Fabric Components, their ViewManagers should also be loaded here
53 | // inside a ReactPackage.
54 | return packages;
55 | }
56 |
57 | @Override
58 | protected String getJSMainModuleName() {
59 | return "index";
60 | }
61 |
62 | @NonNull
63 | @Override
64 | protected ReactPackageTurboModuleManagerDelegate.Builder
65 | getReactPackageTurboModuleManagerDelegateBuilder() {
66 | // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This is necessary
67 | // for the new architecture and to use TurboModules correctly.
68 | return new MainApplicationTurboModuleManagerDelegate.Builder();
69 | }
70 |
71 | @Override
72 | protected JSIModulePackage getJSIModulePackage() {
73 | return new JSIModulePackage() {
74 | @Override
75 | public List getJSIModules(
76 | final ReactApplicationContext reactApplicationContext,
77 | final JavaScriptContextHolder jsContext) {
78 | final List specs = new ArrayList<>();
79 |
80 | // Here we provide a new JSIModuleSpec that will be responsible of providing the
81 | // custom Fabric Components.
82 | specs.add(
83 | new JSIModuleSpec() {
84 | @Override
85 | public JSIModuleType getJSIModuleType() {
86 | return JSIModuleType.UIManager;
87 | }
88 |
89 | @Override
90 | public JSIModuleProvider getJSIModuleProvider() {
91 | final ComponentFactory componentFactory = new ComponentFactory();
92 | CoreComponentsRegistry.register(componentFactory);
93 |
94 | // Here we register a Components Registry.
95 | // The one that is generated with the template contains no components
96 | // and just provides you the one from React Native core.
97 | MainComponentsRegistry.register(componentFactory);
98 |
99 | final ReactInstanceManager reactInstanceManager = getReactInstanceManager();
100 |
101 | ViewManagerRegistry viewManagerRegistry =
102 | new ViewManagerRegistry(
103 | reactInstanceManager.getOrCreateViewManagers(reactApplicationContext));
104 |
105 | return new FabricJSIModuleProvider(
106 | reactApplicationContext,
107 | componentFactory,
108 | ReactNativeConfig.DEFAULT_CONFIG,
109 | viewManagerRegistry);
110 | }
111 | });
112 | return specs;
113 | }
114 | };
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/demo/android/app/src/main/java/com/demo/newarchitecture/components/MainComponentsRegistry.java:
--------------------------------------------------------------------------------
1 | package com.demo.newarchitecture.components;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.proguard.annotations.DoNotStrip;
5 | import com.facebook.react.fabric.ComponentFactory;
6 | import com.facebook.soloader.SoLoader;
7 |
8 | /**
9 | * Class responsible to load the custom Fabric Components. This class has native methods and needs a
10 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
11 | * folder for you).
12 | *
13 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
14 | * `newArchEnabled` property). Is ignored otherwise.
15 | */
16 | @DoNotStrip
17 | public class MainComponentsRegistry {
18 | static {
19 | SoLoader.loadLibrary("fabricjni");
20 | }
21 |
22 | @DoNotStrip private final HybridData mHybridData;
23 |
24 | @DoNotStrip
25 | private native HybridData initHybrid(ComponentFactory componentFactory);
26 |
27 | @DoNotStrip
28 | private MainComponentsRegistry(ComponentFactory componentFactory) {
29 | mHybridData = initHybrid(componentFactory);
30 | }
31 |
32 | @DoNotStrip
33 | public static MainComponentsRegistry register(ComponentFactory componentFactory) {
34 | return new MainComponentsRegistry(componentFactory);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/demo/android/app/src/main/java/com/demo/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java:
--------------------------------------------------------------------------------
1 | package com.demo.newarchitecture.modules;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.react.ReactPackage;
5 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
6 | import com.facebook.react.bridge.ReactApplicationContext;
7 | import com.facebook.soloader.SoLoader;
8 | import java.util.List;
9 |
10 | /**
11 | * Class responsible to load the TurboModules. This class has native methods and needs a
12 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
13 | * folder for you).
14 | *
15 | *