Add an API for React Native

## Introduction

The React Native API for Apryse Mobile SDK includes all of the most used functions and methods for viewing, annotating and saving PDF documents. However, it is possible your app may need access to APIs that are available as part of the native API, but are not directly available to React Native.

This guide provides an example of how to add the following to the React Native interface:

  • pageChangeOnTap prop that determines whether page will turn left or right when tapping corresponding edges.
  • getField function which retrieves information about a field using its name.
  • onLayoutChanged event listener that is raised when the layout of viewer has changed.

You can follow the same pattern to add new functions and props that your React Native app may need. The new additions could be simple ones, which expose one piece of functionality, or custom ones, that expose a series of native commands under the hood.

Prior to following this guide, we highly recommend you to go through the official guide here: Native UI Components to have a better understanding of the system.

1. Fork and clone Apryse's React Native Repo

The source is hosted on GitHub here: https://github.com/ApryseSDK/pdftron-react-native

Fork the project and clone a copy of the repository to your disk.

Adding the pageChangeOnTap prop

2. Add prop to DocumentView.tsx interface file

The DocumentView.tsx interface file lists all of the React Native props on the DocumentView component.

Add the prop declaration:

JavaScript

1static propTypes = {
2 pageChangeOnTap: PropTypes.bool,
3};

For props that accept Config constants or arrays of Config constants, use the oneOf and arrayOf helper methods. These helpers return flexible types that allow custom checks for TypeScript users, while maintaining standard run-time checks for all users.

3. Define a ReactProp matches the TS declaration

Open file /android/src/main/java/com/pdftron/reactnative/viewmanagers/DocumentViewViewManager.java.

Add the method key that matches the TS declaration:

Java

1@ReactProp(name = "pageChangeOnTap")
2public void setPageChangeOnTap(DocumentView documentView, boolean pageChangeOnTap) {
3 documentView.setPageChangeOnTap(pageChangeOnTap);
4}

4. Implement the method to set the property

Open file /android/src/main/java/com/pdftron/reactnative/views/DocumentView.java.

Add the implementation:

Java

1public void setPageChangeOnTap(boolean pageChangeOnTap) {
2 Context context = getContext();
3 if (context != null) {
4 PdfViewCtrlSettingsManager.setAllowPageChangeOnTap(context, pageChangeOnTap);
5 }
6}

The actual implementation will depend on the actual functionality.

Adding the getField function

2. Add function to DocumentView.tsx interface file

The DocumentView.tsx interface file lists all of the React Native functions on the DocumentView component.

Add the function declaration:

JavaScript

1getField = (fieldName: string): Promise<void | {fieldName: string, fieldValue?: any, fieldType?: string}> => {
2 const tag = findNodeHandle(this._viewerRef);
3 if(tag != null) {
4 return DocumentViewManager.getField(tag, fieldName);
5 }
6 return Promise.resolve();
7}

All functions return Promise<void | T> where T is the expected return type upon success. If the function returns void upon success, simply put Promise<void>.

While you are adding types, consider representing objects with reusable object types. You can use existing ones, or create a new type alias or interface in AnnotOptions.ts (see Object Types).

3. Receive the new method from JavaScript

Add this method to /android/src/main/java/com/pdftron/reactnative/modules/DocumentViewModule.java:

Java

1@ReactMethod
2public void getField(final int tag, final String fieldName, final Promise promise) {
3 getReactApplicationContext().runOnUiQueueThread(new Runnable() {
4 @Override
5 public void run() {
6 try {
7 WritableMap field = mDocumentViewInstance.getField(tag, fieldName);
8 promise.resolve(field);
9 } catch (Exception ex) {
10 promise.reject(ex);
11 }
12 }
13 });
14}

4. Define the caller method

Add the following to /android/src/main/java/com/pdftron/reactnative/viewmanagers/DocumentViewViewManager.java:

Java

1public WritableMap getField(int tag, String fieldName) throws PDFNetException {
2 DocumentView documentView = mDocumentViews.get(tag);
3 if (documentView != null) {
4 return documentView.getField(fieldName);
5 } else {
6 throw new PDFNetException("", 0L, getName(), "getField", "Unable to find DocumentView.");
7 }
8}

5. Implement the helper method

Add the following to /android/src/main/java/com/pdftron/reactnative/views/DocumentView.java:

Java

1public WritableMap getField(String fieldName) throws PDFNetException {
2 PDFViewCtrl pdfViewCtrl = getPdfViewCtrl();
3 PDFDoc pdfDoc = pdfViewCtrl.getDoc();
4
5 WritableMap fieldMap = null;
6 boolean shouldUnlock = false;
7
8 try {
9 pdfViewCtrl.docLockRead();
10 shouldUnlock = true;
11
12 Field field = pdfDoc.getField(fieldName);
13
14 if (field != null && field.isValid()) {
15 fieldMap = Arguments.createMap();
16 int fieldType = field.getType();
17 String typeString;
18 switch (fieldType) {
19 case Field.e_button:
20 typeString = FIELD_TYPE_BUTTON;
21 break;
22 case Field.e_check:
23 typeString = FIELD_TYPE_CHECKBOX;
24 fieldMap.putBoolean(KEY_FIELD_VALUE, field.getValueAsBool());
25 break;
26 case Field.e_radio:
27 typeString = FIELD_TYPE_RADIO;
28 fieldMap.putString(KEY_FIELD_VALUE, field.getValueAsString());
29 break;
30 case Field.e_text:
31 typeString = FIELD_TYPE_TEXT;
32 fieldMap.putString(KEY_FIELD_VALUE, field.getValueAsString());
33 break;
34 case Field.e_choice:
35 typeString = FIELD_TYPE_CHOICE;
36 fieldMap.putString(KEY_FIELD_VALUE, field.getValueAsString());
37 break;
38 case Field.e_signature:
39 typeString = FIELD_TYPE_SIGNATURE;
40 break;
41 default:
42 typeString = FIELD_TYPE_UNKNOWN;
43 break;
44 }
45
46 fieldMap.putString(KEY_FIELD_NAME, fieldName);
47 fieldMap.putString(KEY_FIELD_TYPE, typeString);
48 }
49 } finally {
50 if (shouldUnlock) {
51 pdfViewCtrl.docUnlockRead();
52 }
53 }
54 return fieldMap;
55}

The logic is to get the PDF view controller and if the field names are valid, use the controller to get the fields from the current document.

Adding the onLayoutChanged event listener

2. Define the new listener in TS

Event listeners are handled in DocumentView.tsx. Add the following to the file:

JavaScript

1static propTypes = {
2 ...
3 onLayoutChanged: func<() => void>(),
4}
5
6onChange = (event) => {
7 if (event.nativeEvent.onLeadingNavButtonPressed) {
8 ...
9 } else if (event.nativeEvent.onLayoutChanged) {
10 if (this.props.onLayoutChanged) {
11 this.props.onLayoutChanged();
12 }
13 }
14}

The onLayoutChanged event listener does not require any arguments. If your event listener requires arguments, access them using event.nativeEvent.exampleArg.

For event listeners and other props that accept functions, use the func helper method. This helper returns flexible types that allow custom checks for TypeScript users, while maintaining standard run-time checks for all users.

While you are adding types, consider representing objects with reusable object types. You can use existing ones, or create a new type alias or interface in AnnotOptions.ts (see Object Types).

3. Add event constant for Android

In android/src/main/java/com/pdftron/reactnative/utils/Constants.java, add a constant to represent the event.

Java

1// EVENTS
2...
3public static final String ON_LAYOUT_CHANGED = "onLayoutChanged";

4. Implement event listener

In /android/src/main/java/com/pdftron/reactnative/views/DocumentView.java, create a new event listener to send the event to JS. This event listener will call the existing method onReceiveNativeEvent when layout changes. Note that the event you want to implement may be a part of an existing event listener.

Java

1private View.OnLayoutChangeListener mLayoutChangedListener = new OnLayoutChangeListener() {
2 @Override
3 public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
4
5 WritableMap params = Arguments.createMap();
6 params.putString(ON_LAYOUT_CHANGED, ON_LAYOUT_CHANGED);
7
8 onReceiveNativeEvent(params);
9 }
10};

5. Set up and remove event listener

In the same file, /android/src/main/java/com/pdftron/reactnative/views/DocumentView.java, add the event listener to our PDFViewCtrl when the document has loaded, and remove the listener when it is no longer necessary.

Java

1@Override
2public void onTabDocumentLoaded(String tag) {
3 super.onTabDocumentLoaded(tag);
4 ...
5 getPdfViewCtrl().addOnLayoutChangeListener(mLayoutChangedListener);
6 ...
7}
8
9@Override
10protected void onDetachedFromWindow() {
11 if (getPdfViewCtrl() != null) {
12 ...
13 getPdfViewCtrl().removeOnLayoutChangeListener(mLayoutChangedListener);
14 }
15 ...
16}

The actual implementation will depend on the actual functionality.

Finishing steps

1. Push the code and integrate the updated source

Now npm install your forked version to your application.

The new functionality is now ready to use.

2. Access the new functionality

The app can now access the new API as follows:

JavaScript

1onDocumentLoaded = () => {
2 this._viewer.getField('someFieldName').then((field) => {
3 if (field !== undefined) {
4 console.log('field name:', field.fieldName);
5 console.log('field value:', field.fieldValue);
6 console.log('field type:', field.fieldType);
7 }
8 });
9}
10
11onLayoutChanged = () => {
12 console.log("Layout changed");
13}
14
15<DocumentView
16 ref={(c) => this._viewer = c}
17 pageChangeOnTap={false}
18 onDocumentLoaded={this.onDocumentLoaded}
19 onLayoutChanged={this.onLayoutChanged}
20 document={this.state.document}
21/>

3. All done!

If you're only developing for Android, then you're all done!

If you're also deploying on iOS, you'll need to complete the necessary steps for iOS.

If you're developing for both iOS and Android, please consider submitting a PR, as upstreaming the change will simplify your developing and make the APIs available for other Apryse customers.

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales