Tutorials

Integrate ComPDFKit React Native PDF SDK via NPM

By ComPDFKit | Mon. 24 Jun. 2024
React Native

Integrate ComPDFKit React Native PDF SDK via NPM

 

With the development of ComPDFKit, now you can integrate React Native PDF SDK of ComPDFKit via NPM to build your React Native iOS / Android PDF viewer, editor, annotator, converter, etc.

 

It's easy and convenient to embed ComPDFKit PDF SDK into your React Native cross-platform applications, with just a few lines of code. This is a step-by-step guide for you to integrate ComPDFKit React Native PDF SDK via NPM. Let's take a few minutes to get started.

 

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

 

 

Step 1: Integration Requirements for React Native NPM Integration

 

React Native Android Integration Requirements

Please install the following required packages:

 

Operating Environment Requirements:

  • Android minSdkVersion of 21 or higher.
  • ComPDFKit SDK 2.0.1 or higher.

 

React Native iOS Integration Requirements

Please install the following required packages:

  

Operating Environment Requirements:

  • ComPDFKit SDK 2.0.1 or higher.
  • React Native dependency to version 3.0.0 or higher.
  • iOS 10.0 or higher.

 

Step 2: Creating a New React Native Project

Let's create a simple app that integrates ComPDFKit for React Native.

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 MyApp

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

cd MyApp

  

 

Step 3: NPM Install and Integrate the Dependency of ComPDFKit PDF SDK

 

You can install and integrate ComPDFKit PDF SDK for React Native on Github or NPM. Follow the instructions below to install ComPDFKit PDF SDK for React Native:

 

How to Download from NPM

 

Through ComPDFKit NPM package:

In MyApp folder, install run the following commands:

yarn add @compdfkit_pdf_sdk/react_native

 

Android PDF SDK React Native Integration

  1. Open android/app/src/main/AndroidManifest.xml and add Internet Permission and Storage Permission
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.compdfkit.flutter.example">

+    <uses-permission android:name="android.permission.INTERNET"/>

    <!-- 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"/>

    <!-- Optional settings -->
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

    <application
+    android:requestLegacyExternalStorage="true"
        ...>
  ...
    </application>
</manifest>

2. Copy the sample PDF file to the assets directory

 

 

iOS PDF SDK React Native Integration

 

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

open ios/Podfile

2. Add the following line to the target 'MyApp' do ... end block:

target 'MyApp' do
    # ...
+  pod "ComPDFKit", podspec:'https://www.compdf.com/download/ios/cocoapods/xcframeworks/compdfkit/2.0.1.podspec'
+  pod "ComPDFKit_Tools", podspec:'https://www.compdf.com/download/ios/cocoapods/xcframeworks/compdfkit_tools/2.0.1.podspec'
    # ...
end

Note: If SSL network requests fail to download the ComPDFKit library when you run pod install, you can use the following method instead.

target 'MyApp' do
    # ...
+  pod 'ComPDFKit', :git => 'https://github.com/ComPDFKit/compdfkit-pdf-sdk-ios-swift.git', :tag => '2.0.1'
+  pod 'ComPDFKit_Tools', :git => 'https://github.com/ComPDFKit/compdfkit-pdf-sdk-ios-swift.git', :tag => '2.0.1'
    # ...
end

3. In the ios folder, run pod install.

4. Open your project’s Workspace in Xcode:

open ios/MyApp.xcworkspace

Make sure the deployment target is set to 10.0 or higher:

 

 

5. 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 "PDF_Document.pdf" as an example.

 

Add the PDF document you want to display to your application

 

<key>NSCameraUsageDescription</key>
<string>Your consent is required before you could access the function.</string>

<key>NSMicrophoneUsageDescription</key>
<string>Your consent is required before you could access the function.</string>

<key>NSPhotoLibraryAddUsageDescription</key>
<string>Your consent is required before you could access the function.</string>

<key>NSPhotoLibraryUsageDescription</key>
<string>Your consent is required before you could access the function.</string>

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>

 

 

Step 4: Apply the License Key for React Native Project

 

ComPDFKit for React Native is a commercial SDK, that requires a license to grant developer permission to release their apps. Each license is only valid for one bundle ID or applicationId in development mode. Other flexible licensing options are also supported, please contact our marketing team to know more.

 

ComPDFKit provides a 30-day free trial license for React Native PDF SDK.

 

To initialize ComPDFKit using a license key, call either of the following before using any other ComPDFKit APIs or features:

  • Online certification
import { ComPDFKit } from '@compdfkit_pdf_sdk/react_native';

type Props = {};
export default class App extends Component<Props> {
  ...

  componentDidMount(){
    // Fill in your online license
    ComPDFKit.initialize('your android platform compdfkit license', 'your ios platform compdfkit license')
  }
  // ...
}

 

  • Offline authentication
import { ComPDFKit } from '@compdfkit_pdf_sdk/react_native';

type Props = {};
export default class App extends Component<Props> {
  ...

  componentDidMount(){
    // Fill in your offline license
    if(Platform.OS == 'android') {
      ComPDFKit.init_('your compdfkit license for android')
    } else {
      ComPDFKit.init_('your compdfkit license for ios')
    }
  }
// ...
}

 

Step 5: Run React Native PDF Project

  1. Replace App.js (or App.tsx) with what is shown for usage example
/**
 * Copyright © 2014-2024 PDF Technologies, Inc. All Rights Reserved.
 *
 * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
 * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE ComPDFKit LICENSE AGREEMENT.
 * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
 * This notice may not be removed from this file.
 */

 import React, { Component } from 'react';
 // import DocumentPicker from 'react-native-document-picker'
 import {
   StyleSheet,
   Text,
   View,
   TouchableOpacity,
   SafeAreaView
 } from 'react-native';
 import { ComPDFKit } from '@compdfkit_pdf_sdk/react_native';
 import { Platform } from 'react-native';

 type Props = {};

 export default class App extends Component<Props> {

   state = {
     versionCode: ''
   }

   constructor(props: Props) {
     super(props)
     this.initialize()
     this.getVersionCode()
   }

   async getVersionCode() {
     // Get the version code of ComPDFKit SDK
     var version = await ComPDFKit.getVersionCode()
     this.setState({
       versionCode: version
     })
   }

   async initialize() {
     // Online certification, Fill in your online license
     // Returns true if initialization is successful, otherwise returns false.
     var result = await ComPDFKit.initialize('compdfkit android license', 'compdfkit ios license')
     console.log("ComPDFKitRN", "initialize:", result)

     // Offline authentication, Fill in your offline license
     // var result;
     // if(Platform.OS == 'android') {
     //   result = await ComPDFKit.init_('your compdfkit license')
     // } else {
     //   result = await ComPDFKit.init_('your compdfkit license')
     // }
     // console.log("ComPDFKitRN", "init_:", result)
   }

   /**
    * Open the sample document embedded in Android or iOS project.
    */
   openSample(){
     var samplePDF: string = Platform.OS == 'android' ? 'file:///android_asset/PDF_Document.pdf' : 'PDF_Document.pdf'
     // We provide default UI and PDF property related configurations here, you can modify configuration options according to your needs.
     var config = ComPDFKit.getDefaultConfig({

     })
     ComPDFKit.openDocument(samplePDF, '', config)
   }

   /**
    * Pick a PDF file from the local storage of Android or iOS device, this example uses the `react-native-document-picker` package,
    * If you want to use this example, please add this package to your project first.
    * {@link https://www.npmjs.com/package/react-native-document-picker}
    * 
    */
   pickPDFFile(){
     try {
//       const pickerResult = DocumentPicker.pick({
//         type: [DocumentPicker.types.pdf]
//       });
//       pickerResult.then(res => {
//         ComPDFKit.openDocument(res[0]?.uri as string, '', ComPDFKit.getDefaultConfig({}))
//       })
     } catch (err) {
     }
   }

   render() {
     return (
       <SafeAreaView style={{ flex: 1 }}>
         <View style={styles.scaffold}>
           <View style={styles.appBar}>
             <Text style={styles.mediumTitle}>
               ComPDFKit PDF SDK for ReactNative
             </Text>
           </View>
           <View style={styles.container}>
             <TouchableOpacity onPress={() => {
               this.openSample()
             }}>
               <View style={styles.funItem}>
                 <Text style={{ fontWeight: 'bold' }}>{'Open Sample'}</Text>
               </View>
             </TouchableOpacity>

             <View style={styles.dividingLine} />

             <TouchableOpacity onPress={() => {
               this.pickPDFFile()
             }}>
               <View style={styles.funItem}>
                 <Text style={{ fontWeight: 'bold' }}>{'Pick Document'}</Text>
               </View>
               <View style={styles.dividingLine} />

             </TouchableOpacity>

             <View style={styles.buttom}>
               <Text style={styles.body2}>ComPDFKit for {Platform.OS == 'android' ? 'Android' : 'iOS'} {this.state.versionCode}</Text>
             </View>
           </View>
         </View>
       </SafeAreaView>

     );
   }
 }

 const styles = StyleSheet.create({
   appBar: {
     height: 56,
     backgroundColor: '#FAFCFF',
     elevation: 4,
     flexDirection: "row",
     justifyContent: "space-between",
     alignItems: "center",
     padding: 16
   },
   mediumTitle: {
     fontSize: 16,
   },
   body2: {
     textAlign: 'center',
     fontSize: 12
   },
   scaffold: {
     flex: 1,
   },
   container: {
     marginHorizontal: 16,
     marginVertical: 8,
     flex: 1,
     // backgroundColor: '#F5FCFF',
   },
   funItem: {
     height: 56,
     justifyContent: 'center',
     textAlign: 'center'
   },
   dividingLine: {
     height: 0.5, backgroundColor: '#4D333333', width: '100%'
   },
   buttom: {
     flex: 1,
     justifyContent: 'flex-end',
   }
 });

 

2. Finally, run the project in the root project directory

Run on Android to get a React Native Android PDF viewer:

react-native run-android

Run on iOS to get a React Native iOS PDF viewer:

react-native run-ios

 

 

Conclusion

 

ComPDFKit is continuously upgraded and fast-developed. Now you can access and download our React Native PDF SDK on many third-party platforms such as Github, NPM, etc. Contact ComPDFKit if you have any questions or problems with the React-Native-PDF SDK integration.

 

More guides about ComPDFKit PDF SDK for React Native can be accessed on React Native documentation page.

 

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