ComPDFKit / compdfkit-pdf-sdk-react-native

ComPDFKit for React Native is a comprehensive SDK that allows you to quickly add PDF functionality to Android and iOS React Native applications.

Home Page:https://www.compdf.com/react-native

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ComPDFKit React-Native PDF Library

Overview

ComPDFKit PDF SDK is a robust PDF library, which offers comprehensive functions for quickly viewing, annotating, editing, and signing PDFs. It is feature-rich and battle-tested, making PDF files process and manipulation easier and faster.

ComPDFKit for React Native allows you to quickly add PDF functions to any Flutter application, elevating your Android and iOS apps to ensure seamless and efficient development.

Related

Key Features

  • Viewer component offers Standard page display modes, Navigation, Text search & selection, Zoom in and out & Fit-page, Text reflow, and more.
  • Annotations component offers Note, Link, Free Text, Line, Square, Circle, Highlight, Underline, Squiggly, Strikeout, Stamp, Ink, Sound, and more.
  • Forms component offers Push Button, Check Box, Radio Button, Text Field, Combo Box, List Box, Signature, and more.
  • Document Editor component offers Split, Extract, Merge, Delete, Insert, Crop, Move, Rotate, Replace, and Exchange pages, etc.
  • Content Editor component offers Copy, Resize, Change Colors, Text Alignment, Find and Replace, etc.
  • Security component offers Encrypt and Decrypt PDFs, Watermark, etc.

If you want to know all the features that ComPDFKit SDK can offer, please see our Feature List.

Get Started

It's easy to embed ComPDFKit into React Native applications with a few lines of code. The following sections describe the optimal systems and environments to support, as well as quick integration steps. Let's take a few minutes to get started.

Requirements

Android

Please install the following required packages:

Operating Environment Requirements:

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

iOS

Please install the following required packages:

Operating Environment Requirements:

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

How to Run a Demo

ComPDFKit PDF SDK for React-Native provides a complete functional demonstration, you can view the sample project in the Example folder.

  1. Enter the sample project directory in the terminal software
cd Downloads/compdfkit-sdk-pdf-react-native/example
  1. Execute the yarn install command to obtain the software package

Android

Execute the following command to run on the Android device

yarn android

iOS

  1. Open your project's Podfile in a text editor:
open ios/Podfile
  1. 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.13.0.podspec'
+  pod 'ComPDFKit', podspec:'https://www.compdf.com/download/ios/cocoapods/xcframeworks/compdfkit/1.13.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
  1. Go to the example/ios folder and run the pod install command:
pod install
  1. Go to the example folder and the app is now ready to launch! Go back to the terminal.
//Run on iOS emulator
npx react-native run-ios

Integrate into a new React-Native APP

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 compdfkit_rn
  3. In the terminal app, change the location of the current working directory inside the newly created project:

    cd compdfkit_rn
  4. Add the ComPDFKit library and import the presented PDF document.

For Android

  1. Open the android/build.gradle file located in the project root directory and add the mavenCentral repository:
repositories {
    google()
+   mavenCentral()
}
  1. Open the app's Gradle build file, android/app/build.gradle:
open android/app/build.gradle
  1. Modify the minimum SDK version, All this is done inside the android section:
 android {
     defaultConfig {
-        minSdkVersion rootProject.ext.minSdkVersion
+        minSdkVersion 21
         ...
     }
 }
  1. Add ComPDFKit SDK inside the dependencies section:
dependencies {
    ...
+    implementation 'com.compdf:compdfkit:1.13.0'
+    implementation 'com.compdf:compdfkit-ui:1.13.0'
+    implementation 'com.compdf:compdfkit-tools:1.13.0'
}
  1. Add Proguard Rules, In the proguard-rules.pro file, please add the obfuscation configuration information for compdfkit as follows:
-keep class com.compdfkit.ui.** {*;}
-keep class com.compdfkit.core.** {*;}
-keep class com.compdfkit.tools.** {*;}
  1. open android/app/src/main/AndroidManifest.xml , 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"/>
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

    <application
+    android:requestLegacyExternalStorage="true"
        ...>
        ...
    </application>
</manifest>
  1. Copy the pdf folder code from the sample project Android project to your project

1-5

  1. Open the MainApplication file and fill in the following code in the getPackages() method
@Override
protected List<ReactPackage> getPackages() {
  @SuppressWarnings("UnnecessaryLocalVariable")
  List<ReactPackage> packages = new PackageList(this).getPackages();
+  packages.add(new PDFReactPackage());
  return packages;
}
  1. Copy the sample pdf file to the assets directory

1-6

For iOS

  1. Open your project's Podfile in a text editor:
open ios/Podfile
  1. 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.13.0.podspec'
+  pod 'ComPDFKit', podspec:'https://www.compdf.com/download/ios/cocoapods/xcframeworks/compdfkit/1.13.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
  1. Go to the compdfkit_rn/ios folder and run the pod install command:
pod install

Note: If SSL network requests fail to download the ComPDFKit library when you run pod install, you can see the processing method in Troubleshooting.

  1. Open your project's Workspace in Xcode:
open ios/PDFView_RN.xcworkspace	
  1. Make sure the deployment target is set to 10.0 or higher:

  1. Import resource file,"OpenPDFModule.swift" is the bridging file for connecting React Native to the iOS native module.

1-2

  1. Search for bridging in the Build Settings and locate the Objective-C Bridging Header option. Then, enter the file path of the header file "ComPDFKit_RN-Bridging-Header.h":

1-9

  1. 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.

  1. 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.

<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>

Apply the License Key

ComPDFKit for React Native is a commercial SDK, which 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.

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

  • Online license
type Props = {};
export default class App extends Component<Props> {
	...
  
  componentDidMount(){
    // Fill in your online license
    NativeModules.OpenPDFModule.initialize('your android platform compdfkit license', 'your ios platform compdfkit license')
  }
  // ...
}
  • Offline license
type Props = {};
export default class App extends Component<Props> {
	...
  
  componentDidMount(){
    // Fill in your offline license
    NativeModules.OpenPDFModule.init_('your compdfkit license')
  }
  // ...
}

Run Project

  1. Create an assets directory in the project's root directory and copy the configuration.json file from the demo to this directory.

2-3-1

  1. Open your App.tsx file:
open App.tsx
  1. Replace the entire contents of App.tsx with the following code snippet:
/**
 * 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 configuration from './assets/configuration.json';
import DocumentPicker from 'react-native-document-picker'
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Button,
  NativeModules
} from 'react-native';


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',
});


type Props = {};
export default class App extends Component<Props> {
  
   componentDidMount(){
      // Fill in your online license
         NativeModules.OpenPDFModule.initialize('your android platform compdfkit license', 'your ios platform compdfkit license')
    
      // Fill in your offline license
      // NativeModules.OpenPDFModule.init_('your compdfkit license')
  }
  
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.tsx
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
        <Button
          title={'Open sample document'}
          onPress={() => {
            this.jumpToNativeView();
          }}
        />
        <View style={{margin:5}}/>
        <Button 
          title={'pick document'}
          onPress={() => {
            try {
              const pickerResult = DocumentPicker.pick({
                type: [DocumentPicker.types.pdf]
              });
              pickerResult.then(res => {
                if (Platform.OS == 'android') {
                  // only android
                  NativeModules.OpenPDFModule.openPDFByUri(res[0].uri, '', JSON.stringify(configuration))
                } else {
                  NativeModules.OpenPDFModule.openPDFByConfiguration(res[0].uri, '', JSON.stringify(configuration))
                }
              })
            } catch (err) {
            }
          }}
        />
      </View>
    );
  }

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

    // android: filePath, ios:URL
    // NativeModules.OpenPDFModule.openPDFByConfiguration(filePath, password, JSON.stringify(configuration))

    // only android platform
    // NativeModules.OpenPDFModule.openPDFByUri(uriString, 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,
  }
});
  1. Go to the example folder and 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

Example APP

To see ComPDFKit for React-Native in action, check out our React-Native example app

Showing a PDF document inside your React-Native app is as simple as this:

// Open the default document directly
NativeModules.OpenPDFModule.openPDF(JSON.stringify(configuration))

// Open the document in the specified path
// The ios platform can use this method to pass in the url string
NativeModules.OpenPDFModule.openPDFByConfiguration(String filePath, String password, String configuration)

// Opening a document using Uri on the Android platform.
NativeModules.OpenPDFModule.openPDFByUri(String uriString, String password, String configuration)

Troubleshooting

1.SSL network request to download 'ComPDFKit' library failed when cocopods downloaded iOS third-party library

If SSL network requests fail to download the ComPDFKit library when you run pod install, replace the third-party platform download address link of the ComPDFKit library and execute pod install

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', :git => 'https://github.com/ComPDFKit/compdfkit-pdf-sdk-ios-swift.git', :tag => '1.13.0'
+  pod 'ComPDFKit_Tools', :git => 'https://github.com/ComPDFKit/compdfkit-pdf-sdk-ios-swift.git', :tag => '1.13.0'

  # 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

Support

ComPDFKit has a professional R&D team that produces comprehensive technical documentation and guides to help developers. Also, you can get an immediate response when reporting your problems to our support team.

  • For detailed information, please visit our Guides page.
  • Stay updated with the latest improvements through our Changelog.
  • For technical assistance, please reach out to our Technical Support.
  • To get more details and an accurate quote, please contact our Sales Team.

License

ComPDFKit PDF SDK supports flexible licensing options, please contact our sales team to know more. Each license is only valid for one application ID in development mode. However, any documents, sample code, or source code distribution from the released package of ComPDFKit PDF SDK to any third party is prohibited.

Note

We are glad to announce that you can register a ComPDFKit API account for a free trial to process 1000 documents per month for free.

Thanks,

The ComPDFKit Team

About

ComPDFKit for React Native is a comprehensive SDK that allows you to quickly add PDF functionality to Android and iOS React Native applications.

https://www.compdf.com/react-native

License:Other


Languages

Language:TypeScript 60.3%Language:Java 9.8%Language:Swift 9.8%Language:Objective-C 5.0%Language:Ruby 4.8%Language:Objective-C++ 3.7%Language:Kotlin 3.5%Language:JavaScript 3.0%Language:C 0.1%