Add an API for Flutter

Introduction

The Flutter 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 Flutter.

There are 2 different ways to use Apryse Flutter API on iOS or Android:

  • Present a document via a plugin.
  • Show an Apryse document view via a Widget.

This guide will demonstrate how to add a new functionality to both approaches.

The examples provided will show you how to add the following to the Flutter interface:

  • readOnly viewer configuration option that determines if the viewer will allow edits to the document.
  • getPageCropBox function that returns a PTRect object containing information about the crop box of a specified page.
  • startZoomChangedListener event listener that is raised when the zoom ratio is changed in the current document.

You can follow the same pattern to add new functions and viewer configuration options that your Flutter app may need. These 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: Writing Platform-specific code to have a better understanding of the system.

1. Fork and clone Apryse's Flutter Repo

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

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

Adding the readOnly viewer configuration option

2. Define the new viewer configuration option in Dart

The config.dart file is responsible for setting all of the viewer configuration options.

Dart

1var _readOnly;
2
3set readOnly(bool value) => _readOnly = value;
4
5Config.fromJson(Map<String, dynamic> json) :
6 _readOnly = json['readOnly'];
7
8Map<String, dynamic> toJson() => {
9 'readOnly': _readOnly,
10};

3. Define the new viewer configuration option in Java

First define a config constant for the property in /android/src/main/java/com/pdftron/pdftronflutter/helpers/PluginUtils.java:

Java

1public static final String KEY_CONFIG_READ_ONLY = "readOnly";

4. Set the property

In the same file, /android/src/main/java/com/pdftron/pdftronflutter/helpers/PluginUtils.java, add the code to set the property:

Java

1public static ConfigInfo handleOpenDocument(@NonNull ViewerConfig.Builder builder, @NonNull ToolManagerBuilder toolManagerBuilder,
2 @NonNull PDFViewCtrlConfig pdfViewCtrlConfig, @NonNull String document, @NonNull Context context,
3 String configStr) {
4 ...
5 if (configStr != null && !configStr.equals("null")) {
6 try {
7 if (!configJson.isNull(KEY_CONFIG_READ_ONLY)) {
8 boolean readOnly = configJson.getBoolean(KEY_CONFIG_READ_ONLY);
9 builder.documentEditingEnabled(!readOnly);
10 }
11 }
12 }
13 }

## Adding the `getPageCropBox` function

2. Define the new function in Dart

The constants.dart file contains constants grouped by their purpose. The names of functions, parameters, buttons, toolbars, and other relevant constants are stored here. Add a constant to the Functions class:

Dart

1class Functions {
2 static const getPageCropBox = "getPageCropBox";
3}

The document_view.dart file handles function calls for the widget, while pdftron_flutter.dart handles function calls for the plugin. If you want to implement for both the widget and plugin then add functions to both files, otherwise add your function to whichever you prefer.

Note that since we use JSON to transfer the information between Flutter and the native code, one extra step of decoding is required here.

In document_view.dart, add the getPageCropBox method to the DocumentViewController class:

Dart

1Future<PTRect> getPageCropBox(int pageNumber) {
2 return _channel.invokeMethod(Functions.getPageCropBox, <String, dynamic>{'pageNumber': pageNumber}).then((value) => jsonDecode(value));
3}

In pdftron_flutter.dart, add the getPageCropBox method to the PdftronFlutter class:

Dart

1static Future<PTRect> getPageCropBox(int pageNumber) {
2 return _channel.invokeMethod(Functions.getPageCropBox, <String, dynamic>{'pageNumber': pageNumber}).then((value) => jsonDecode(value));
3}

The options.dart file contains constants and classes for convenience. In this exercise, we add a new class called PTRect to this file for easier access of information.

Dart

1class PTRect {
2 double x1, y1, x2, y2, width, height;
3 PTRect(this.x1, this.y1, this.x2, this.y2, this.width, this.height);
4
5 factory PTRect.fromJson(dynamic json) {
6 return PTRect(getDouble(json['x1']), getDouble(json['y1']), getDouble(json['x2']), getDouble(json['y2']), getDouble(json['width']), getDouble(json['height']));
7 }
8
9 // a helper for JSON number decoding
10 static getDouble(dynamic value) {
11 if (value is int) {
12 return value.toDouble();
13 } else {
14 return value;
15 }
16 }
17}

3. Receive the new function from method channel

First, define the function and argument constants in /android/src/main/java/com/pdftron/pdftronflutter/helpers/PluginUtils.java, (constants are grouped according to purpose):

Java

1public static final String KEY_PAGE_NUMBER = "pageNumber";
2...
3public static final String FUNCTION_GET_PAGE_CROP_BOX = "getPageCropBox";

Then, you have 3 options:

Option 1

You would like the new function implemented for the plugin version.

Open the /android/src/main/java/com/pdftron/pdftronflutter/PdftronFlutterPlugin.java file and add a new case for the new function to onMethodCall:

Java

1@Override
2public void onMethodCall(MethodCall call, Result result) {
3 switch (call.method) {
4 case FUNCTION_GET_PAGE_CROP_BOX: {
5 FlutterDocumentActivity flutterDocumentActivity = FlutterDocumentActivity.getCurrentActivity();
6 Objects.requireNonNull(flutterDocumentActivity);
7 Objects.requireNonNull(flutterDocumentActivity.getPdfDoc());
8 Integer pageNumber = call.argument(KEY_PAGE_NUMBER);
9 if (pageNumber != null) {
10 try {
11 flutterDocumentActivity.getPageCropBox(pageNumber, result);
12 } catch (JSONException ex) {
13 ex.printStackTrace();
14 result.error(Integer.toString(ex.hashCode()), "JSONException Error: " + ex, null);
15 } catch (PDFNetException ex) {
16 ex.printStackTrace();
17 result.error(Long.toString(ex.getErrorCode()), "PDFTronException Error: " + ex, null);
18 }
19 }
20 break;
21 }
22 }
23}

Option 2

You would like the new function implemented for the widget version.

Open the /android/src/main/java/com/pdftron/pdftronflutter/FlutterDocumentView.java file and add a new case for the new function to onMethodCall:

Java

1@Override
2public void onMethodCall(MethodCall call, MethodChannel.Result result) {
3 switch (call.method) {
4 case FUNCTION_GET_PAGE_CROP_BOX: {
5 Objects.requireNonNull(documentView);
6 Objects.requireNonNull(documentView.getPdfDoc());
7 Integer pageNumber = call.argument(KEY_PAGE_NUMBER);
8 if (pageNumber != null) {
9 try {
10 documentView.getPageCropBox(pageNumber, result);
11 } catch (JSONException ex) {
12 ex.printStackTrace();
13 result.error(Integer.toString(ex.hashCode()), "JSONException Error: " + ex, null);
14 } catch (PDFNetException ex) {
15 ex.printStackTrace();
16 result.error(Long.toString(ex.getErrorCode()), "PDFTronException Error: " + ex, null);
17 }
18 }
19 break;
20 }
21 }
22}

Option 3

You would like the new function implemented for both versions. Note that this option is only for convenience and easier maintenance; you could always just use Options 1 and/or 2.

Open the /android/src/main/java/com/pdftron/pdftronflutter/helpers/PluginUtils.java file and add a new case for the new function to onMethodCall:

Java

1public static void onMethodCall(MethodCall call, MethodChannel.Result result, ViewActivityComponent component) {
2 switch (call.method) {
3 case FUNCTION_GET_PAGE_CROP_BOX: {
4 checkFunctionPrecondition(component);
5 Integer pageNumber = call.argument(KEY_PAGE_NUMBER);
6 if (pageNumber != null) {
7 try {
8 getPageCropBox(pageNumber, result, component);
9 } catch (JSONException ex) {
10 ex.printStackTrace();
11 result.error(Integer.toString(ex.hashCode()), "JSONException Error: " + ex, null);
12 } catch (PDFNetException ex) {
13 ex.printStackTrace();
14 result.error(Long.toString(ex.getErrorCode()), "PDFTronException Error: " + ex, null);
15 }
16 }
17 break;
18 }
19 }
20}

4. Implement the new function

Following step 3, 3 options will be listed below.

Option 1

You would like the new function implemented for the plugin version.

Open the /android/src/main/java/com/pdftron/pdftronflutter/FlutterDocumentActivity.java file and implement the new function:

Java

1public void getPageCropBox(int pageNumber, Result result) throws PDFNetException, JSONException {
2 JSONObject jsonObject = new JSONObject();
3 PDFDoc pdfDoc = getPdfDoc();
4 if (pdfDoc == null) {
5 result.error("InvalidState", "Activity not attached", null);
6 return;
7 }
8
9 Rect rect = pdfDoc.getPage(pageNumber).getCropBox();
10 jsonObject.put(KEY_X1, rect.getX1());
11 jsonObject.put(KEY_Y1, rect.getY1());
12 jsonObject.put(KEY_X2, rect.getX2());
13 jsonObject.put(KEY_Y2, rect.getY2());
14 jsonObject.put(KEY_WIDTH, rect.getWidth());
15 jsonObject.put(KEY_HEIGHT, rect.getHeight());
16 result.success(jsonObject.toString());
17}

Option 2

You would like the new function implemented for the widget version.

Open the /android/src/main/java/com/pdftron/pdftronflutter/views/DocumentView.java file and implement the new function:

Java

1public void getPageCropBox(int pageNumber, MethodChannel.Result result) throws PDFNetException, JSONException {
2 JSONObject jsonObject = new JSONObject();
3 PDFDoc pdfDoc = getPdfDoc();
4 if (pdfDoc == null) {
5 result.error("InvalidState", "Activity not attached", null);
6 return;
7 }
8
9 Rect rect = pdfDoc.getPage(pageNumber).getCropBox();
10 jsonObject.put(KEY_X1, rect.getX1());
11 jsonObject.put(KEY_Y1, rect.getY1());
12 jsonObject.put(KEY_X2, rect.getX2());
13 jsonObject.put(KEY_Y2, rect.getY2());
14 jsonObject.put(KEY_WIDTH, rect.getWidth());
15 jsonObject.put(KEY_HEIGHT, rect.getHeight());
16 result.success(jsonObject.toString());
17}

Option 3

You would like the new function implemented for both versions.

In the same file /android/src/main/java/com/pdftron/pdftronflutter/helpers/PluginUtils.java, implement the new function:

Java

1private static void getPageCropBox(int pageNumber, MethodChannel.Result result, ViewActivityComponent component) throws PDFNetException, JSONException {
2 JSONObject jsonObject = new JSONObject();
3 PDFDoc pdfDoc = component.getPdfDoc();
4 if (pdfDoc == null) {
5 result.error("InvalidState", "Activity not attached", null);
6 return;
7 }
8
9 Rect rect = pdfDoc.getPage(pageNumber).getCropBox();
10 jsonObject.put(KEY_X1, rect.getX1());
11 jsonObject.put(KEY_Y1, rect.getY1());
12 jsonObject.put(KEY_X2, rect.getX2());
13 jsonObject.put(KEY_Y2, rect.getY2());
14 jsonObject.put(KEY_WIDTH, rect.getWidth());
15 jsonObject.put(KEY_HEIGHT, rect.getHeight());
16 result.success(jsonObject.toString());
17}

The logic is to first get the current doc, get the crop box and encode all the associated information into a JSON string as the result.

The actual implementation will depend on the actual functionality.

Adding startZoomChangedListener

2. Define the new listener in Dart

The events.dart file is where all event listeners are defined and implemented. In this file do the following:

  • add a constant to represent the event channel.
  • declare a type alias for the listener.
  • add an id to the enum eventSinkId.
  • add a method that sets up a stream for our event.

Dart

1const _zoomChangedChannel = const EventChannel('zoom_changed_event');
2
3typedef void ZoomChangedListener(dynamic zoom);
4
5enum eventSinkId {
6 zoomChangedId,
7}
8
9CancelListener startZoomChangedListener(ZoomChangedListener listener) {
10 var subscription = _zoomChangedChannel
11 .receiveBroadcastStream(eventSinkId.zoomChangedId.index)
12 .listen(listener, cancelOnError: true);
13
14 return () {
15 subscription.cancel();
16 };
17}

3. Define event emitter

The ViewerComponent interface contains various methods that can be overridden by subclasses. In /android/src/main/java/com/pdftron/pdftronflutter/helpers/ViewerComponent.java, add a getter for an event emitter:

Java

1EventChannel.EventSink getZoomChangedEventEmitter();

The FlutterDocumentActivity class extends ViewerComponent and is used for the plugin version of our APIs. Do the following steps in /android/src/main/java/com/pdftron/pdftronflutter/FlutterDocumentActivity.java:

  • define the event emitter,
  • add a setter,
  • override the getter, and
  • destroy the event emitter when it is no longer necessary.

Java

1private static AtomicReference<EventSink> sZoomChangedEventEmitter = new AtomicReference<>();
2
3public static void setZoomChangedEventEmitter(EventSink emitter) {
4 sZoomChangedEventEmitter.set(emitter);
5}
6
7@Override
8public EventSink getZoomChangedEventEmitter() {
9 return sZoomChangedEventEmitter.get();
10}
11
12@Override
13protected void onDestroy() {
14 PluginUtils.handleOnDetach(this);
15
16 super.onDestroy();
17
18 ...
19 sZoomChangedEventEmitter.set(null);
20
21 detachActivity();
22}

The DocumentView class extends ViewerComponent and is used for the widget version of our APIs. Do the following steps in /android/src/main/java/com/pdftron/pdftronflutter/views/DocumentView.java:

  • define the event emitter,
  • add a setter, and
  • override the getter.

Java

1private EventChannel.EventSink sZoomChangedEventEmitter;
2
3public void setZoomChangedEventEmitter(EventChannel.EventSink emitter) {
4 sZoomChangedEventEmitter = emitter;
5}
6
7@Override
8public EventChannel.EventSink getZoomChangedEventEmitter() {
9 return sZoomChangedEventEmitter;
10}

4. Add event constant

In /android/src/main/java/com/pdftron/pdftronflutter/helpers/PluginUtils.java, add a constant for the event.

Java

1public static final String EVENT_ZOOM_CHANGED = "zoom_changed_event";

5. Set up event channel

For the plugin version, set up the event channel and stream handler in /android/src/main/java/com/pdftron/pdftronflutter/PdftronFlutterPlugin.java. In the stream handler, set our event emitter when an event stream is created, and remove it when an event stream is torn down.

Java

1import static com.pdftron.pdftronflutter.helpers.PluginUtils.EVENT_ZOOM_CHANGED;
2...
3public static void registerWith(Registrar registrar) {
4 final MethodChannel methodChannel = new MethodChannel(registrar.messenger(), "pdftron_flutter");
5 methodChannel.setMethodCallHandler(new PdftronFlutterPlugin(registrar.activeContext()));
6 ...
7 final EventChannel zoomChangedEventChannel = new EventChannel(registrar.messenger(), EVENT_ZOOM_CHANGED);
8 zoomChangedEventChannel.setStreamHandler(new EventChannel.StreamHandler() {
9 @Override
10 public void onListen(Object arguments, EventChannel.EventSink emitter) {
11 FlutterDocumentActivity.setZoomChangedEventEmitter(emitter);
12 }
13
14 @Override
15 public void onCancel(Object arguments) {
16 FlutterDocumentActivity.setZoomChangedEventEmitter(null);
17 }
18 });
19
20 registrar.platformViewRegistry().registerViewFactory("pdftron_flutter/documentview", new DocumentViewFactory(registrar.messenger(), registrar.activeContext()));
21}

For the widget version, set up the event channel and stream handler in /android/src/main/java/com/pdftron/pdftronflutter/FlutterDocumentView.java. In the stream handler, set our event emitter when an event stream is created, and remove it when an event stream is torn down.

Java

1import static com.pdftron.pdftronflutter.helpers.PluginUtils.EVENT_ZOOM_CHANGED;
2...
3public void registerWith(BinaryMessenger messenger) {
4 ...
5 final EventChannel zoomChangedEventChannel = new EventChannel(messenger, EVENT_ZOOM_CHANGED);
6 zoomChangedEventChannel.setStreamHandler(new EventChannel.StreamHandler() {
7 @Override
8 public void onListen(Object arguments, EventChannel.EventSink emitter) {
9 documentView.setZoomChangedEventEmitter(emitter);
10 }
11
12 @Override
13 public void onCancel(Object arguments) {
14 documentView.setZoomChangedEventEmitter(null);
15 }
16 });
17}

6. Send event to Flutter

In /android/src/main/java/com/pdftron/pdftronflutter/helpers/ViewerImpl.java, set up an event listener that sends the event to Flutter. Note that the necessary listener may already exist.

Java

1private PDFViewCtrl.OnCanvasSizeChangeListener mOnCanvasSizeChangedListener = new PDFViewCtrl.OnCanvasSizeChangeListener() {
2 @Override
3 public void onCanvasSizeChanged() {
4 EventChannel.EventSink eventSink = mViewerComponent.getZoomChangedEventEmitter();
5 if (eventSink != null && mViewerComponent.getPdfViewCtrl() != null) {
6 eventSink.success(mViewerComponent.getPdfViewCtrl().getZoom());
7 }
8 }
9};

The actual implementation will depend on the actual functionality.

Finishing steps

1. Push the code and integrate the updated source

Now update your library with the new code.

The new functionality is now ready to use.

2. Access the new functionality

The app can now access the new APIs as follows:

Plugin version:

Dart

1var config = Config();
2config.readOnly = true;
3
4await PdftronFlutter.openDocument("https://pdftron.s3.amazonaws.com/downloads/pl/PDFTRON_mobile_about.pdf", config: config);
5
6var cropBox = await PdftronFlutter.getPageCropBox(1);
7print('The width of crop box for page 1 is: ' + cropBox.width.toString());
8
9var zoomChangedCancel = startZoomChangedListener((zoom) {
10 print("flutter zoom changed. Current zoom is: $zoom");
11});
12
13zoomChangedCancel(); // Cancels the listener

Or:

Widget version:

Dart

1var config = Config();
2config.readOnly = true;
3
4await controller.openDocument("https://pdftron.s3.amazonaws.com/downloads/pl/PDFTRON_mobile_about.pdf", config: config);
5
6var cropBox = await controller.getPageCropBox(1);
7print('The width of crop box for page 1 is: ' + cropBox.width.toString());
8
9var zoomChangedCancel = startZoomChangedListener((zoom) {
10 print("flutter zoom changed. Current zoom is: $zoom");
11});
12
13zoomChangedCancel(); // Cancels the listener

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