Cordova tutorial – How to integrate our scanning functionalities

app store

Getting started

We will use the Ionic framework with Cordova for this tutorial. Ionic is an open-source mobile toolkit for building high-quality, cross-platform mobile apps and web apps.

Requirements

For Android apps

For iOS apps

  • macOS with the latest version of Xcode

Install Cordova and Ionic CLI tools

$ npm install -g cordova cordova-res native-run
$ npm install -g @ionic/cli

Create a “Hello World” Cordova app with Ionic support

$ ionic start my_awesome_cordova_ionic_app blank --cordova --type=ionic-angular --package-id="com.example.hello"

This command will create a blank Cordova app with Ionic support. 

The prompt might show you a recommendation to use Capacitor instead of Cordova. Capacitor is the successor of Cordova. For more details, please see our Capacitor blog post. For this tutorial, we will stick with Cordova.

Please also note the parameter “com.example.hello”, which is an app identifier (called Application ID on Android and Bundle Identifier on iOS). We will get back to this later.

Next, let’s add iOS and Android as platforms to our app:

$ cd my_awesome_cordova_ionic_app/
$ ionic cordova platform add ios
$ ionic cordova platform add android
$ cordova prepare

Enable AndroidX

By default, Cordova does not enable AndroidX in a new project. AndroidX libraries – also called Android Jetpack libraries – replace the old Android Support Library. They are required by most modern plugins, including the Scanbot SDK plugin. To enable AndroidX, we have to add the following preference entry in the config.xml file of our project:

<platform name="android">
  <preference name="AndroidXEnabled" value="true" />
  ...
</platform>

Furthermore, we need to install the plugin cordova-plugin-androidx-adapter:

$ ionic cordova plugin add cordova-plugin-androidx-adapter

Test run

Let’s connect a mobile device via USB and run the app.

Android

$ ionic cordova run android

iOS

$ ionic cordova prepare ios

Open the Xcode workspace platforms/ios/my_awesome_cordova_ionic_app.xcworkspace
and adjust the Signing & Capabilities settings in the Xcode IDE by selecting your Apple developer account. Then build and run the app in Xcode.

On both Android and iOS, you should now see the same blank app.

Add the Scanbot SDK plugin

Now let’s add the Scanbot SDK Cordova Plugin to our project. The plugin is available as the NPM package cordova-plugin-scanbot-sdk. Use the following command to install it:

$ ionic cordova plugin add cordova-plugin-scanbot-sdk

Android settings

Tuning the AndroidManifest.xml

Since our application will work with high-resolution images, it’s best to add the attribute android:largeHeap="true" in the <application> element of the Android manifest file. In a Cordova project, this manifest file is located at platforms/android/app/src/main/AndroidManifest.xml:

<application android:largeHeap="true" ...>
  ...
</application>

Furthermore, we need to declare that our app works with the camera and requires the corresponding permission. Make sure the request for camera permission has been properly added by the Scanbot Cordova plugin.

<manifest ...>
<uses-permission android:name="android.permission.CAMERA" />
</manifest>

iOS Settings

Add the required NSCameraUsageDescription property in Xcode in the “Info” settings tab of the project (which corresponds to the Info.plist file):

NSCameraUsageDescription "Privacy - Camera Usage Description"

As the value, enter a brief description of why your app needs access to the camera, e.g. “Camera access is required to scan documents”.

It’s coding time

Now, let’s write some JavaScript and HTML code! We are going to adjust the src/app/app.component.ts file, which is the entry point of our Cordova app.

Import the Scanbot SDK

import ScanbotSdk, {
    ScanbotSDKConfiguration
} from 'cordova-plugin-scanbot-sdk';

Initialize the Scanbot SDK

The Scanbot SDK for Cordova must be initialized before usage. Make sure to call the initialization after the Cordova event deviceready has fired. 

export class MyApp {
  ...
  private SDK = ScanbotSdk.promisify();
  
  constructor(platform: Platform, ...) {
    platform.ready().then(() => {
      ...
      this.initScanbotSdk();
    });
  }
 
  async initScanbotSdk(){
    const config: ScanbotSDKConfiguration = {
      loggingEnabled: true,
      licenseKey: '', // see the license key notes below!
    };
    try {
      const result = await this.SDK.initializeSdk(config);
      console.log(result);
    } catch (e) {
      console.error(e);
    }
  }
  ...
}

For the full API reference of the Cordova Scanbot SDK, please check out the documentation.

Integrate the document scanner UI

The Scanbot Scanner SDK for Cordova provides a scanner UI for document scanning. The Document Scanner is a complete and ready-to-use screen component. It can be easily integrated with just a few lines of code using the API method SDK.UI.startDocumentScanner({uiConfigs: configs}).

Let’s put the SDK call in a simple function named scanDocument() so that we can bind it to a clickable UI item. Add the following code in src/app/pages/home/home.ts>:


import { DomSanitizer } from '@angular/platform-browser';
import ScanbotSdk, {
  DocumentScannerConfiguration
} from 'cordova-plugin-scanbot-sdk';
 
export class HomePage {
  private SDK = ScanbotSdk.promisify();
  public imageFileUri: String = '';
 
  constructor(public sanitizer: DomSanitizer) {
  }
 
  async scanDocument(){
    const configs: DocumentScannerConfiguration = {
      orientationLockMode: 'PORTRAIT',
      multiPageEnabled: false,
      ignoreBadAspectRatio: true,
    };
    const result = await this.SDK.UI.startDocumentScanner({uiConfigs: configs});
    if (result.status === 'OK') {
      this.imageFileUri = this.sanitizeFileUri(result.pages[0].documentPreviewImageFileUri);
    }
  }
 
  sanitizeFileUri(fileUri: string): string {
    // see https://ionicframework.com/docs/building/webview/#file-protocol
    const convertedUri = (window as any).Ionic.WebView.convertFileSrc(fileUri);
    // see https://angular.io/guide/security#bypass-security-apis
    return this.sanitizer.bypassSecurityTrustUrl(convertedUri) as string;
  }
  ...
}

Now add a clickable UI item <ion-item> in src/app/pages/home/home.html and bind our scanDocument() method to a click event:

<ion-content padding>
  <ion-item (click)="scanDocument()">
    <ion-label>Scan Document</ion-label>
  </ion-item>
</ion-content>

The resulting images are returned as an array of Page elements.

For simplicity, in this example, we have disabled the multipage feature of the Document Scanner via the config parameter multiPageEnabled: false. This means that the Scanner UI will automatically close after a single scan, and we can use the first Page element from the array –  result.pages[0] – to display its cropped document image.

With the DocumentScannerConfiguration, you can pass further config parameters to customize colors, text resources, and the behavior of some features of the Document Scanner. See the API docs for more details.

The function sanitizeFileUri(fileUri) allows us to  display an image file by converting its file URI (file://) into a URL compatible with Ionic WebView.

Display the scanned image

Finally, let’s show a preview image, which we can do using the JPG file URI of a Page object. For that, we will use an image UI element <img> with imageFileUri as the image source.

Add the <img> element in src/app/pages/home/home.html:

<ion-content padding>
  ...
  <img [src]='imageFileUri' />
</ion-content>

That’s it! Now run the complete project. The app should be able to scan a document and display a preview image:

Android

$ ionic cordova run android

iOS

$ ionic cordova prepare ios

then, run the app in Xcode.

Complete example projects

To get off to a flying start, check out the following example projects on GitHub:

  • Small example project for this tutorial: https://github.com/doo/my_awesome_cordova_ionic_app 
  • Full example project: https://github.com/doo/scanbot-sdk-example-ionic
    It demonstrates the integration of all API methods of the Scanbot SDK Cordova Plugin, such as Cropping UI, Image Filtering, PDF and TIFF Rendering, Optical Character Recognition, Barcode Reader, QR Code Scanning, MRZ Scanner (Machine Readable Zones), EHIC Scanning (European Health Insurance Card), and License Plate Scanning.

Scanbot SDK (trial) license key

Please note: The Scanbot SDK will run without a license key for one minute per session! After the trial period has expired, all Scanbot SDK functions, as well as the UI components, will stop working or may be terminated. 

You can get an unrestricted, no-strings-attached 7-day trial license for free.

As the Scanbot SDK license key is bound to an app identifier (i.e., Application ID on Android and Bundle Identifier on iOS), you will have to use the app identifier com.example.hello that we defined at the beginning of the tutorial when creating the app. Of course, you can also use the ID of your app to get a trial license. Please also note that app IDs are case-sensitive!

Where to find the app identifier:

  • For Android see applicationId in the platforms/android/app/build.gradle file.
  • For iOS see Bundle Identifier in the General settings tab in the Xcode IDE.

💡 Did you have trouble with this tutorial?

We offer free integration support for the implementation and testing of the Scanbot SDK. If you encounter technical issues or need advice on choosing the appropriate framework or features, join our Slack or MS Teams or send us an email to receive your free support.

Developers, ready to get started?

Adding our free trial to your app is easy. Download the Scanbot SDK now and discover the power of mobile data capture