├── .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 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/c1c746575c124138936e9418865136ab)](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 | [![npm](https://img.shields.io/npm/l/express.svg)](https://github.com/rumax/react-native-PDFView) 5 | [![npm version](https://badge.fury.io/js/react-native-view-pdf.svg)](https://badge.fury.io/js/react-native-view-pdf) 6 | [![CircleCI](https://circleci.com/gh/rumax/react-native-PDFView.svg?style=shield)](https://circleci.com/gh/rumax/react-native-PDFView) 7 | [![codecov](https://codecov.io/gh/rumax/react-native-PDFView/branch/master/graph/badge.svg)](https://codecov.io/gh/rumax/react-native-PDFView) 8 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](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 | ![Android](https://github.com/rumax/react-native-PDFView/raw/master/demo/res/android_pdf.gif) | ![iOS](https://github.com/rumax/react-native-PDFView/raw/master/demo/res/ios_pdf.gif) 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 | *

Please note that this class is used ONLY if you opt-in for the New Architecture (see the 16 | * `newArchEnabled` property). Is ignored otherwise. 17 | */ 18 | public class MainApplicationTurboModuleManagerDelegate 19 | extends ReactPackageTurboModuleManagerDelegate { 20 | 21 | private static volatile boolean sIsSoLibraryLoaded; 22 | 23 | protected MainApplicationTurboModuleManagerDelegate( 24 | ReactApplicationContext reactApplicationContext, List packages) { 25 | super(reactApplicationContext, packages); 26 | } 27 | 28 | protected native HybridData initHybrid(); 29 | 30 | native boolean canCreateTurboModule(String moduleName); 31 | 32 | public static class Builder extends ReactPackageTurboModuleManagerDelegate.Builder { 33 | protected MainApplicationTurboModuleManagerDelegate build( 34 | ReactApplicationContext context, List packages) { 35 | return new MainApplicationTurboModuleManagerDelegate(context, packages); 36 | } 37 | } 38 | 39 | @Override 40 | protected synchronized void maybeLoadOtherSoLibraries() { 41 | if (!sIsSoLibraryLoaded) { 42 | // If you change the name of your application .so file in the Android.mk file, 43 | // make sure you update the name here as well. 44 | SoLoader.loadLibrary("demo_appmodules"); 45 | sIsSoLibraryLoaded = true; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /demo/android/app/src/main/jni/Android.mk: -------------------------------------------------------------------------------- 1 | THIS_DIR := $(call my-dir) 2 | 3 | include $(REACT_ANDROID_DIR)/Android-prebuilt.mk 4 | 5 | # If you wish to add a custom TurboModule or Fabric component in your app you 6 | # will have to include the following autogenerated makefile. 7 | # include $(GENERATED_SRC_DIR)/codegen/jni/Android.mk 8 | include $(CLEAR_VARS) 9 | 10 | LOCAL_PATH := $(THIS_DIR) 11 | 12 | # You can customize the name of your application .so file here. 13 | LOCAL_MODULE := demo_appmodules 14 | 15 | LOCAL_C_INCLUDES := $(LOCAL_PATH) 16 | LOCAL_SRC_FILES := $(wildcard $(LOCAL_PATH)/*.cpp) 17 | LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) 18 | 19 | # If you wish to add a custom TurboModule or Fabric component in your app you 20 | # will have to uncomment those lines to include the generated source 21 | # files from the codegen (placed in $(GENERATED_SRC_DIR)/codegen/jni) 22 | # 23 | # LOCAL_C_INCLUDES += $(GENERATED_SRC_DIR)/codegen/jni 24 | # LOCAL_SRC_FILES += $(wildcard $(GENERATED_SRC_DIR)/codegen/jni/*.cpp) 25 | # LOCAL_EXPORT_C_INCLUDES += $(GENERATED_SRC_DIR)/codegen/jni 26 | 27 | # Here you should add any native library you wish to depend on. 28 | LOCAL_SHARED_LIBRARIES := \ 29 | libfabricjni \ 30 | libfbjni \ 31 | libfolly_runtime \ 32 | libglog \ 33 | libjsi \ 34 | libreact_codegen_rncore \ 35 | libreact_debug \ 36 | libreact_nativemodule_core \ 37 | libreact_render_componentregistry \ 38 | libreact_render_core \ 39 | libreact_render_debug \ 40 | libreact_render_graphics \ 41 | librrc_view \ 42 | libruntimeexecutor \ 43 | libturbomodulejsijni \ 44 | libyoga 45 | 46 | LOCAL_CFLAGS := -DLOG_TAG=\"ReactNative\" -fexceptions -frtti -std=c++17 -Wall 47 | 48 | include $(BUILD_SHARED_LIBRARY) 49 | -------------------------------------------------------------------------------- /demo/android/app/src/main/jni/MainApplicationModuleProvider.cpp: -------------------------------------------------------------------------------- 1 | #include "MainApplicationModuleProvider.h" 2 | 3 | #include 4 | 5 | namespace facebook { 6 | namespace react { 7 | 8 | std::shared_ptr MainApplicationModuleProvider( 9 | const std::string moduleName, 10 | const JavaTurboModule::InitParams ¶ms) { 11 | // Here you can provide your own module provider for TurboModules coming from 12 | // either your application or from external libraries. The approach to follow 13 | // is similar to the following (for a library called `samplelibrary`: 14 | // 15 | // auto module = samplelibrary_ModuleProvider(moduleName, params); 16 | // if (module != nullptr) { 17 | // return module; 18 | // } 19 | // return rncore_ModuleProvider(moduleName, params); 20 | return rncore_ModuleProvider(moduleName, params); 21 | } 22 | 23 | } // namespace react 24 | } // namespace facebook 25 | -------------------------------------------------------------------------------- /demo/android/app/src/main/jni/MainApplicationModuleProvider.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | namespace facebook { 9 | namespace react { 10 | 11 | std::shared_ptr MainApplicationModuleProvider( 12 | const std::string moduleName, 13 | const JavaTurboModule::InitParams ¶ms); 14 | 15 | } // namespace react 16 | } // namespace facebook 17 | -------------------------------------------------------------------------------- /demo/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp: -------------------------------------------------------------------------------- 1 | #include "MainApplicationTurboModuleManagerDelegate.h" 2 | #include "MainApplicationModuleProvider.h" 3 | 4 | namespace facebook { 5 | namespace react { 6 | 7 | jni::local_ref 8 | MainApplicationTurboModuleManagerDelegate::initHybrid( 9 | jni::alias_ref) { 10 | return makeCxxInstance(); 11 | } 12 | 13 | void MainApplicationTurboModuleManagerDelegate::registerNatives() { 14 | registerHybrid({ 15 | makeNativeMethod( 16 | "initHybrid", MainApplicationTurboModuleManagerDelegate::initHybrid), 17 | makeNativeMethod( 18 | "canCreateTurboModule", 19 | MainApplicationTurboModuleManagerDelegate::canCreateTurboModule), 20 | }); 21 | } 22 | 23 | std::shared_ptr 24 | MainApplicationTurboModuleManagerDelegate::getTurboModule( 25 | const std::string name, 26 | const std::shared_ptr jsInvoker) { 27 | // Not implemented yet: provide pure-C++ NativeModules here. 28 | return nullptr; 29 | } 30 | 31 | std::shared_ptr 32 | MainApplicationTurboModuleManagerDelegate::getTurboModule( 33 | const std::string name, 34 | const JavaTurboModule::InitParams ¶ms) { 35 | return MainApplicationModuleProvider(name, params); 36 | } 37 | 38 | bool MainApplicationTurboModuleManagerDelegate::canCreateTurboModule( 39 | std::string name) { 40 | return getTurboModule(name, nullptr) != nullptr || 41 | getTurboModule(name, {.moduleName = name}) != nullptr; 42 | } 43 | 44 | } // namespace react 45 | } // namespace facebook 46 | -------------------------------------------------------------------------------- /demo/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | #include 6 | 7 | namespace facebook { 8 | namespace react { 9 | 10 | class MainApplicationTurboModuleManagerDelegate 11 | : public jni::HybridClass< 12 | MainApplicationTurboModuleManagerDelegate, 13 | TurboModuleManagerDelegate> { 14 | public: 15 | // Adapt it to the package you used for your Java class. 16 | static constexpr auto kJavaDescriptor = 17 | "Lcom/demo/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate;"; 18 | 19 | static jni::local_ref initHybrid(jni::alias_ref); 20 | 21 | static void registerNatives(); 22 | 23 | std::shared_ptr getTurboModule( 24 | const std::string name, 25 | const std::shared_ptr jsInvoker) override; 26 | std::shared_ptr getTurboModule( 27 | const std::string name, 28 | const JavaTurboModule::InitParams ¶ms) override; 29 | 30 | /** 31 | * Test-only method. Allows user to verify whether a TurboModule can be 32 | * created by instances of this class. 33 | */ 34 | bool canCreateTurboModule(std::string name); 35 | }; 36 | 37 | } // namespace react 38 | } // namespace facebook 39 | -------------------------------------------------------------------------------- /demo/android/app/src/main/jni/MainComponentsRegistry.cpp: -------------------------------------------------------------------------------- 1 | #include "MainComponentsRegistry.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | namespace facebook { 9 | namespace react { 10 | 11 | MainComponentsRegistry::MainComponentsRegistry(ComponentFactory *delegate) {} 12 | 13 | std::shared_ptr 14 | MainComponentsRegistry::sharedProviderRegistry() { 15 | auto providerRegistry = CoreComponentsRegistry::sharedProviderRegistry(); 16 | 17 | // Custom Fabric Components go here. You can register custom 18 | // components coming from your App or from 3rd party libraries here. 19 | // 20 | // providerRegistry->add(concreteComponentDescriptorProvider< 21 | // AocViewerComponentDescriptor>()); 22 | return providerRegistry; 23 | } 24 | 25 | jni::local_ref 26 | MainComponentsRegistry::initHybrid( 27 | jni::alias_ref, 28 | ComponentFactory *delegate) { 29 | auto instance = makeCxxInstance(delegate); 30 | 31 | auto buildRegistryFunction = 32 | [](EventDispatcher::Weak const &eventDispatcher, 33 | ContextContainer::Shared const &contextContainer) 34 | -> ComponentDescriptorRegistry::Shared { 35 | auto registry = MainComponentsRegistry::sharedProviderRegistry() 36 | ->createComponentDescriptorRegistry( 37 | {eventDispatcher, contextContainer}); 38 | 39 | auto mutableRegistry = 40 | std::const_pointer_cast(registry); 41 | 42 | mutableRegistry->setFallbackComponentDescriptor( 43 | std::make_shared( 44 | ComponentDescriptorParameters{ 45 | eventDispatcher, contextContainer, nullptr})); 46 | 47 | return registry; 48 | }; 49 | 50 | delegate->buildRegistryFunction = buildRegistryFunction; 51 | return instance; 52 | } 53 | 54 | void MainComponentsRegistry::registerNatives() { 55 | registerHybrid({ 56 | makeNativeMethod("initHybrid", MainComponentsRegistry::initHybrid), 57 | }); 58 | } 59 | 60 | } // namespace react 61 | } // namespace facebook 62 | -------------------------------------------------------------------------------- /demo/android/app/src/main/jni/MainComponentsRegistry.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | namespace facebook { 9 | namespace react { 10 | 11 | class MainComponentsRegistry 12 | : public facebook::jni::HybridClass { 13 | public: 14 | // Adapt it to the package you used for your Java class. 15 | constexpr static auto kJavaDescriptor = 16 | "Lcom/demo/newarchitecture/components/MainComponentsRegistry;"; 17 | 18 | static void registerNatives(); 19 | 20 | MainComponentsRegistry(ComponentFactory *delegate); 21 | 22 | private: 23 | static std::shared_ptr 24 | sharedProviderRegistry(); 25 | 26 | static jni::local_ref initHybrid( 27 | jni::alias_ref, 28 | ComponentFactory *delegate); 29 | }; 30 | 31 | } // namespace react 32 | } // namespace facebook 33 | -------------------------------------------------------------------------------- /demo/android/app/src/main/jni/OnLoad.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "MainApplicationTurboModuleManagerDelegate.h" 3 | #include "MainComponentsRegistry.h" 4 | 5 | JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { 6 | return facebook::jni::initialize(vm, [] { 7 | facebook::react::MainApplicationTurboModuleManagerDelegate:: 8 | registerNatives(); 9 | facebook::react::MainComponentsRegistry::registerNatives(); 10 | }); 11 | } 12 | -------------------------------------------------------------------------------- /demo/android/app/src/main/res/drawable/rn_edit_text_material.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 21 | 22 | 23 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | demo 3 | 4 | -------------------------------------------------------------------------------- /demo/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /demo/android/build.gradle: -------------------------------------------------------------------------------- 1 | import org.apache.tools.ant.taskdefs.condition.Os 2 | 3 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 4 | 5 | buildscript { 6 | ext { 7 | buildToolsVersion = "31.0.0" 8 | minSdkVersion = 21 9 | compileSdkVersion = 31 10 | targetSdkVersion = 31 11 | 12 | pdfViewerVersion = "3.2.0-beta.1" 13 | pdfViewerRepo = "com.github.mhiew" 14 | 15 | if (System.properties['os.arch'] == "aarch64") { 16 | // For M1 Users we need to use the NDK 24 which added support for aarch64 17 | ndkVersion = "24.0.8215888" 18 | } else { 19 | // Otherwise we default to the side-by-side NDK version from AGP. 20 | ndkVersion = "21.4.7075529" 21 | } 22 | } 23 | repositories { 24 | google() 25 | mavenCentral() 26 | } 27 | dependencies { 28 | classpath("com.android.tools.build:gradle:7.1.1") 29 | classpath("com.facebook.react:react-native-gradle-plugin") 30 | classpath("de.undercouch:gradle-download-task:5.0.1") 31 | // NOTE: Do not place your application dependencies here; they belong 32 | // in the individual module build.gradle files 33 | } 34 | } 35 | 36 | allprojects { 37 | repositories { 38 | maven { 39 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 40 | url("$rootDir/../node_modules/react-native/android") 41 | } 42 | maven { 43 | // Android JSC is installed from npm 44 | url("$rootDir/../node_modules/jsc-android/dist") 45 | } 46 | mavenCentral { 47 | // We don't want to fetch react-native from Maven Central as there are 48 | // older versions over there. 49 | content { 50 | excludeGroup "com.facebook.react" 51 | } 52 | } 53 | google() 54 | maven { url 'https://www.jitpack.io' } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /demo/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m 13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | # Automatically convert third-party libraries to use AndroidX 25 | android.enableJetifier=true 26 | 27 | # Version of flipper SDK to use with React Native 28 | FLIPPER_VERSION=0.125.0 29 | 30 | # Use this property to specify which architecture you want to build. 31 | # You can also override it from the CLI using 32 | # ./gradlew -PreactNativeArchitectures=x86_64 33 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 34 | 35 | # Use this property to enable support to the new architecture. 36 | # This will allow you to use TurboModules and the Fabric render in 37 | # your application. You should enable this flag either if you want 38 | # to write custom TurboModules/Fabric components OR use libraries that 39 | # are providing them. 40 | newArchEnabled=false 41 | -------------------------------------------------------------------------------- /demo/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /demo/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /demo/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /demo/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /demo/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'demo' 2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 3 | include ':app' 4 | includeBuild('../node_modules/react-native-gradle-plugin') 5 | 6 | if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") { 7 | include(":ReactAndroid") 8 | project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid') 9 | include(":ReactAndroid:hermes-engine") 10 | project(":ReactAndroid:hermes-engine").projectDir = file('../node_modules/react-native/ReactAndroid/hermes-engine') 11 | } 12 | -------------------------------------------------------------------------------- /demo/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo", 3 | "displayName": "demo" 4 | } -------------------------------------------------------------------------------- /demo/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /demo/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import {AppRegistry} from 'react-native'; 6 | import App from './src/App'; 7 | import {name as appName} from './app.json'; 8 | 9 | AppRegistry.registerComponent(appName, () => App); 10 | -------------------------------------------------------------------------------- /demo/ios/Podfile: -------------------------------------------------------------------------------- 1 | require_relative '../node_modules/react-native/scripts/react_native_pods' 2 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' 3 | 4 | platform :ios, '12.4' 5 | install! 'cocoapods', :deterministic_uuids => false 6 | 7 | production = ENV["PRODUCTION"] == "1" 8 | 9 | target 'demo' do 10 | config = use_native_modules! 11 | 12 | # Flags change depending on the env values. 13 | flags = get_default_flags() 14 | 15 | use_react_native!( 16 | :path => config[:reactNativePath], 17 | # to enable hermes on iOS, change `false` to `true` and then install pods 18 | :production => production, 19 | :hermes_enabled => flags[:hermes_enabled], 20 | :fabric_enabled => flags[:fabric_enabled], 21 | :flipper_configuration => FlipperConfiguration.enabled, 22 | # An absolute path to your application root. 23 | :app_path => "#{Pod::Config.instance.installation_root}/.." 24 | ) 25 | 26 | target 'demoTests' do 27 | inherit! :complete 28 | # Pods for testing 29 | end 30 | 31 | post_install do |installer| 32 | react_native_post_install(installer) 33 | __apply_Xcode_12_5_M1_post_install_workaround(installer) 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /demo/ios/_xcode.env: -------------------------------------------------------------------------------- 1 | # This `.xcode.env` file is versioned and is used to source the environment 2 | # used when running script phases inside Xcode. 3 | # To customize your local environment, you can create an `.xcode.env.local` 4 | # file that is not versioned. 5 | 6 | # NODE_BINARY variable contains the PATH to the node executable. 7 | # 8 | # Customize the NODE_BINARY variable here. 9 | # For example, to use nvm with brew, add the following line 10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use 11 | export NODE_BINARY=$(command -v node) 12 | -------------------------------------------------------------------------------- /demo/ios/demo.xcodeproj/xcshareddata/xcschemes/demo.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /demo/ios/demo.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /demo/ios/demo/AppDelegate.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | @interface AppDelegate : UIResponder 5 | 6 | @property (nonatomic, strong) UIWindow *window; 7 | 8 | @end 9 | -------------------------------------------------------------------------------- /demo/ios/demo/AppDelegate.mm: -------------------------------------------------------------------------------- 1 | #import "AppDelegate.h" 2 | 3 | #import 4 | #import 5 | #import 6 | 7 | #import 8 | 9 | #if RCT_NEW_ARCH_ENABLED 10 | #import 11 | #import 12 | #import 13 | #import 14 | #import 15 | #import 16 | 17 | #import 18 | 19 | static NSString *const kRNConcurrentRoot = @"concurrentRoot"; 20 | 21 | @interface AppDelegate () { 22 | RCTTurboModuleManager *_turboModuleManager; 23 | RCTSurfacePresenterBridgeAdapter *_bridgeAdapter; 24 | std::shared_ptr _reactNativeConfig; 25 | facebook::react::ContextContainer::Shared _contextContainer; 26 | } 27 | @end 28 | #endif 29 | 30 | @implementation AppDelegate 31 | 32 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 33 | { 34 | RCTAppSetupPrepareApp(application); 35 | 36 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; 37 | 38 | #if RCT_NEW_ARCH_ENABLED 39 | _contextContainer = std::make_shared(); 40 | _reactNativeConfig = std::make_shared(); 41 | _contextContainer->insert("ReactNativeConfig", _reactNativeConfig); 42 | _bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:bridge contextContainer:_contextContainer]; 43 | bridge.surfacePresenter = _bridgeAdapter.surfacePresenter; 44 | #endif 45 | 46 | NSDictionary *initProps = [self prepareInitialProps]; 47 | UIView *rootView = RCTAppSetupDefaultRootView(bridge, @"demo", initProps); 48 | 49 | if (@available(iOS 13.0, *)) { 50 | rootView.backgroundColor = [UIColor systemBackgroundColor]; 51 | } else { 52 | rootView.backgroundColor = [UIColor whiteColor]; 53 | } 54 | 55 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 56 | UIViewController *rootViewController = [UIViewController new]; 57 | rootViewController.view = rootView; 58 | self.window.rootViewController = rootViewController; 59 | [self.window makeKeyAndVisible]; 60 | return YES; 61 | } 62 | 63 | /// This method controls whether the `concurrentRoot`feature of React18 is turned on or off. 64 | /// 65 | /// @see: https://reactjs.org/blog/2022/03/29/react-v18.html 66 | /// @note: This requires to be rendering on Fabric (i.e. on the New Architecture). 67 | /// @return: `true` if the `concurrentRoot` feture is enabled. Otherwise, it returns `false`. 68 | - (BOOL)concurrentRootEnabled 69 | { 70 | // Switch this bool to turn on and off the concurrent root 71 | return true; 72 | } 73 | 74 | - (NSDictionary *)prepareInitialProps 75 | { 76 | NSMutableDictionary *initProps = [NSMutableDictionary new]; 77 | 78 | #ifdef RCT_NEW_ARCH_ENABLED 79 | initProps[kRNConcurrentRoot] = @([self concurrentRootEnabled]); 80 | #endif 81 | 82 | return initProps; 83 | } 84 | 85 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 86 | { 87 | #if DEBUG 88 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"]; 89 | #else 90 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 91 | #endif 92 | } 93 | 94 | #if RCT_NEW_ARCH_ENABLED 95 | 96 | #pragma mark - RCTCxxBridgeDelegate 97 | 98 | - (std::unique_ptr)jsExecutorFactoryForBridge:(RCTBridge *)bridge 99 | { 100 | _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge 101 | delegate:self 102 | jsInvoker:bridge.jsCallInvoker]; 103 | return RCTAppSetupDefaultJsExecutorFactory(bridge, _turboModuleManager); 104 | } 105 | 106 | #pragma mark RCTTurboModuleManagerDelegate 107 | 108 | - (Class)getModuleClassFromName:(const char *)name 109 | { 110 | return RCTCoreModulesClassProvider(name); 111 | } 112 | 113 | - (std::shared_ptr)getTurboModule:(const std::string &)name 114 | jsInvoker:(std::shared_ptr)jsInvoker 115 | { 116 | return nullptr; 117 | } 118 | 119 | - (std::shared_ptr)getTurboModule:(const std::string &)name 120 | initParams: 121 | (const facebook::react::ObjCTurboModule::InitParams &)params 122 | { 123 | return nullptr; 124 | } 125 | 126 | - (id)getModuleInstanceFromClass:(Class)moduleClass 127 | { 128 | return RCTAppSetupDefaultModuleFromClass(moduleClass); 129 | } 130 | 131 | #endif 132 | 133 | @end 134 | -------------------------------------------------------------------------------- /demo/ios/demo/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "scale" : "2x", 6 | "size" : "20x20" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "scale" : "3x", 11 | "size" : "20x20" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "scale" : "2x", 16 | "size" : "29x29" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "scale" : "3x", 21 | "size" : "29x29" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "scale" : "2x", 26 | "size" : "40x40" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "scale" : "3x", 31 | "size" : "40x40" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "scale" : "2x", 36 | "size" : "60x60" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "scale" : "3x", 41 | "size" : "60x60" 42 | }, 43 | { 44 | "idiom" : "ios-marketing", 45 | "scale" : "1x", 46 | "size" : "1024x1024" 47 | } 48 | ], 49 | "info" : { 50 | "author" : "xcode", 51 | "version" : 1 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /demo/ios/demo/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /demo/ios/demo/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | demo 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSExceptionDomains 30 | 31 | localhost 32 | 33 | NSExceptionAllowsInsecureHTTPLoads 34 | 35 | 36 | 37 | 38 | NSLocationWhenInUseUsageDescription 39 | 40 | UILaunchStoryboardName 41 | LaunchScreen 42 | UIRequiredDeviceCapabilities 43 | 44 | armv7 45 | 46 | UISupportedInterfaceOrientations 47 | 48 | UIInterfaceOrientationPortrait 49 | UIInterfaceOrientationLandscapeLeft 50 | UIInterfaceOrientationLandscapeRight 51 | 52 | UIViewControllerBasedStatusBarAppearance 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /demo/ios/demo/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 24 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /demo/ios/demo/main.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "AppDelegate.h" 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | @autoreleasepool { 8 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /demo/ios/demoTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /demo/ios/demoTests/demoTests.m: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | #import 5 | #import 6 | 7 | #define TIMEOUT_SECONDS 600 8 | #define TEXT_TO_LOOK_FOR @"Welcome to React" 9 | 10 | @interface demoTests : XCTestCase 11 | 12 | @end 13 | 14 | @implementation demoTests 15 | 16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test 17 | { 18 | if (test(view)) { 19 | return YES; 20 | } 21 | for (UIView *subview in [view subviews]) { 22 | if ([self findSubviewInView:subview matching:test]) { 23 | return YES; 24 | } 25 | } 26 | return NO; 27 | } 28 | 29 | - (void)testRendersWelcomeScreen 30 | { 31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 33 | BOOL foundElement = NO; 34 | 35 | __block NSString *redboxError = nil; 36 | #ifdef DEBUG 37 | RCTSetLogFunction( 38 | ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 39 | if (level >= RCTLogLevelError) { 40 | redboxError = message; 41 | } 42 | }); 43 | #endif 44 | 45 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 46 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 47 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 48 | 49 | foundElement = [self findSubviewInView:vc.view 50 | matching:^BOOL(UIView *view) { 51 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 52 | return YES; 53 | } 54 | return NO; 55 | }]; 56 | } 57 | 58 | #ifdef DEBUG 59 | RCTSetLogFunction(RCTDefaultLogFunction); 60 | #endif 61 | 62 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 63 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /demo/ios/test-pdf.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/ios/test-pdf.pdf -------------------------------------------------------------------------------- /demo/metro.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Metro configuration for React Native 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | */ 7 | 8 | module.exports = { 9 | transformer: { 10 | getTransformOptions: async () => ({ 11 | transform: { 12 | experimentalImportSupport: false, 13 | inlineRequires: true, 14 | }, 15 | }), 16 | }, 17 | }; 18 | -------------------------------------------------------------------------------- /demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "android": "react-native run-android", 7 | "ios": "react-native run-ios", 8 | "start": "react-native start", 9 | "preinstall": "rm -rf node_modules package-lock.json && cd .. && rm -rf react-native-view-pdf-*.tgz && npm i && npm pack && mv react-native-view-pdf-*.tgz react-native-view-pdf.tgz", 10 | "test": "jest", 11 | "lint": "eslint . --ext .js,.jsx,.ts,.tsx" 12 | }, 13 | "dependencies": { 14 | "react": "18.0.0", 15 | "react-native": "0.69.4", 16 | "react-native-dropdownalert": "^4.3.0", 17 | "react-native-loading-spinner-overlay": "^1.1.0", 18 | "react-native-view-pdf": "../react-native-view-pdf.tgz" 19 | }, 20 | "devDependencies": { 21 | "@babel/core": "^7.12.9", 22 | "@babel/runtime": "^7.12.5", 23 | "@react-native-community/eslint-config": "^2.0.0", 24 | "@tsconfig/react-native": "^2.0.2", 25 | "@types/jest": "^26.0.23", 26 | "@types/react-native": "^0.69.3", 27 | "@types/react-native-loading-spinner-overlay": "^0.5.3", 28 | "@types/react-test-renderer": "^18.0.0", 29 | "@typescript-eslint/eslint-plugin": "^5.29.0", 30 | "@typescript-eslint/parser": "^5.29.0", 31 | "babel-jest": "^26.6.3", 32 | "eslint": "^7.32.0", 33 | "jest": "^26.6.3", 34 | "metro-react-native-babel-preset": "^0.70.3", 35 | "react-test-renderer": "18.0.0", 36 | "typescript": "^4.4.4" 37 | }, 38 | "jest": { 39 | "preset": "react-native", 40 | "moduleFileExtensions": [ 41 | "ts", 42 | "tsx", 43 | "js", 44 | "jsx", 45 | "json", 46 | "node" 47 | ] 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /demo/res/android_pdf.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/res/android_pdf.gif -------------------------------------------------------------------------------- /demo/res/ios_pdf.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rumax/react-native-PDFView/1296639a651ed7d538eb0b103440176d9dbaadc5/demo/res/ios_pdf.gif -------------------------------------------------------------------------------- /demo/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React, { Fragment } from 'react'; 2 | import { Alert, SafeAreaView, StatusBar, Text, View } from 'react-native'; 3 | import PDFView from 'react-native-view-pdf'; 4 | import Spinner from 'react-native-loading-spinner-overlay'; 5 | import DropdownAlert from 'react-native-dropdownalert'; 6 | 7 | import styles from './styles'; 8 | import resources from './resources'; 9 | import type { Resource } from './resources'; 10 | import Button from './Button'; 11 | import pkg from '../package.json'; 12 | 13 | type StateType = { 14 | activeButton?: 15 | | 'assets' 16 | | 'file' 17 | | 'url' 18 | | 'post' 19 | | 'base64' 20 | | 'reset' 21 | | 'errorData' 22 | | 'errorProtocol'; 23 | resource?: Resource; 24 | spinner: boolean; 25 | canReload?: boolean; 26 | multiple?: boolean; 27 | }; 28 | 29 | const HorisontalLine = () => ; 30 | 31 | type PdfContentType = { 32 | resource?: Resource; 33 | onRef?: any; 34 | onLoad?: () => void; 35 | onError?: (error: { message: string }) => void; 36 | onPageChanged?: (page: number, pageCount: number) => void; 37 | onScrolled?: (offset: number) => void; 38 | }; 39 | 40 | const PdfContent = (props: PdfContentType) => { 41 | if (props.resource) { 42 | return ( 43 | 53 | ); 54 | } 55 | 56 | return ( 57 | 58 | 59 | No resources 60 | {'\n'} 61 | Press one of the buttons above 62 | 63 | 64 | You are running the app in {__DEV__ ? 'DEV' : 'RELEASE'} mode{'\n'} 65 | RN version is {pkg.dependencies['react-native']} 66 | 67 | 68 | ); 69 | }; 70 | 71 | export default class App extends React.Component<{}, StateType> { 72 | _dropdownRef: DropdownAlert | null = null; 73 | 74 | _pdfRef: PDFView | null = null; 75 | 76 | _renderStarted: number; 77 | 78 | constructor(props: {}) { 79 | super(props); 80 | this.state = { resource: undefined, spinner: false }; 81 | this._renderStarted = 0; 82 | } 83 | 84 | setUrl = () => { 85 | this.setState({ 86 | activeButton: 'url', 87 | resource: resources.url, 88 | spinner: true, 89 | }); 90 | }; 91 | 92 | setUrlPost = () => { 93 | this.setState({ 94 | activeButton: 'post', 95 | resource: resources.urlPost, 96 | spinner: true, 97 | }); 98 | }; 99 | 100 | setBase64 = () => { 101 | this.setState({ 102 | activeButton: 'base64', 103 | resource: resources.base64, 104 | spinner: true, 105 | }); 106 | }; 107 | 108 | setFile = () => { 109 | this.setState({ 110 | activeButton: 'file', 111 | resource: resources.file, 112 | spinner: true, 113 | }); 114 | }; 115 | 116 | setFileAssets = () => { 117 | this.setState({ 118 | activeButton: 'assets', 119 | resource: resources.fileAssets, 120 | spinner: true, 121 | }); 122 | }; 123 | 124 | dataWithError = () => { 125 | this.setState({ 126 | activeButton: 'errorData', 127 | resource: resources.invalidData, 128 | spinner: true, 129 | }); 130 | }; 131 | 132 | protocolWithError = () => { 133 | this.setState({ 134 | activeButton: 'errorProtocol', 135 | resource: resources.invalidProtocol, 136 | spinner: true, 137 | }); 138 | }; 139 | 140 | resetData = () => { 141 | this.setState({ 142 | activeButton: undefined, 143 | resource: undefined, 144 | canReload: false, 145 | }); 146 | }; 147 | 148 | multiplePDFs = () => { 149 | const { state } = this; 150 | 151 | if (state.multiple) { 152 | this.setState({ multiple: false }); 153 | return; 154 | } 155 | 156 | Alert.alert( 157 | 'Duplicate PDF', 158 | 'The PDF will be duplicated', 159 | [ 160 | { text: 'Cancel', onPress: () => {}, style: 'cancel' }, 161 | { 162 | text: 'OK', 163 | onPress: () => { 164 | this.setState({ multiple: true }); 165 | }, 166 | }, 167 | ], 168 | { cancelable: false }, 169 | ); 170 | }; 171 | 172 | handleLoad = () => { 173 | this.setState({ spinner: false, canReload: true }); 174 | if (this._dropdownRef) { 175 | this._dropdownRef.alertWithType( 176 | 'success', 177 | 'Document loaded', 178 | `Loading time: ${new Date().getTime() - this._renderStarted}`, 179 | ); 180 | } 181 | }; 182 | 183 | handleError = (error: { message: string }) => { 184 | this.setState({ spinner: false, canReload: true }); 185 | if (this._dropdownRef) { 186 | this._dropdownRef.alertWithType( 187 | 'error', 188 | 'Document loading failed', 189 | `error message: ${error.message}`, 190 | ); 191 | } 192 | }; 193 | 194 | handlePageChanged = (page: number, pageCount: number) => { 195 | console.log(`page ${page + 1} out of ${pageCount}`); 196 | }; 197 | 198 | handleOnScrolled = (offset: number) => { 199 | console.log(`offset is: ${offset}`); 200 | }; 201 | 202 | reloadPDF = async () => { 203 | const pdfRef = this._pdfRef; 204 | 205 | if (!pdfRef) { 206 | return; 207 | } 208 | 209 | this.setState({ spinner: true }); 210 | try { 211 | await pdfRef.reload(); 212 | } catch (err) { 213 | this.setState({ spinner: false }); 214 | if (this._dropdownRef) { 215 | this._dropdownRef.alertWithType( 216 | 'error', 217 | 'Document reload failed', 218 | `error message: ${(err as any).message}`, 219 | ); 220 | } 221 | } 222 | }; 223 | 224 | onRef = (ref: PDFView) => { 225 | this._pdfRef = ref; 226 | }; 227 | 228 | render() { 229 | const { state } = this; 230 | const { activeButton } = state; 231 | this._renderStarted = new Date().getTime(); 232 | 233 | return ( 234 | 235 | 236 | 237 | 238 |