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 ios/RNTPTDocumentViewManager.m.

Add the method key that matches the TS declaration:

Obj-C

1RCT_CUSTOM_VIEW_PROPERTY(pageChangeOnTap, BOOL, RNTPTDocumentView)
2{
3 if (json) {
4 view.pageChangeOnTap = [RCTConvert BOOL:json];
5 }
6}

4. Implement the methods to set the property

Open the ios/RNTPTDocumentView.h interface file and add a new property to the RNTPTDocumentView class:

Obj-C

1@interface RNTPTDocumentView
2
3...
4
5@property (nonatomic, assign) BOOL pageChangeOnTap;
6
7...
8
9@end

Open the ios/RNTPTDocumentView.m implementation file, and add the property setter:

Obj-C

1- (void)setPageChangeOnTap:(BOOL)pageChangeOnTap
2{
3 _pageChangeOnTap = pageChangeOnTap;
4
5 if (self.documentViewController) {
6 [self applyViewerSettings];
7 }
8}

In this case, we call the applyViewerSettings method and access the changesPageOnTap property to complete our implementation:

Obj-C

1- (void)applyViewerSettings
2{
3 ...
4
5 // Page change on tap.
6 self.documentViewController.changesPageOnTap = self.pageChangeOnTap;
7
8 ...
9}

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. Add method to module

The JS name of the new method is getField and the native method is getFieldForDocumentViewTag:fieldname:.

In ios/RNTPTDocumentViewModule.m, use the RCT_REMAP_METHOD macro to expose the native method to JS and simultaneously specify the JS name of the method.

Obj-C

1RCT_REMAP_METHOD(getField,
2 getFieldForDocumentViewTag:(nonnull NSNumber *)tag
3 fieldName:(NSString *)fieldName
4 resolver:(RCTPromiseResolveBlock)resolve
5 rejecter:(RCTPromiseRejectBlock)reject)
6{
7 @try {
8 NSDictionary *field = [[self documentViewManager] getFieldForDocumentViewTag:tag fieldName:fieldName];
9 resolve(field);
10 }
11 @catch (NSException *exception) {
12 reject(@"set_value_for_fields", @"Failed to set value on fields", [self errorFromException:exception]);
13 }
14}

4. Implement the native method

Add the native method to ios/RNTPTDocumentViewManager.h:

Obj-C

1- (NSDictionary *)getFieldForDocumentViewTag:(NSNumber *)tag fieldName:(NSString *)fieldName;

Implement the native method in ios/RNTPTDocumentViewManager.m:

Obj-C

1- (NSDictionary *)getFieldForDocumentViewTag:(NSNumber *)tag fieldName:(NSString *)fieldName
2{
3 RNTPTDocumentView *documentView = self.documentViews[tag];
4 if (documentView) {
5 return [documentView getField:fieldName];
6 } else {
7 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Unable to get field for tag" userInfo:nil];
8 return nil;
9 }
10}

5. Implement the helper method

Add the following to ios/RNTPTDocumentView.h:

Obj-C

1- (NSDictionary *)getField:(NSString *)fieldName;

Implement the method in ios/RNTPTDocumentView.m:

Obj-C

1- (NSDictionary *)getField:(NSString *)fieldName
2{
3 PTPDFViewCtrl *pdfViewCtrl = self.currentDocumentViewController.pdfViewCtrl;
4 if (!pdfViewCtrl) {
5 return nil;
6 }
7
8 NSMutableDictionary <NSString *, NSObject *> *fieldMap = [[NSMutableDictionary alloc] init];
9
10 NSError *error;
11 [pdfViewCtrl DocLockReadWithBlock:^(PTPDFDoc * _Nullable doc) {
12
13 PTField *field = [doc GetField:fieldName];
14 if (field && [field IsValid]) {
15
16 PTFieldType fieldType = [field GetType];
17 NSString* typeString;
18 if (fieldType == e_ptbutton) {
19 typeString = PTFieldTypeButtonKey;
20 } else if (fieldType == e_ptcheck) {
21 typeString = PTFieldTypeCheckboxKey;
22 [fieldMap setValue:[[NSNumber alloc] initWithBool:[field GetValueAsBool]] forKey:PTFormFieldValueKey];
23 } else if (fieldType == e_ptradio) {
24 typeString = PTFieldTypeRadioKey;
25 [fieldMap setValue:[field GetValueAsString] forKey:PTFormFieldValueKey];
26 } else if (fieldType == e_pttext) {
27 typeString = PTFieldTypeTextKey;
28 [fieldMap setValue:[field GetValueAsString] forKey:PTFormFieldValueKey];
29 } else if (fieldType == e_ptchoice) {
30 typeString = PTFieldTypeChoiceKey;
31 [fieldMap setValue:[field GetValueAsString] forKey:PTFormFieldValueKey];
32 } else if (fieldType == e_ptsignature) {
33 typeString = PTFieldTypeSignatureKey;
34 } else {
35 typeString = PTFieldTypeUnknownKey;
36 }
37
38 [fieldMap setValue:typeString forKey:PTFormFieldTypeKey];
39 [fieldMap setValue:fieldName forKey:PTFormFieldNameKey];
40 }
41
42
43 } error:&error];
44
45 if (error) {
46 NSLog(@"Error: There was an error while trying to get field. %@", error.localizedDescription);
47 }
48
49 return [[fieldMap allKeys] count] == 0 ? nil : fieldMap;
50}

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. Send event to JS

Add the following protocol method to ios/RNTPTDocumentView.h:

Obj-C

1@protocol RNTPTDocumentViewDelegate <NSObject>
2@optional
3...
4- (void)layoutChanged:(RNTPTDocumentView *)sender;
5...
6@end

Implement the protocol method in ios/RNTPTDocumentViewManager.m, under the Events pragma mark. Notice that we call RNTPTDocumentView's RCTBubblingEventBlock onChange event handler block, which will call the callback prop in JS.

Obj-C

1#pragma mark - Events
2...
3- (void)layoutChanged:(RNTPTDocumentView *)sender
4{
5 if (sender.onChange) {
6 sender.onChange(@{
7 @"onLayoutChanged" : @"onLayoutChanged",
8 });
9 }
10}

4. Call layoutChanged protocol method in iOS

In step 3, we implemented the protocol method layoutChanged to send events to JS, but we haven't used it yet.

Add the following protocol method to ios/DocumentViewController/RNTPTDocumentViewController.h:

Obj-C

1@protocol RNTPTDocumentBaseViewControllerDelegate <PTToolManagerDelegate>
2@required
3...
4- (void)rnt_documentViewControllerLayoutDidChange:(PTDocumentBaseViewController *)documentViewController;
5...
6@end

Implement this protocol method in ios/RNTPTDocumentView.m, under the RNTPTDocumentViewControllerDelegate pragma mark. This is where we use layoutChanged.

Obj-C

1#pragma mark - <RNTPTDocumentViewControllerDelegate>
2...
3- (void)rnt_documentViewControllerLayoutDidChange:(PTDocumentBaseViewController *)documentViewController
4{
5 if ([self.delegate respondsToSelector:@selector(layoutChanged:)]) {
6 [self.delegate layoutChanged:self];
7 }
8}

5. Receive layout changes from PDFViewCtrl

The PTPDFViewCtrlDelegate protocol contains the method pdfViewCtrlOnLayoutChanged. This method allows adopting delegates to respond to the PTPDFViewCtrl class when page layout has changed.

Implement pdfViewCtrlOnLayoutChanged in the following files:

  • ios/DocumentViewController/RNTPTDocumentViewController.m
  • ios/DocumentViewController/RNTPTDocumentController.m
  • ios/DocumentViewController/RNTPTCollaborationDocumentViewController.m
  • ios/DocumentViewController/RNTPTCollaborationDocumentController.m

Obj-C

1#pragma mark - <PTPDFViewCtrlDelegate>
2...
3- (void)pdfViewCtrlOnLayoutChanged:(PTPDFViewCtrl *)pdfViewCtrl
4{
5 if ([self.delegate respondsToSelector:@selector(rnt_documentViewControllerLayoutDidChange:)]) {
6 [self.delegate rnt_documentViewControllerLayoutDidChange:self];
7 }
8}

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 iOS, then you're all done!

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

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