Tutorials

How to Build a React Native PDF Viewer with Proper Library?

By ComPDFKit | Tue. 10 Dec. 2024
AndroidiOSReact Native

 

In this article, we will compare some of the most popular React Native PDF libraries available on the market. Additionally, we will provide a step-by-step guide on how to use the best of these libraries like ComPDFKit and react-native-pdf to create a React Native PDF viewer.



Create a React Native PDF Viewer with ComPDFKit

 

Obtain the React Native PDF SDK license and SDK package directly, bypassing sales. Then, follow these instructions to integrate ComPDFKit into your app and achieve the PDF viewer shown below. 

 

ComPDFKit React Native - Android ComPDFKit React Native - iOS
ComPDFKit-demo-android ComPFKit-demo-ios

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

Create a Project

 

1. In the terminal app, change the current working directory to the location where you wish to save your project. In this example, we’ll use the ~/Documents/ directory cd ~/Documents.

 

2. Create the React Native project by running the following command:

react-native init compdfkit_rn

 

3. In the terminal app, change the location of the current working directory inside the newly created project:

cd compdfkit_rn

 

Add ComPDFKit to Your Project

 

For iOS:

 

1. Open your project’s Podfile in a text editor:

open ios/Podfile

 

2. Update the platform to iOS 11 and add the ComPDFKit Podspec:

 

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

- platform :ios, '10.0'
+ platform :ios, '11.0'
install! 'cocoapods', :deterministic_uuids => false

target 'PDFView_RN' do
  config = use_native_modules!

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => flags[:hermes_enabled],
    :fabric_enabled => flags[:fabric_enabled],
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'PDFView_RNTests' do
    inherit! :complete
    # Pods for testing
  end

+  pod 'ComPDFKit_Tools', podspec:'https://www.compdf.com/download/ios/cocoapods/xcframeworks/compdfkit_tools/1.11.0.podspec'
+  pod 'ComPDFKit', podspec:'https://www.compdf.com/download/ios/cocoapods/xcframeworks/compdfkit/1.11.0.podspec'

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

 

3. Go to the compdfkit_rn/ios folder and run the pod install command:

pod install

 

4. Open your project’s Workspace in Xcode:

open ios/PDFView_RN.xcworkspace

 

 

5. Import resource file, CPDFViewController view controller that contains ready-to-use UI module implementations:

 

 

6. In the Build Settings search for "bridging" locate the Objective-C Bridging Header, and enter the file path for that header:

 

 

7. Add the PDF document you want to display to your application by dragging it into your project. On the dialog that’s displayed, select Finish to accept the default integration options. You can use “developer_guide_ios.pdf” as an example.

 

 

8. To protect user privacy, before accessing the sensitive privacy data, you need to find the Info configuration in your iOS 10.0 or higher iOS project and configure the relevant privacy terms as shown in the following picture.

 

 

NSCameraUsageDescription
Your consent is required before you could access the function.

NSMicrophoneUsageDescription
Your consent is required before you could access the function.

NSPhotoLibraryAddUsageDescription
Your consent is required before you could access the function.

NSPhotoLibraryUsageDescription
Your consent is required before you could access the function.

 

For Android:

 

1. Open the “android/build.gradle” file located in the project root directory and add the mavenCentral repository:

repositories {
    google()
+   mavenCentral()
}

 

2. Open the app’s Gradle build file “android/app/build.gradle”:

open android/app/build.gradle

 

3. Modify the minimum SDK version, all this is done inside the android section:

android {
     defaultConfig {
-        minSdkVersion rootProject.ext.minSdkVersion
+        minSdkVersion 21
         ...
     }
 }

 

4. Add ComPDFKit SDK inside the dependencies section:

dependencies {
    ...
+    implementation 'com.compdf:compdfkit:1.11.0'
+    implementation 'com.compdf:compdfkit-ui:1.11.0'
+    implementation 'com.compdf:compdfkit-tools:1.11.0'
}

 

5. open “android/app/src/main/AndroidManifest.xml”, add ComPDFKit License and Storage Permission.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.compdfkit.flutter.example">
    
    <!-- Required to read and write documents from device storage -->
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        ...>
        ...
        <!-- Please replace it with your ComPDFKit license -->
+        <meta-data
+            android:name="compdfkit_key"
+            android:value="{your license key}" />
				...
    </application>
</manifest>

 

6. Enable viewBinding in the Android node setting of app/build.gradle.

android {
		...
    buildFeatures {
        viewBinding = true
    }
}

 

7. Copy the pdf folder and res/layout code from the sample project — Android project, to your project.

 

 

8. Open the MainApplication file and fill in the following code in the openDocumentgetPackages() method:

@Override
protected List getPackages() {
  @SuppressWarnings("UnnecessaryLocalVariable")
  List packages = new PackageList(this).getPackages();
+  packages.add(new PDFReactPackage());
  return packages;
}

 

9. Add PDFActivity in “AndroidManifest.xml” file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.projectname">
  <application
    ...>
    ...
+    <activity
+              android:name=".pdf.PDFActivity"
+              android:configChanges="keyboardHidden|orientation|screenSize"
+              android:windowSoftInputMode="adjustPan"
+              android:exported="true"/>

    </activity>
  </application>

 

10. Copy the sample pdf file to the assets directory:

 

 

11. Open your “App.tsx” file.

open App.tsx

 

12. Replace all the contents of “App.tsx” with the following code.

 

import React, { Component } from 'react';
 import {
   Platform,
   StyleSheet,
   Text,
   View,
   Button,
   NativeModules
 } from 'react-native';

 var nativeModule = NativeModules.OpenNativeModule;
 // var analyticsModule = NativeModules.UMAnalyticsModule;

 const instructions = Platform.select({
   ios: 'Press Cmd+R to reload,\n' +
     'Cmd+D or shake for dev menu',
   android: 'Double tap R on your keyboard to reload,\n' +
     'Shake or press menu button for dev menu',
 });

 

 // set disable functionality:
 const configuration = {
                         "modeConfig": {
                           // setting the default display mode when opening
                           // viewer、annotations、contentEditor、forms、digitalSignatures
                           "initialViewMode": "viewer"
                         },
                         // top toolbar configuration:
                         "toolbarConfig": {
                           "androidAvailableActions": [
                             "thumbnail",
                             "search",
                             "bota",
                             "menu"
                           ],
                           // ios top toolbar left buttons
                           "iosLeftBarAvailableActions":[
                             "back",
                             "thumbnail"
                           ],
                           // ios top toolbar right buttons
                           "iosRightBarAvailableActions":[
                             "search",
                             "bota",
                             "menu"
                           ],
                           "availableMenus": [
                             "viewSettings",
                             "documentEditor",
                             "security",
                             "watermark",
                             "documentInfo",
                             "save",
                             "share",
                             "openDocument"
                           ]
                         },
                         // readerView configuration
                         "readerViewConfig": {
                           "linkHighlight": true,
                           "formFieldHighlight": true
                         }
                       };
 
 type Props = {};
 export default class App extends Component {
   render() {
     return (
       
         
           Welcome to React Native!
         
         
           To get started, edit App.js
         
         
           {instructions}
         
          {
             this.jumpToNativeView();
           }}
         />
       
     );
   }
   
   jumpToNativeView() {
        NativeModules.OpenPDFModule.openPDF(JSON.stringify(configuration))
        // NativeModules.OpenPDFModule.openPDFByConfiguration(filePath, password, JSON.stringify(configuration))
   }
 }
 
 const styles = StyleSheet.create({
   container: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center',
     backgroundColor: '#F5FCFF',
   },
   welcome: {
     fontSize: 20,
     textAlign: 'center',
     margin: 10,
   },
   instructions: {
     textAlign: 'center',
     color: '#333333',
     marginBottom: 5,
   },
 });

 

Display a PDF

 

1. We have provided two quick ways to open PDFs:

         - Open the default document directly.

NativeModules.OpenPDFModule.openPDF(JSON.stringify(configuration))

 

         - Open the document in the specified path.

NativeModules.OpenPDFModule.openPDFByConfiguration(String filePath, String password, String configuration)

 

2. The app is now ready to launch! Go back to the terminal.

//Run on Android devices
npx react-native run-android

 

//Run on iOS devices
npx react-native run-ios



Frequently Asked Questions

 

I'm considering using Flutter or React Native for my mobile app development. Do I need to purchase separate iOS and Android licenses, or can I get away with just one license?

 

  • When you purchase ComPDFKit for Flutter: It can be used for iOS and Android development.
  • When you purchase ComPDFKit for React Native: It can be used for iOS and Android development.
  • When you purchase ComPDFKit for iOS: It can only be used for iOS app development. Customers can choose native iOS frameworks or cross-platform frameworks (if they choose the cross-platform framework, it can only be used for developing iOS apps under the cross-platform framework).
  • When you purchase ComPDFKit for Android: It can only be used for Android app development. Customers can choose native Android frameworks or cross-platform frameworks (if they choose the cross-platform framework, it can only be used for developing Android apps under the cross-platform framework).

 

 

Create a PDF Viewer with Open Source React-Native-PDF

 

Create a Project

 

1. In the terminal app, change the current working directory to the location you wish to save your project. In this example, we’ll use the ~/Documents/ directory cd ~/Documents.

 

2. Create the React Native project by running the following command:

react-native init compdfkit_rn

 

3. In the terminal app, change the location of the current working directory inside the newly created project:

cd compdfkit_rn

 

Add react-native-pdf

 

1. To make React Native PDF work you also need another library react native blob util. Install both libraries using the command given below.

npm install react-native-pdf react-native-blob-util --save

 

2. Also, don’t forget to run the pod install command inside the iOS folder. On Android, open android/app/build.gradle and add the following inside the android {} tag.

 

packagingOptions {
       pickFirst 'lib/x86/libc++_shared.so'
       pickFirst 'lib/x86_64/libjsc.so'
       pickFirst 'lib/arm64-v8a/libjsc.so'
       pickFirst 'lib/arm64-v8a/libc++_shared.so'
       pickFirst 'lib/x86_64/libc++_shared.so'
       pickFirst 'lib/armeabi-v7a/libc++_shared.so'
     }

 

Display a PDF

 

Now, you can create a simple PDF viewer in react native as given below.

 

import React from 'react';
import {StyleSheet, Dimensions, View, Platform} from 'react-native';
import Pdf from 'react-native-pdf';

const source = {
  uri: 'https://www.africau.edu/images/default/sample.pdf',
  cache: true,
};
const App = () => {
  return (
    
       {
          console.log(`number of pages: ${numberOfPages}`);
        }}
        onPageChanged={(page, numberOfPages) => {
          console.log(`current page: ${page}`);
        }}
        onError={error => {
          console.log(error);
        }}
        onPressLink={uri => {
          console.log(`Link presse: ${uri}`);
        }}
        style={styles.pdf}
      />
    
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    marginTop: 25,
  },
  pdf: {
    flex: 1,
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
})

 

This Pdf component displays the PDF file and provides callbacks for various events, such as when the PDF file is completely loaded, when a page is changed, when an error occurs, and when a link is pressed.



React Native PDF Library Comparison

 

We can see the popular open-source React Native PDF library is react-native-pdf. But it only supports reading PDFs. For more PDF reading and editing, a commercial license is necessary.

 

ComPDFKit is a comprehensive, mature, and continuously updated PDF library. It not only supports all PDF reading and editing features but also stands out among competitors with the integration of AI. Its data extraction, text editing, and AI-powered file conversion capabilities have been highly praised by customers. Contact us now to experience the effectiveness of our PDF technology!

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

PDF Libraries for React Native

Features

Downloads on NPM (Data on Dec 5, 2024)

Last Publish

License Type

Issues

Commercial React Native PDF Library

ComPDFKit React Native PDF Library

Comprehensive PDF Reading and editing. Feature Lists.

/

V 2.1.3-2

Sep 27, 2024

Commercial License Needed

0

Nutrient React Native Library

Comprehensive PDF Reading and editing. View details.

/

V 6.7.6

Oct 30, 2024

Commercial License Needed

330

Apryse React Native PDF Library

Comprehensive PDF Reading and editing. View details.

/

Pre-Java17

Mar 19, 2024

Commercial License Needed

0

Open Source React Native PDF Library

react-native-pdf

- Read a PDF from url, blob, local file, or asset and can cache it.

- Display horizontally or vertically

- Drag and zoom

- Double tap for zoom

- Support password-protected pdf

- Jump to a specific page in the pdf

143,695 / Week

V 6.7.6

Dec 3, 2024

MIT

329

react-native-view-pdf

- Render PDF using URL, BASE64 data or local file

11,899 / Week

V 0.14.0

Aug 16, 2022

MIT

/

react-native-pdf-light

- Render PDF

- Zoom pages

- Scroll

- Render annotations

1,388 / Week

V 2.4.1

Sep 23, 2024

MIT

3

react-native-pdf-renderer

- Render PDF

1,260 / Week

V 1.4.0

Sep 26, 2024

MIT

2

react-native-file-viewer

- Read PDFs

- Search PDFs

96,123 / Week

V 2.1.5

Dec 12, 2021

MIT

33

 

 

Conclusion

 

In conclusion, this article has provided a comprehensive guide to creating a React Native PDF viewer along with a comparison of different React Native PDF libraries. As you've seen, there are many open-source PDF libraries available for the React Native development framework. 

 

However, if your React Native project demands more advanced PDF functionalities, such as PDF annotations or form filling, it is highly advisable to consider commercial libraries like ComPDFKit. These solutions often offer robust features and better support, ensuring your app meets all necessary requirements.

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

 

FAQ About React Native PDF

 

  1. How do you open a PDF in React Native?

You can open a PDF in React Native by setting up a React Native project, installing a PDF library like react-native-pdf or ComPDFKit, adding PDF documents to the project, and implementing a component to display the PDF. Refer to the table above to choose a suitable React Native PDF Library.

 

  1. What are the advantages of using the ComPDFKit PDF Library for React Native?
  • The ComPDFKit React Native PDF Library offers more functionalities such as PDF editing, form filling, comparing, converting, and OCR features.
  • It is continuously updated to keep pace with market PDF technology developments.
  • Offers reasonable pricing based on needed features.
  • Provides prompt technical support.

 

  1. What are the steps to set up a React Native PDF Viewer?

To set up a React Native PDF Viewer, create a new React Native application, install the necessary dependencies (react-native-pdf or PSPDFKit), add PDF documents to the project, and write code to render the PDF in a component.

 

  1. What is the best library to build a React Native PDF Viewer?

Two popular libraries for building a PDF viewer in React Native are the open-source react-native-pdf and the more feature-rich commercial library ComPDFKit React Native PDF Library.

 

  1. How do you add annotations, edit PDF text, and edit pages in a React Native application?

To add annotations, edit PDF text, or edit pages, the only React Native PDF Library that provides such features are commercial PDF Libraries like ComPDFKit.