Getting Started

If you rather like to jump into some code than to walk through a Quick Start Guide, a good starting point for development with the Anyline SDK on Cordova, is to download the Cordova GitHub Repository.

The bundle includes:

  • anylinesdk-plugin: The plugin that you can add to your project
  • example: A simple Cordova example project, demonstrating how the Anyline SDK Cordova-Plugin can be used
  • PLUGIN_USAGE: A quick start guide

Requirements

In order to be able to use the Anyline SDK Cordova Plugin, the following requirements have to be met:

Android

  • An Android device with Android SDK Level >= 21
  • An Android device with decent camera functionality (recommended: 720p and adequate auto focus)

iOS

  • minimum iOS 12.0
  • minimum iPhone 5s

Cordova Quick Start Guide

In this guide, we will show you how to integrate the Anyline Cordova Plugin into your existing Cordova project.

For more information about Cordova itself, how to use plugins, etc., please refer to The Apache Cordova Website.

Warning

Keep in mind, all the images are saved in the cache directory of the app. For performance reasons, we only provide the path as string, so we don’t have to transfer the whole image through the bridge. Please be aware, that you should not use the images in the cache directory for persistent storage, but store the images in a location of your choice for persistence.

Add the Anyline SDK Plugin to your Project

You can add the Anyline SDK Plugin to your project by either installing it locally from the anylinesdk-plugin folder in the Cordova GitHub Repository, or add it via npm.

Add the plugin locally
cordova plugin add PATH_TO_DIR/anylinesdk-plugin/
Add the plugin via npm
cordova plugin add io-anyline-cordova

If you’d like to clone the repository you will have to use git-lfs. Use the following commands to install git-lfs.

download git LFS
brew install git-lfs
git lfs install

If you prefer downloading a package, use the provided zip package on the releases page. Be aware that the github download zip button does not work for projects with git-lfs.

iOS

if you get this error:

Error: CocoaPods was not found. Please install version 1.0.1 or greater from https://cocoapods.org/

please install Cocoapods

Generate an Anyline License

In order to run the Anyline SDK in your app, you require a License Key. The Guide on How To Generate a License can be found at Anyline License Key Generation

This section focuses on how to integrate the license on Cordova.

How to identify the Application ID

The Application ID on Cordova can be found in the config.xml file in the widgets id parameter.

Cordova Application ID
...
<widget id="io.anyline.examples.cordova" version="3.8.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
...

Different App IDs for Android and iOS

In case you have different Application IDs for Android and iOS, please use android-packageName and ios-CFBundleIdentifier parameters of the widget

Create your Javascript file

You can now start to create your Javascript files. Or you can build your Cordova application based on the examples provided in the Cordova GitHub Repository. The examples are located under examples/www/js.

The following setup is just a recommendation. You can, of course, implement the Plugin the way you prefer.

Create an anyline object

You can create an object, holding all your callbacks and configuration files.

All the following functions and fields can be simply added to your object.

The anyline object
if (anyline === undefined) {
    var anyline = {};
  }
  anyline.ocr = {
      cordova.exec(this.onResult, this.onError, "AnylineSDK", "scan", [this.licenseKey, this.ibanViewConfig]);

Add the callback functions

The Anyline SDK Cordova Plugin provides requires two callback functions: onResult and onError.

onResult(result)

This function is called once the scan was successfully performed.

The returned result object is a json-object containing all the scaned values and check-digits.

The onResult callback
    onResult: function (result) {
      localStorage.setItem("hasStartedAnyline", false);
      //this is called for every mrz scan result
      //the result is a json-object containing all the scaned values and check-digits
  
      console.log("Result: " + JSON.stringify(result));
      var div = document.getElementById('results');
  
      if(div.childElementCount >= 3) {
        div.removeChild(div.childNodes[div.childElementCount - 1]);
      }
  
      div.innerHTML = "<p>" + "<img src=\"" + result.imagePath + "\" width=\"100%\" height=\"auto\"/><br/>" +
          "<b>Result: </b> " + result.text
          + "<br/><i><b>Confidence:</b> " + result.confidence + "</i>"
          + "<br/><i><b>Outline Points:</b> " + result.outline + "</i>" + "</p>"
          + div.innerHTML;
  
      document.getElementById("details_scan_modes").removeAttribute("open");
      document.getElementById("details_results").setAttribute("open", "");
      window.scrollTo(0, 0);
    },
onError(error)

This function is called if an error occurred or the user canceled the scanning.

The returned error object is a String, providing the error message.

The onError callback
    onError: function (error) {
      localStorage.setItem("hasStartedAnyline", false);
      //called if an error occurred or the user canceled the scanning
      if (error == "Canceled") {
        //do stuff when user has canceled
        // this can be used as an indicator that the user finished the scanning if canclelOnResult is false
        console.log("AnylineOcr scanning canceled");
        return;
      }
  
      alert(error);
    },

Add the License Key

You need a license key, in order to run the scanning process in your app. You can learn about creating a license key in Anyline License Key Generation.

Add the license key to your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ExQanBkbkpmQXdqUT09Cg==K",

Add the View Configuration

The View Configuration defines the look & feel of your scanning application. More information about the View Configuration can be found in Anyline View Configuration.

Add the View Configuration
    anylineVoucherCodesViewConfig: {
      "camera": {
        "captureResolution": "1080"
      },
      "flash": {
        "mode": "manual",
        "alignment": "bottom_right"
      },
      "viewPlugin": {
        "plugin" : {
          "id" : "OCR_VC",
          "ocrPlugin" : {
            "scanMode" : "AUTO",
            "languages" : ["www/assets/anyline_capitals.traineddata"],
            "charWhitelist": "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            "validationRegex": "[A-Z0-9]{8}$",
            "minConfidence": 85,
            "reportingEnabled" : true
          }
        },
        "cutoutConfig": {
          "style": "rect",
          "maxWidthPercent": "80%",
          "maxHeightPercent": "80%",
          "alignment": "center",
          "width": 540,
          "ratioFromSize": {
            "width": 5,
            "height": 1
          },
          "strokeWidth": 2,
          "cornerRadius": 10,
          "strokeColor": "FFFFFF",
          "outerColor": "000000",
          "outerAlpha": 0.3,
          "feedbackStrokeColor": "0099FF"
        },
        "scanFeedback": {
          "style": "contour_point",
          "strokeWidth": 3,
          "strokeColor": "0099FF",
          "fillColor": "220099FF",
          "beepOnResult": true,
          "vibrateOnResult": true,
          "blinkAnimationOnResult": true
        },
        "doneButton": { // iOS only. Android uses hardware back button.
          "title": "OK",
          "type": "rect", // fullwidth, rect
Additional Parameters in the View Configuration

Cordova adds some additional parameters to the View configuration.

nativeBarcodeEnabled

You can enable the Simultaneous Barcode scanning while scanning meter reader.

quality

Here you can set the quality of the saved transformed and full image. The range is 0 - 100, where 0 is the lowest quality and 100 the best.

quality

Only for the Document product

cropAndTransformErrorMessage

If set cropAndTransformErrorMessage as custom error message, a notification will appear in the screen containing this error message when the SDK gets the result, but can’t detect the corners. This requires “cropAndTransformID” is set to true. Default String is empty (so no notification will be shown).

cropAndTransformErrorMessage

Only for the MRZ product

iOS Done Button Configuration

On iOS, a done button can be added to the view by providing additional parameters.

"doneButton": { // iOS only. Android uses hardware back button.
    "title": "OK",
    "type": "rect", // fullwidth, rect
    "cornerRadius": 0,
    //"backgroundColor":"#EEEEEE", // default clearcolor
    "textColor": "FFFFFF",
    "textColorHighlighted": "CCCCCC",
    "fontSize": 33,
    "fontName": "HelveticaNeue",
    "positionXAlignment": "center", // left,right,center - no affect on fullwidth
    "positionYAlignment": "bottom", // top, center, bottom
    "offset": {
        "x": 0, // postive -> right
        "y": -88, // postive -> down
    }
}
doneButton.title

The title of the button.

JSON-Type Example
String OK
doneButton.type

The type of the button. Can be one of rect or fullWidth.

JSON-Type Example
String rect
doneButton.cornerRadius

The corner radius of the button

JSON-Type Example
Integer 0
doneButton.backgroundColor

The buttons background color. Default is set to clearcolor

JSON-Type Example
String (RRGGBB) EEEEEE
doneButton.textColor

The buttons text color.

JSON-Type Example
String (RRGGBB) FFFFFF
doneButton.textColorHighlighted

The buttons text color when highlighted.

JSON-Type Example
String (RRGGBB) CCCCCC
doneButton.fontSize

The font size of the buttons text.

JSON-Type Example
Integer 33
doneButton.fontName

The font family name of the buttons text.

JSON-Type Example
String HelveticaNeue
doneButton.positionXAlignment

The X alignment of the button. One of left, center, or right.

fullwidth

This parameter has no effect if type is set to fullwidth.

JSON-Type Example
String center
doneButton.positionYAlignment

The Y alignment of the button. One of top, center, or bottom.

JSON-Type Example
String bottom
doneButton.offset.x

The X offset relative to the algignment. Positive values move the button to the right.

JSON-Type Example
Integer 10
doneButton.offset.y

The Y offset relative to the algignment. Positive values move the button downwards.

JSON-Type Example
Integer -80
Additional Parameters for the Anyline OCR plugin

The Anyline Cordova Plugin offers two additional parameters for the /toc/plugins/anyline_ocr/index:

languages

Any array of languages files that are used for the OCR step of the Anyline SDK.

Corresponds to the languages parameter of the Anyline OCR plugin.

Path

The file paths are relative to the www directory

aleFile

A String of your custom Anyline ALE file for the OCR step of the Anyline SDK. It is located in the config under myConfig.viewplugin

Path

The file paths are relative to the www directory

Start the Scanning

cordova.exec takes the following parameters:

  • onResult: The result callback function
  • onError: The error callback function
  • AnylineSDK: String that tells Cordova to start the Anyline SDK Plugin
  • scan: String to start the scanning
  • config: An array consisting of the license_key and the view_config

Create your index.html

In order to scan with your Cordova application, you need to call the Javscript function from your index.html file. You can do that on a button onclick attribute for example.

Of course, you can call cordova.exec() directly. We recommend wrapping the call in your Javscript file, as shown below. This way, your callbacks, parameters and the configuration are located in one place.

<input type="button" value="Anyline Voucher Codes" onclick="anyline.ocr.scanAnylineVoucherCodes()" />

Additional Functions

getLicenseExpiryDate

Check till when the provided License is or was valid. Returns a string.

Get License expiry date
    cordova.exec(console.log, console.log, "AnylineSDK", "CHECK_LICENSE", [licenseKey]); // YYYY-MM-DD

Full Example

/*
 * Anyline Cordova Plugin
 * anyline.ocr.js
 *
 * Copyright (c) 2018 Anyline GmbH
 */

if (anyline === undefined) {
    var anyline = {};
  }
  anyline.ocr = {
    onResult: function (result) {
      localStorage.setItem("hasStartedAnyline", false);
      //this is called for every mrz scan result
      //the result is a json-object containing all the scaned values and check-digits
  
      console.log("Result: " + JSON.stringify(result));
      var div = document.getElementById('results');
  
      if(div.childElementCount >= 3) {
        div.removeChild(div.childNodes[div.childElementCount - 1]);
      }
  
      div.innerHTML = "<p>" + "<img src=\"" + result.imagePath + "\" width=\"100%\" height=\"auto\"/><br/>" +
          "<b>Result: </b> " + result.text
          + "<br/><i><b>Confidence:</b> " + result.confidence + "</i>"
          + "<br/><i><b>Outline Points:</b> " + result.outline + "</i>" + "</p>"
          + div.innerHTML;
  
      document.getElementById("details_scan_modes").removeAttribute("open");
      document.getElementById("details_results").setAttribute("open", "");
      window.scrollTo(0, 0);
    },
  
    onError: function (error) {
      localStorage.setItem("hasStartedAnyline", false);
      //called if an error occurred or the user canceled the scanning
      if (error == "Canceled") {
        //do stuff when user has canceled
        // this can be used as an indicator that the user finished the scanning if canclelOnResult is false
        console.log("AnylineOcr scanning canceled");
        return;
      }
  
      alert(error);
    },
    anylineVoucherCodesViewConfig: {
      "camera": {
        "captureResolution": "1080"
      },
      "flash": {
        "mode": "manual",
        "alignment": "bottom_right"
      },
      "viewPlugin": {
        "plugin" : {
          "id" : "OCR_VC",
          "ocrPlugin" : {
            "scanMode" : "AUTO",
            "languages" : ["www/assets/anyline_capitals.traineddata"],
            "charWhitelist": "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            "validationRegex": "[A-Z0-9]{8}$",
            "minConfidence": 85,
            "reportingEnabled" : true
          }
        },
        "cutoutConfig": {
          "style": "rect",
          "maxWidthPercent": "80%",
          "maxHeightPercent": "80%",
          "alignment": "center",
          "width": 540,
          "ratioFromSize": {
            "width": 5,
            "height": 1
          },
          "strokeWidth": 2,
          "cornerRadius": 10,
          "strokeColor": "FFFFFF",
          "outerColor": "000000",
          "outerAlpha": 0.3,
          "feedbackStrokeColor": "0099FF"
        },
        "scanFeedback": {
          "style": "contour_point",
          "strokeWidth": 3,
          "strokeColor": "0099FF",
          "fillColor": "220099FF",
          "beepOnResult": true,
          "vibrateOnResult": true,
          "blinkAnimationOnResult": true
        },
        "doneButton": { // iOS only. Android uses hardware back button.
          "title": "OK",
          "type": "rect", // fullwidth, rect
          "cornerRadius": 0,
          "textColor": "FFFFFF",
          "textColorHighlighted": "CCCCCC",
          "fontSize": 33,
          "fontName": "HelveticaNeue",
          "positionXAlignment": "center", // left,right,center - no affect on fullwidth
          "positionYAlignment": "bottom", // top, center, bottom
          "offset": {
              "x": 0, // postive -> right
              "y": -88, // postive -> down
          }
        },
        "cancelOnResult": true
      }
    },
    scanAnylineVoucherCodes: function () {
      if (localStorage.getItem("hasStartedAnyline") === 'true') {
        return;
      }
      localStorage.setItem("hasStartedAnyline", true);
      // start the Anyline OCR scanning
      // pass the success and error callbacks, as well as the license key and the config to the plugin
      // see http://documentation.anyline.io/#anyline-config for config details
      // and http://documentation.anyline.io/#anylineOcrModule for module details
  
      cordova.exec(this.onResult, this.onError, "AnylineSDK", "scan", [this.licenseKey, this.anylineVoucherCodesViewConfig]);
    }
  };
  
<!DOCTYPE html>
<!--
 Anyline Cordova Plugin
 indext.html

 Copyright (c) 2018 Anyline GmbH
 -->
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1,
                    width=device-width, height=device-height">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <link rel="stylesheet" type="text/css" href="css/anyline.css">
    <title>Anyline Cordova Example</title>
    <script type="application/javascript">localStorage.setItem("hasStartedAnyline", false);</script>
</head>

<body>
    <h1>Anyline Cordova</h1>

    <div id="navigation">
        <details id="details_scan_modes" open>
                <p>
                    <input type="button" value="Anyline Voucher Codes" onclick="anyline.ocr.scanAnylineVoucherCodes()" />
                    <br />
                </p>
        </details>
        <details id="details_results">
            <summary class="summary1">
                Results
            </summary>
            <p>
                <div id="results">

                </div>
            </p>
        </details>
        <hr>
        <div id="versions">
            <div id="SDK">
            </div>
            <div>
                <p>Cordova Build Version: 1</p>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="js/anyline.ocr.js"></script>
</body>

</html>