React native Pdf viewer implementation
npm install react-native-view-pdf





Library for displaying PDF documents in react-native
- android - uses Android PdfViewer. Targets minSdkVersion 21 (required by setClipToOutline) 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:
```
buildscript {
ext {
...
pdfViewerVersion = "3.1.0-beta.1"
}
...
}
Barteksc PdfViewer uses JCenter, which should be read-only indefinitely, but in case the host project does not use it, there is a possibility to use mhiew/AndroidPdfViewer
which is a fork published on mavenCentral. To use it, define the following configuration in your gradle script:
``
buildscript {
ext {
...
pdfViewerVersion = "3.2.0-beta.1"
pdfViewerRepo = "com.github.mhiew"
}
...
}
- ios - uses WKWebView.
Targets iOS9.0 and above
- zero NPM dependencies
$ npm install react-native-view-pdf --save
From RN 0.60 there is no need to link - Native Modules are now Autolinked
$ react-native link
If it doesn't work follow the official react native documentation
##### Using CocoaPods
In your Xcode project directory open Podfile and add the following line:
``
pod 'RNPDF', :path => '../node_modules/react-native-view-pdf'
And install:
``
pod install
#### Android
1. Open up android/app/src/main/java/[...]/MainApplication.javaimport com.rumax.reactnative.pdfviewer.PDFViewPackage;
- Add to the imports at the top of the filenew PDFViewPackage()
- Add to the list returned by the getPackages() methodandroid/settings.gradle
2. Append the following lines to :`
`
include ':react-native-view-pdf'
project(':react-native-view-pdf').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-view-pdf/android')
android/app/build.gradle
3. Insert the following lines inside the dependencies block in :`
`
compile project(':react-native-view-pdf')
##### Note for Android
The Android project tries to retrieve the following properties:
- compileSdkVersion
- buildToolsVersion
- minSdkVersion
- targetSdkVersion
from the ext object if you have one defined in your Android's project root (you can read more about it here). If not, it falls back to its current versions (check the gradle file for additional information).
#### Windows
ReactWindows
N/A
Android | iOS
------- | ---
!Android | !iOS
`
// With Flow type annotations (https://flow.org/)
import PDFView from 'react-native-view-pdf';
// Without Flow type annotations
// import PDFView from 'react-native-view-pdf/lib/index';
const resources = {
file: Platform.OS === 'ios' ? 'downloadedDocument.pdf' : '/sdcard/Download/downloadedDocument.pdf',
url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
base64: 'JVBERi0xLjMKJcfs...',
};
export default class App extends React.Component {
render() {
const resourceType = 'url';
return (
{/ Some Controls to change PDF resource /}
style={{ flex: 1 }}
resource={resources[resourceType]}
resourceType={resourceType}
onLoad={() => console.log(PDF rendered from ${resourceType})}
onError={(error) => console.log('Cannot render PDF', error)}
/>
);
}
}
`
Use the demo project to:
- Test the component on both android and iOS
- Render PDF using URL, BASE64 data or local file
- Handle error state
Name | Android | iOS | Description
---- | ------- | --- | -----------
resource | ✓ | ✓ | A resource to render. It's possible to render PDF from file, url (should be encoded) or base64file
resourceType | ✓ | ✓ | Should correspond to resource and can be: , url or base64resourceType
fileFrom | ✗ | ✓ | iOS ONLY: In case if is set to file, there are different way to search for it on iOS file system. Currently documentsDirectory, libraryDirectory, cachesDirectory, tempDirectory and bundle are supported.url
onLoad | ✓ | ✓ | Callback that is triggered when loading is completed
onError | ✓ | ✓ | Callback that is triggered when loading has failed. And error is provided as a function parameter
style | ✓ | ✓ | A style
fadeInDuration | ✓ | ✓ | Fade in duration (in ms, defaults to 0.0) to smoothly fade the webview into view when pdf loading is completed
enableAnnotations | ✓ | ✗ | Android ONLY: Boolean to enable Android view annotations (default is false).
urlProps | ✓ | ✓ | Extended properties for type that allows to specify HTTP Method, HTTP headers and HTTP bodyactive page
onPageChanged | ✓ | ✗ | Callback that is invoked when page is changed. Provides and total pages informationoffset
onScrolled | ✓ | ✓ | Callback that is invoked when PDF is scrolled. Provides value in a range between 0 and 1. Currently only 0 and 1 are supported.
#### reload
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:
`js
...
render() {
return (
ref={(ref) => this._pdfRed = ref} />
);
}
`
And trigger it by calling reloadPDF:
`js
reloadPDF = async () => {
const pdfRef = this._pdfRef;
if (!pdfRef) {
return;
}
try {
await pdfRef.reload();
} catch (err) {
console.err(err.message);
}
}
`
Or check the demo project which also includes this functionality.
On android for the file type it is required to request permissions to
read/write. You can get more information in PermissionsAndroid
section from react native or Request App Permissions from android
documentation. Demo
project provides an example how to implement it using Java, check the MainActivity.java and AndroidManifest.xml files.
Before trying file type in demo project, open sdcard/Download folder in Device File Explorer and store some downloadedDocument.pdf document that you want to render.
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.file://.....
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 ).
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.
In demo project you can also run the simple server to serve PDF file. To do this navigate to demo/utils/ and start the servernode server.js. (*Do not forget to set proper IP adress of the serverdemo/App.js
in *)
- Generated with react-native-create-library
- Zero JavaScript dependency. Which means that you do not bring other dependencies to your project
- If you think that something is missing or would like to propose new feature, please, discuss it with authors
- 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 🤩
- If you are using ProGuard, add following rule to proguard config file:
```
-keep class com.shockwave.**