Skip to main content

Features | React Native Document Scanner

Storage#

Since version 3.0 of this module the native Scanbot SDKs use the internal and secure storage locations for all produced files (JPG, PNG, PDF, TIFF, etc) by default.

  • On Android all files will be stored in the internal files directory of your application. No permissions are required for your app to read or write files in this directory.

  • On iOS all files will be stored in the Application Support folder of your application.

Customize Storage Location#

It is strongly recommended to use the default storage location. However, you can override the storage directory on initialization of the SDK Module. The initializeSdk method can take an optional parameter storageBaseDirectory to set a custom storage location.

const options = {  storageBaseDirectory: 'file:///some/custom/storage-dir/',  ...};
const result = await ScanbotSDK.initializeSDK(options);

The value of the storageBaseDirectory must be a file URL ('file:///...) pointing to a valid platform-specific file system path. If this directory does not exist yet, the SDK Module will try to create it. To work with the file system we recommend the npm module react-native-fs

For the full demo code please check out our example app scanbot-sdk-example-react-native.

⚠️ Note: When overriding the default storage location, make sure

  • you have implemented a suitable storage permissions request handling on Android
  • you fully understand the consequences regarding the accessibility (security) of the produced document files.

👉 For more details about the storage locations on Android and iOS please also see:

Storage Cleanup#

There is no automatic file clean mechanism in this SDK Module, because only your App can decide when the perfect time is to remove the files produced by this SDK (images, PDFs, etc).

To avoid storage space issues caused by too many produced image files, it is strongly recommended to implement a suitable cleanup functionality based on the requirements of your app. This SDK Module provides the following helper methods to keep the storage clean:

  • removePage method to delete a certain Page object with all its files.
  • cleanup method to remove all generated files by this RN SDK Module (scanned and imported images, export files like PDF, TIFF, etc).

Storage Encryption#

The Scanbot SDK provides the ability to store the generated image files (JPG, PNG) and PDF files encrypted. This feature provides an additional level of security to the default secure storage locations of the native SDKs.

By default the file encryption is disabled. To enable it you have to pass the following config parameters on SDK initialization:

  • fileEncryptionPassword: A secure password or passphrase to derive the AES key for encryption/decryption.
  • fileEncryptionMode: Encryption mode, AES128 or AES256 (default and recommended).
const options: InitializationOptions = {  fileEncryptionPassword: 'SomeSecretPa$$w0rdForFileEncryption',  fileEncryptionMode: 'AES256'};await ScanbotSDK.initializeSDK(options);

By activating the storage encryption the native Scanbot SDKs will use the builtin AES 128 or AES 256 encryption. All generated image files (JPG, PNG) including the preview image files, as well as the exported PDF files will be encrypted in memory and stored as encrypted data files on the flash storage of the device.

The Scanbot SDK derives the AES key from the given password, an internal salt value, and the internal number of iterations using the PBKDF2 function.

When applying image operations like cropping, rotation or image filters, the Scanbot SDK will decrypt the image file in memory, apply the changes, encrypt and store it again.

Handle Encrypted Images#

Display Encrypted Images

If the file encryption is enabled you will not be able to display preview images via file URIs (e.g. page.documentPreviewImageFileUri). Instead, you have to load the decrypted data of a preview image and use it for displaying an image. In order to do this use the API function getImageData(imageFileUri: string):

// use the low-res image "documentPreviewImageFileUri" for the preview:const result = await ScanbotSDK.getImageData(page.documentPreviewImageFileUri);const decryptedImageDataAsBase64 = `data:image/jpeg;base64,${result.base64ImageData}`;...<Image source={uri: decryptedImageDataAsBase64} style={...} />

👉 For a full implementation see our example app.

Upload Encrypted Images

To upload an image you have the following options:

1) Use the encrypted image file to upload to your server and decrypt it in the backend. Please contact our team to get support on how to generate the corresponding AES key and decrypt images on your backend.

2) Alternatively, get the decrypted image data as Base64 on the mobile device by using the getImageData(imageFileUri: string) function and use this data for the upload process:

// use the final hi-res image "documentImageFileUri" for the upload process:const result = await ScanbotSDK.getImageData(page.documentImageFileUri);const decryptedImageDataAsBase64 = result.base64ImageData;yourCustomUploadFunction(decryptedImageDataAsBase64);

Ready-To-Use UI#

Configuration#

Settings controlling color are expected to be passed as strings in the '#RRGGBB' format.

Pages#

The Scanbot SDK provides a ready-to-use UI for document scanning and cropping. Both components use the notion of a 'page' as a data model for the scanning and cropping activities. A Page object has the following fields:

interface Page {    pageId: string;    polygon: Point[];    detectionResult: DetectionStatus;    pageImageSource: PageImageSource;    filter: ImageFilter;    documentImageSizeLimit?: Size;    originalImageFileUri: string;    documentImageFileUri?: string;    originalPreviewImageFileUri: string;    documentPreviewImageFileUri?: string;}

The fields are:

  • pageId - a string identifying the page in the internal page file storage
  • polygon - the page's cropping polygon as calculated by a document detection operation or as set by the cropping UI. Modifying the polygon will change the polygon as shown in the cropping UI but will not automatically re-crop the original image
  • detectionResult - the detection result of the document detection operation that produced the page (either the document scanner or detectDocument())
  • pageImageSource - The PageImageSource (MANUAL_SNAP, AUTO_SNAP, CAMERA_FRAME) or UNKNOWN if the image has been imported or the source is unknown.
  • filter - The Image Filter that was applied on the page image
  • documentImageSizeLimit - The value that was set for documentImageSizeLimit, which limits the maximum size of the document image.
  • originalImageFileUri - file URI of the original image
  • documentImageFileUri - file URI of the cropped document image (if document detection was successful)
  • originalPreviewImageFileUri - file URI of a screen-sized preview of the original image
  • documentPreviewImageFileUri - file URI of a screen-sized preview of the document image

Pages are stored in an internal page file storage, where the pageId serves as a name prefix for the stored image files. Operations that modify pages work in-place. That is, for example, rotatePage() overwrites the page's image files with their rotated versions. This behavior differs from the behavior of raw image functions like rotateImage(), which always create a new file. All URI properties of a page have a ?minihash= query parameter appended to them with the hash of a portion of the image file. Different images will almost always have a different hash and therefore a different URI, which will force the WebView to reload the page's images when changed.

Persistence of Page Objects#

Scanbot SDK does not persist page objects, only the image files (.jpg or .png). The management of page objects and the persistence of the page metadata is left to the app. Depending on the use case, it may be necessary to persist the data of the page objects in the app (e.g. as JSON in a local SQLite database). If this is the case, the following must be considered.

The Page objects contain absolute paths to the image files:

{  "pageId": "60426F47-4119-48F8-ADA9-F7E60D583CB4",  "filter": "NONE",  "detectionResult": "OK",  "polygon": [{"x":0.17427248677248677,"y":0.1212797619047619},{"x":0.8604497354497355,"y":0.13120039682539678},{"x":0.8349867724867724,"y":0.9729662698412699},{"x":0.12202380952380967,"y":0.9471726190476191}],  "documentPreviewImageFileUri": "file:///var/mobile/Containers/Data/Application/54286F82-A8F7-4850-A684-8D3487726A4D/Library/Application%20Support/net.doo.ScanbotSDK/SBSDK_ImageStorage_Default/PageFileStorage/JPEG/documents/60426F47-4119-48F8-ADA9-F7E60D583CB4_preview.jpg?minihash=a236a8ba5510cd0f4e88bd2045f52c4e",  "originalImageFileUri": "file:///var/mobile/Containers/Data/Application/54286F82-A8F7-4850-A684-8D3487726A4D/Library/Application%20Support/net.doo.ScanbotSDK/SBSDK_ImageStorage_Default/PageFileStorage/JPEG/originals/60426F47-4119-48F8-ADA9-F7E60D583CB4.jpg?minihash=4e9f0446421343eaaa1e415fdb446a12",  "originalPreviewImageFileUri": "file:///var/mobile/Containers/Data/Application/54286F82-A8F7-4850-A684-8D3487726A4D/Library/Application%20Support/net.doo.ScanbotSDK/SBSDK_ImageStorage_Default/PageFileStorage/JPEG/originals/60426F47-4119-48F8-ADA9-F7E60D583CB4_preview.jpg?minihash=da888cd42db07e52b15a6ada29a37b63",  "documentImageFileUri": "file:///var/mobile/Containers/Data/Application/54286F82-A8F7-4850-A684-8D3487726A4D/Library/Application%20Support/net.doo.ScanbotSDK/SBSDK_ImageStorage_Default/PageFileStorage/JPEG/documents/60426F47-4119-48F8-ADA9-F7E60D583CB4.jpg?minihash=f9aab62cc37fec555abe94c83406a1b3"}

The page image files are stored in corresponding storage locations - also see the Storage section. By default, the Scanbot SDK Android uses the internal files directory of the app, whereas the Scanbot SDK iOS uses the "Application Support" folder. Those storage folders are secure and are not affected by an app update.

However, on iOS, the absolute file path of the "Application Support" folder is not reliable. For each fresh install of an app, a new UUID is generated, in the following format: /var/mobile/Containers/Data/Application/{UUID}. That is where application data is stored. When updating the app, the uuid may change. For example:

Before an app update:

file:///var/mobile/Containers/Data/Application/54286F82-A8F7-4850-A684-8D3487726A4D/Library/Application%20Support/net.doo.ScanbotSDK/SBSDK_ImageStorage_Default/PageFileStorage/JPEG/documents/60426F47-4119-48F8-ADA9-F7E60D583CB4.jpg

After the app update:

file:///var/mobile/Containers/Data/Application/C9181555-252A-4665-892F-793008ED0EDD/Library/Application%20Support/net.doo.ScanbotSDK/SBSDK_ImageStorage_Default/PageFileStorage/JPEG/documents/60426F47-4119-48F8-ADA9-F7E60D583CB4.jpg

Please note that the actual image files are still there, only the absolute file paths change.

To get to the new absolute paths, the API method refreshImageUris({pages: Page []}) has been introduced in the plugin version 4.4.0. Please use this method to refresh all image file URIs from affected pages:

const result = await ScanbotSDK.refreshImageUris({pages: loadedPages});const refreshedPages = result.pages;

It is highly recommended using this method whenever you have to (re-)load JSON Page objects from the database of your app, regardless of whether there was an app update or not.

Document Scanner#

ScanbotSdk.UI.startDocumentScanner(configuration: DocumentScannerConfiguration): Promise#

Starts the ready-to-use Document Scanner for guided, automatic document scanning.

alt text

Result#

The promise resolves to an object with the following properties:

  • status - 'OK' if some pages were snapped, 'CANCELED' if the user canceled the operation.
  • pages - an array of pages. If multi-page mode is enabled, this array may contain more than one page. If multi-page mode is not enabled and status is 'OK', this array contains one object.
Options:#

All configuration options are optional.

export interface DocumentScannerConfiguration{    /**    * The minimum score in percent (0 - 100) of the perspective distortion to accept a detected document.    * Default is 75.0.    */    acceptedAngleScore?: number;    /**    * The minimum document width or height in percent (0 - 100) of the screen size to accept a detected document.    * Default is 80.0.    */    acceptedSizeScore?: number;    /**    * Controls whether the auto-snapping toggle button is hidden or not.    */    autoSnappingButtonHidden?: boolean;    /**    * Title of the auto-snapping toggle button.    */    autoSnappingButtonTitle?: string;    /**    * When auto-snapping is enabled the document scanner will take a photo automatically    * when a document is detected, conditions are good and the auto-snapping time-out elapses. In this    * mode the user can still tap the shutter button to snap a document.    */    autoSnappingEnabled?: boolean;    /**    * Controls the auto-snapping speed. Sensitivity must be within the 0..1 range.    * A value of 1.0 triggers automatic capturing immediately, a value of 0.0 delays the automatic by 3 seconds.    * The default value is 0.66 (2 seconds)    */    autoSnappingSensitivity?: number;    /**    * The background color of the bottom shutter-bar.    */    bottomBarBackgroundColor?: string;    /**    * The color of the title of all buttons in the bottom shutter-bar (Cancel button, etc.),    * as well as the camera permission prompt button.    */    bottomBarButtonsColor?: string;    /**    * The color of the camera background (relevant only when the camera preview mode is CameraPreviewMode.FIT_IN).    */    cameraBackgroundColor?: string;    /**    * Preview mode of the camera: Fit-In or Fill-In.    * Optional, default is Fit-In.    */    cameraPreviewMode?: CameraPreviewMode;    /**    * Title of the cancel button.    */    cancelButtonTitle?: string;    /**    * Title of the button that opens the screen where the user can allow    * the usage of the camera by the app.    */    enableCameraButtonTitle?: string;    /**    * Text that will be displayed when the app    * is not allowed to use the camera, prompting the user    * to enable the usage of the camera.    */    enableCameraExplanationText?: string;    /**    * Controls whether the flash toggle button is hidden or not.    */    flashButtonHidden?: boolean;    /**    * Title of the flash toggle button.    */    flashButtonTitle?: string;    /**    * Controls whether the flash should be initially enabled.    * The default value is FALSE.    */    flashEnabled?: boolean;    /**    * Sets whether to ignore the OK_BUT_BAD_ASPECT_RATIO detection status.    * By default BadAspectRatio is not ignored.    */    ignoreBadAspectRatio?: boolean;    /**    * The image scaling factor. The factor must be within the 0..1 range.    * A factor of 1 means that the resulting images retain their original size.    * When the factor is less than 1, resulting images will be made smaller by that factor.    * By default the scale is 1.    */    imageScale?: number;    /**    * Controls whether the multi-page toggle button is hidden or not.    */    multiPageButtonHidden?: boolean;    /**    * Title of the multi-page mode toggle button.    */    multiPageButtonTitle?: string;    /**    * Controls multi-page mode. When enabled, the user can take multiple document photos before    * closing the screen by tapping the page counter button. When disabled, the screen will be    * closed immediately after the first document photo is made.    * The default value is FALSE.    */    multiPageEnabled?: boolean;    /**    * Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.    * By default the camera orientation is not locked.    */    orientationLockMode?: CameraOrientationMode;    /**    * Title suffix of the button that finishes the document scanning when multi-page scanning is enabled.    * The button's title has the format "# Pages", where # shows the number of images captured up to now and the    * suffix "Pages" is set using this method.    */    pageCounterButtonTitle?: string;    /**    * The background color of the detected document outline when the document's angle, size or aspect ratio    * is not yet sufficiently good.    * (All net.doo.snap.lib.detector.DetectionResult with OK_BUT_XXX).    */    polygonBackgroundColor?: string;    /**    * The background color of the detected document outline when we are ready to snap OK.    */    polygonBackgroundColorOK?: string;    /**    * The color of the detected document outline when the document's angle, size or aspect ratio    * is not yet sufficiently good.    * (All detection statuses in net.doo.snap.lib.detector.DetectionResult that have the OK_BUT_XXX prefix).    */    polygonColor?: string;    /**    * The color of the detected document outline when we are ready to snap OK.    */    polygonColorOK?: string;    /**    * Width of the detected document outline.    */    polygonLineWidth?: number;    /**     * The radius to use when drawing rounded corners of the polygon. Default is 8.0.     */    polygonCornerRadius?: number;    /**     * Stroke color of polygon auto snap progress animation. Default is green. Can't be null.     */    polygonAutoSnapProgressColor?: string;    /**     * Line width of polygon auto snap progress animation. Default is 5.0.     */    polygonAutoSnapProgressLineWidth?: number;    /**     * Whether polygon auto snap progress animation is enabled or no. Default is true.     */    polygonAutoSnapProgressEnabled?: boolean;    /**    * The foreground color of the shutter button in auto-snapping mode.    */    shutterButtonAutoInnerColor?: string;    /**    * The background color of the shutter button in auto-snapping mode.    */    shutterButtonAutoOuterColor?: string;    shutterButtonIndicatorColor?: string;    /**    * The foreground color of the shutter button in manual mode.    */    shutterButtonManualInnerColor?: string;    /**    * The background color of the shutter button in manual mode.    */    shutterButtonManualOuterColor?: string;    /**    * Text hint that will be shown when the current detection status is OK_BUT_BAD_ANGLES    */    textHintBadAngles?: string;    /**    * Text hint that will be shown when the current detection status is OK_BUT_BAD_ASPECT_RATIO    */    textHintBadAspectRatio?: string;    /**    * Text hint that will be shown when the current detection status is ERROR_NOTHING_DETECTED    */    textHintNothingDetected?: string;    /**    * Text hint that will be shown when the current detection status is OK    */    textHintOK?: string;    /**    * Text hint that will be shown when the current detection status is ERROR_TOO_DARK    */    textHintTooDark?: string;    /**    * Text hint that will be shown when the current detection status is ERROR_TOO_NOISY    */    textHintTooNoisy?: string;    /**    * Text hint that will be shown when the current detection status is OK_BUT_TOO_SMALL    */    textHintTooSmall?: string;    /**    * The background color of the top toolbar.    */    topBarBackgroundColor?: string;    /**    * The color of all active toggle buttons in the toolbar.    */    topBarButtonsActiveColor?: string;    /**    * The color of all inactive toggle buttons in the toolbar.    */    topBarButtonsInactiveColor?: string;    /**    * The background color of the user guidance hints.    */    userGuidanceBackgroundColor?: string;    /**    * The text color of the user guidance hints.    */    userGuidanceTextColor?: string;    /**     * Limits the maximum size of the document image. If width or height are zero,     * this property is effectively ignored.     * Where Size is     * {     * width: number;     * height: number;     * }     */    documentImageSizeLimit?: Size;    /**     * Hides the shutter button if set to TRUE. Shows it otherwise. Defaults to FALSE.     * If set to TRUE, auto-snapping is enabled and the property     * autoSnappingEnabled of the behaviour configuration will     * have no effect.     * Also, the auto-snapping button will be hidden.     */    shutterButtonHidden?: boolean;    /**     * The text being displayed on the user-guidance label, when the scanners energy saver is activated.     * iOS only.     */    textHintEnergySavingActive?: string;    /**     * Maximum number of pages to scan. Ignored when set to null, or when `multiPageEnabled` is FALSE.     * Default value is null.     */    maxNumberOfPages?: number;    /**     * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.     * Android only.     */    useButtonsAllCaps?: boolean;
    /**     * Allows you to customize the accessibility configuration for the Document Scanner UI    */    accessibilityConfiguration?: DocumentScannerAccessibilityConfiguration;}
export interface DocumentScannerAccessibilityConfiguration {    /**     * Text, that is used as an accessibility label for the flash button.     */    flashButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the flash button.     */    flashButtonAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the multi-page button.     */    multiPageButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the multi-page button.     */    multiPageButtonAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the auto-snapping button.     */    autoSnappingButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the auto-snapping button.     */    autoSnappingButtonAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the cancel button.     */    cancelButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the cancel button.     */    cancelButtonAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the page-amount button.     */    pageCounterButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the page-amount button.     */
    pageCounterAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the shutter button.     */    shutterButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the shutter button.     */    shutterButtonAccessibilityHint: string;  }

Cropping UI#

ScanbotSdk.UI.startCroppingScreen(page: Page, options: CroppingScreenConfiguration)#

The Cropping UI provides functionality for manual cropping and rotation of an image. It uses the edge detection algorithm of the Scanbot SDK and contains some smart UI elements like magnetic lines and a magnifier.

alt

Returns#

The promise resolves to an object with the following properties:

  • status - 'OK' if the user modified the page, 'CANCELED' if the user canceled the operation.
  • page - the cropped page.
Options:#

The cropping UI requires a page object. A page object can be initially created using the Document Scanner or createPage().

All configuration settings are optional.

export interface CroppingScreenConfiguration{    /**    * The color of the cropping anchor handles.    */    anchorPointsColor?: string;    /**     * String being displayed as a hint. Empty by default.     */    hintTitle?: string;    /**     * Text color of the hint title.     */    hintTitleColor?: string;    /**    * Background color of the main screen.    */    backgroundColor?: string;    /**    * Background color of the bottom toolbar.    */    bottomBarBackgroundColor?: string;    /**    * Color of the titles of all buttons in the bottom toolbar (Rotate button).    */    bottomBarButtonsColor?: string;    /**    * Title of the cancel button.    */    cancelButtonTitle?: string;    /**    * Title of the Done button.    */    doneButtonTitle?: string;    /**    * Default color of the cropping outline.    */    polygonColor?: string;    /**    * Outline color of magnetically snapped edges.    */    polygonColorMagnetic?: string;    /**    * Width of the cropping outline.    */    polygonLineWidth?: number;    /**    * Title of the Rotate button.    */    rotateButtonTitle?: string;    titleColor?: string;    /**    * Background color of the top toolbar.    */    topBarBackgroundColor?: string;    /**    * Color of the titles of all buttons in the top toolbar (Cancel and Done buttons).    */    topBarButtonsColor?: string;    topBarTitle?: string;    /**     * Title of the Detect button.     */    detectButtonTitle?: string;    /**     * Title of the Reset button.     */    resetButtonTitle?: string;    /**     * Controls whether the Rotate button is hidden or not.     */    rotateButtonHidden?: boolean;    /**     * Controls whether the Detect/Reset button is hidden or not.     */    detectResetButtonHidden?: boolean;    /**     * UI orientation lock mode: PORTRAIT, LANDSCAPE, etc.     * By default the UI is not locked.     */    orientationLockMode?: UIOrientationMode;    /**     * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.     * Android only.     */    useButtonsAllCaps?: boolean;     /**     * Allows you to customize the accessibility configuration for the Cropping Screen UI    */    accessibilityConfiguration?: CroppingScreenAccessibilityConfiguration;}
export interface CroppingScreenAccessibilityConfiguration {    /**     * Text, that is used as an accessibility label for the cancel button.     */    cancelButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the cancel button.     */    cancelButtonAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the done button.     */    doneButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the done button.     */    doneButtonAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the detect button.     */    detectButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the detect button.     */    detectButtonAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the reset button.     */    resetButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the reset button.     */    resetButtonAccessibilityHint: string;    /**     * Text, that is used as an accessibility label for the rotate button.     */    rotateButtonAccessibilityLabel: string;    /**     * Text, that is used as an accessibility hint for the rotate button.     */    rotateButtonAccessibilityHint: string;}

Barcode and QR Code Scanner#

ScanbotSdk.UI.startBarcodeScanner(configuration: BarcodeScannerConfiguration): Promise#

Opens a Scanning UI for barcodes and QR codes.

alt

Returns#

The promise resolves to an object with the following properties:

  • status - 'OK' if a barcode was scanned, 'CANCELED' if the user canceled the scanner UI.
  • format - Format of detected barcode/QR code (e.g. CODE_128, EAN_13, QR_CODE, etc).
  • value - Text value of detected barcode/QR code.
Options:#

All settings are optional.

configuration.barcodeFormats is an optional array of barcode formats that acts as a detection filter. By default all supported formats will be detected.

  • configuration.acceptedDocumentFormats is an optional array of barcode document formats that act as a detection filter. By default all supported document formats will be detected.
export interface BarcodeScannerConfiguration {  /**   * An optional array of barcode document formats that act as a detection filter.   * By default all supported document formats will be detected.   */  acceptedDocumentFormats?: BarcodeDocumentFormat[];  /**   * Allowed orientations for automatic interface rotations. *   */  allowedInterfaceOrientations?: UIInterfaceOrientationMask;  /**   * Background color of the detection overlay.   */  cameraOverlayColor?: string;  /**   * The relative initial zoom level of the camera in the range [0,1], where 0 is zoomed out and 1 is zoomed in.   * The default value is 0.   */  cameraZoomFactor?: number;  /**   * Whether the cancel button is hidden or not.   */  cancelButtonHidden?: boolean;  /**   * String being displayed on the cancel button.   */  cancelButtonTitle?: string;  /**   * The engine mode of the barcode recognizer. Defaults to NEXT_GEN.   * To use legacy recognizer, please specify LEGACY   */  engineMode?: EngineMode;  /**   * Foreground color of the detection overlay.   */  finderLineColor?: string;  /**   * Width of finder frame border. Default is 2.   */  finderLineWidth?: number;  /**   * String being displayed as description.   */  finderTextHint?: string;  /**   * Foreground color of the description label.   */  finderTextHintColor?: string;  /**   * Aspect ratio of finder frame (width \ height), which is used to build actual finder frame.   * Default is 1 - it is a square frame, which is good for QR capturing.   */  finderAspectRatio?: FinderAspectRatio;  /**   * String being displayed on the flash button.   */  flashButtonTitle?: string;  /**   * Foreground color of the flash button when flash is off.   */  flashButtonInactiveColor?: string;  /**   * Whether flash is toggled on or off.   */  flashEnabled?: boolean;  /**   * Optional minimum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  minimumTextLength?: number;  /**   * Optional maximum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  maximumTextLength?: number;  /**   * Optional minimum required quiet zone on the barcode.   * Measured in modules (the size of minimal bar on the barcode).   * The default is 10.   * NOTE: This feature works on ITF barcodes only.   */  minimum1DBarcodesQuietZone?: number;  /**   * With this option enabled, the scanner removes checks digits for UPC, EAN and MSI Plessey codes.   * Has no effect if both single and double digit MSI Plessey checksums are enabled.   * The default is `false`   */  stripCheckDigits?: boolean;  /**   * Whether scanner screen should make a sound on successful barcode or MRZ detection.   */  successBeepEnabled?: boolean;  /**   * Background color of the top bar.   */  topBarBackgroundColor?: string;  /**   * Foreground color of the cancel button.   */  topBarButtonsColor?: string;  /**   * Accepted barcode formats   */  barcodeFormats?: BarcodeFormat[];  /**   * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.   * Android only.   */  useButtonsAllCaps?: boolean;  /**   * When set to `true`, the scanner assumes that the barcode can be a GS1 barcode.   * Turn it off, if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).   * The default value is `true`.   * NOTE: Currently works for CODE128 barcodes only!   */  gs1DecodingEnabled?: boolean;  /**   * The checksum algorithms for MSI Plessey barcodes.   * The default value is [MSIPlesseyChecksumAlgorithm.Mod10].   */  msiPlesseyChecksumAlgorithm?: MSIPlesseyChecksumAlgorithm;}

Batch Barcode and QR Code Scanner#

ScanbotSdk.UI.startBatchBarcodeScanner(configuration: BatchBarcodeScannerConfiguration): Promise#

Opens a Scanning UI to scan multiple barcodes and QR-codes in a row.

Result:#

The promise resolves to a result object with the following properties:

  • result.status - 'OK' If there is at least one barcode in the result list available, 'CANCELED' if the user canceled the operation (tapped on the "cancel" button).
  • result.barcodes[] - Array of scanned barcodes/QR codes.
  • result.barcodes[n].type - Format of detected barcode/QR code (e.g. CODE_128, EAN_13, QR_CODE, etc).
  • result.barcodes[n].text - Text value of detected and decoded barcode/QR code.

Options:#

All configuration options are optional.

uiConfigs.barcodeFormats is an optional array of barcode formats that acts as a detection filter. By default all supported formats will be detected.

  • configuration.acceptedDocumentFormats is an optional array of barcode document formats that act as a detection filter. By default all supported document formats will be detected.
export interface BatchBarcodeScannerConfiguration {  /**   * An optional array of barcode document formats that act as a detection filter.   * By default all supported document formats will be detected.   */  acceptedDocumentFormats?: BarcodeDocumentFormat[];  /**   * Allowed orientations for automatic interface rotations. *   */  allowedInterfaceOrientations?: UIInterfaceOrientationMask;  /**   * String used for displaying amount of scanned barcodes. Use %d for number formatting symbol.   */  barcodesCountText?: string;  /**   * Text color of the barcodes count label.   */  barcodesCountTextColor?: string;  /**   * Background color of the detection overlay.   */  cameraOverlayColor?: string;  /**   * Whether the cancel button is hidden or not.   */  cancelButtonHidden?: boolean;  /**   * String being displayed on the cancel button.   */  cancelButtonTitle?: string;  /**   * String being displayed on the clear button.   */  clearButtonTitle?: string;  /**   * String being displayed on the delete button.   */  deleteButtonTitle?: string;  /**   * Foreground color of the top bar buttons on the details screen.   */  detailsActionColor?: string;  /**   * Background color of the details screen.   */  detailsBackgroundColor?: string;  /**   * Text color in the details barcodes list. Also affects image background, separator and progress spinner.   */  detailsPrimaryColor?: string;  /**   * The engine mode of the barcode recognizer. Defaults to NEXT_GEN.   * To use legacy recognizer, please specify LEGACY   */  engineMode?: EngineMode;  /**   * String used to show process of fetching mapped data for barcodes.   */  fetchingStateText?: string;  /**   * Aspect ratio of finder frame (width \ height), which is used to build actual finder frame.   * Default is 1 - it is a square frame, which is good for QR capturing.   */  finderAspectRatio?: FinderAspectRatio;  /**   * Foreground color of the detection overlay.   */  finderLineColor?: string;  /**   * Width of finder frame border. Default is 2.   */  finderLineWidth?: number;  /**   * String being displayed as description.   */  finderTextHint?: string;  /**   * Foreground color of the description label.   */  finderTextHintColor?: string;  /**   * Whether flash is toggled on or off.   */  flashEnabled?: boolean;  /**   * String to show that no barcodes were scanned yet.   */  noBarcodesTitle?: string;  /**   * Enables or disables the barcode detection.   */  recognitionEnabled?: boolean;  /**   * With this option enabled, the scanner removes checks digits for UPC, EAN and MSI Plessey codes.   * Has no effect if both single and double digit MSI Plessey checksums are enabled.   * The default is `false`   */  stripCheckDigits?: boolean;  /**   * String being displayed on the submit button.   */  submitButtonTitle?: string;  /**   * Whether scanner screen should make a sound on successful barcode or MRZ detection.   */  successBeepEnabled?: boolean;  /**   * Background color of the top bar.   */  topBarBackgroundColor?: string;  /**   * Foreground color of the top bar buttons on the scanning screen.   */  topBarButtonsColor?: string;  /**   * Foreground color of the flash button when flash is off.   */  topBarButtonsInactiveColor?: string;  /**   * Accepted barcode formats   */  barcodeFormats?: BarcodeFormat[];  /**   * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.   * Android only.   */  useButtonsAllCaps?: boolean;  /**   * Optional minimum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  minimumTextLength?: number;  /**   * Optional maximum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  maximumTextLength?: number;  /**   * Optional minimum required quiet zone on the barcode.   * Measured in modules (the size of minimal bar on the barcode).   * The default is 10.   * NOTE: This feature works on ITF barcodes only.   */  minimum1DBarcodesQuietZone?: number;
  /**   * When set to `true`, the scanner assumes that the barcode can be a GS1 barcode.   * Turn it off, if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).   * The default value is `true`.   * NOTE: Currently works for CODE128 barcodes only!   */  gs1DecodingEnabled?: boolean;
  /**   * The checksum algorithms for MSI Plessey barcodes.   * The default value is [MSIPlesseyChecksumAlgorithm.Mod10].   */  msiPlesseyChecksumAlgorithm?: MSIPlesseyChecksumAlgorithm;}

ID Card Scanner#

ScanbotSdk.UI.startIdCardScanner(configuration: IdCardScannerConfiguration): Promise#

The ID Card Scanner detects and recognizes ID cards or passports on video frames and extracts the data fields, like names, dates, photo, signature, MRZ, etc.

Note: This feature is currently limited to German ID cards and passports.

The ID Card Scanner is based on the OCR feature and thus requires the proper installation of the OCR language files deu.traineddata and eng.traineddata (aka. blob files). For more details on how to set up OCR language files please refer to the OCR section.

Use the API method ScanbotSdk.UI.startIdCardScanner(configuration: IdCardScannerConfiguration): Promise to start the ID Card Scanner UI.

Result:#

The promise resolves to a result object with the following properties:

  • result.status - 'OK' if detection was successful. 'CANCELED' if the user canceled the operation (tapped on the "cancel" button).
  • result.idCard - contains all the detected fields
    • id
    • surname
    • givenNames
    • birthDate
    • nationality
    • expiryDate
    • mrz
    • photoImageUri
    • signatureImageUri

And additionally, depending on the type of card, the following properties:

  • birthplace
  • issueDate
  • issuingAuthority
  • address
  • eyeColor
  • height
  • pin
  • pseudonym
  • countryCode
  • gender
  • maidenName
  • passportType

Options:#

All configuration options are optional.

  • configuration.acceptedDocumentTypes is an optional array of ID Card Document Types that act as a detection filter. Default is DeIdCardBack and DeIdCardFront.
export interface IdCardScannerConfiguration {  /**   * Accepted document types. All other document types will be ignored.   * By default - DeIdFront and DeIdBack   */  acceptedDocumentTypes?: IDCardDocumentType[];  /**   * Allowed orientations for automatic interface rotations   */  allowedInterfaceOrientations?: UIInterfaceOrientationMask;  /**   * Background color of the detection overlay.   */  cameraOverlayColor?: string;  /**   * Whether the cancel button is hidden or not (iOS only)   */  cancelButtonHidden?: boolean;  /**   * String being displayed on the cancel button.   */  cancelButtonTitle?: string;  /**   * String being displayed on the clear button.   */  clearButtonTitle?: string;  /**   * String that shows average confidence value of scanned card. Use %li as number formatting symbol.   */  confidenceValue?: string;  /**   * Foreground color of the top bar buttons on the details screen.   */  detailsActionColor?: string;  /**   * Background color of the details screen.   */  detailsBackgroundColor?: string;  /**   * Text color in the details list. Also affects image background and separator.   */  detailsPrimaryColor?: string;  /**   * The title for the results group in the ID card scanner list, for `DePassport`   */  dePassportDocumentTitle?: string;  /**   * The title for the results group in the ID card scanner list, for `DeIdCardBack`   */  deIdCardBackDocumentTitle?: string;  /**   * The title for the results group in the ID card scanner list, for `DeIdCardFront`   */  deIdCardFrontDocumentTitle?: string;  /**   * A title for address field in details screen.   */  fieldAddressTitle?: string;  /**   * A title for birth date field in details screen.   */  fieldBirthDateTitle?: string;  /**   * A title for birth place field in details screen.   */  fieldBirthPlaceTitle?: string;  /**   * Color of confidence value label background in details screen, when the field confidence level is high.   */  fieldConfidenceHighColor?: string;  /**   * Color of confidence value label background  in details screen, when the field confidence level is low.   */  fieldConfidenceLowColor?: string;  /**   * Color of confidence value label background  in details screen, when the field confidence level is moderate.   */  fieldConfidenceModerateColor?: string;  /**   * Color of confidence value label text in details. Use %d for number formatting symbol.   */  fieldConfidenceTextColor?: string;  /**   * A title for country code field in details screen.   */  fieldCountryCodeTitle?: string;  /**   * A title for expiry date field in details screen.   */  fieldExpiryDateTitle?: string;  /**   * A title for eye color field in details screen.   */  fieldEyeColorTitle?: string;  /**   * A title for gender field in details screen.   */  fieldGenderTitle?: string;  /**   * A title for given names field in details screen.   */  fieldGivenNamesTitle?: string;  /**   * A title for height field in details screen.   */  fieldHeightTitle?: string;  /**   * A title for id field in details screen.   */  fieldIDTitle?: string;  /**   * A title for issuing date field in details screen.   */  fieldIssueDateTitle?: string;  /**   * A title for issuing authority  field in details screen.   */  fieldIssuingAuthorityTitle?: string;  /**   * A title for maiden name field in details screen.   */  fieldMaidenNameTitle?: string;  /**   * A title for machine readable zone field in details screen.   */  fieldMRZTitle?: string;  /**   * A title for nationality field in details screen.   */  fieldNationalityTitle?: string;  /**   * A title for passport type field in details screen.   */  fieldPassportTypeTitle?: string;  /**   * A title for photo field in details screen.   */  fieldPhotoTitle?: string;  /**   * A title for PIN field in details screen.   */  fieldPINTitle?: string;  /**   * A title for pseudonym field in details screen.   */  fieldPseudonymTitle?: string;  /**   * String used for displaying amount of detected fields. Use %li for number formatting symbol.   */  fieldsCountText?: string;  /**   * Text color of the fields count label. Use %d for number formatting symbol.   */  fieldsCountTextColor?: string;  /**   * A title for signature field in details screen.   */  fieldSignatureTitle?: string;  /**   * A title for surname field in details screen.   */  fieldSurnameTitle?: string;  /**   * Foreground color of the detection overlay.   */  finderLineColor?: string;  /**   * Width of finder frame border. Default is 2.   */  finderLineWidth?: number;  /**   * Whether the torch light is toggled on or off.   */  flashEnabled?: boolean;  /**   * A title to show image content.   */  imageTitle?: string;  /**   * String that notifies that nothing was scanned yet.   */  noDataTitle?: string;  /**   * String that asks user to scan back side of a card.   */  scanBackSideTitle?: string;  /**   * String that asks user to scan front side of a card.   */  scanFrontSideTitle?: string;  /**   * String that notifies that both sides of card are scanned.   */  scannedEverythingTitle?: string;  /**   * Defines, if photo image should be stored in internal storage (SBSDKUIIDCardStorage) on disk.   */  shouldSavePhotoImageInStorage?: boolean;  /**   * Defines, if signature image should be stored in internal storage (SBSDKUIIDCardStorage) on disk.   */  shouldSaveSignatureImageInStorage?: boolean;  /**   * String that asks user to start scanning a card.   */  startScanningTitle?: string;  /**   * String being displayed on the 'View Results' button.   */  viewResultsButtonTitle?: string;  /**   * Color of tip background on scanning screen.   */  tipBackgroundColor?: string;  /**   * Color of tip text on scanning screen.   */  tipTextColor?: string;  /**   * Background color of the top bar.   */  topBarBackgroundColor?: string;  /**   * Foreground color of the top bar buttons on the scanning screen.   */  topBarButtonsColor?: string;  /**   * Foreground color of the flash button when flash is off.   */  topBarButtonsInactiveColor?: string;  /**   * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.   * Android only.   */  useButtonsAllCaps?: boolean;  /**   * The accepted minimal sharpness score. Images with a score less than that will   * be rejected with blurry status.   *   * 0 - any image will be accepted (NOTE: the value must be > 0 for the ID Card Scanner to work)   * 80 - a good compromise; the recommended setting.   * 100 - only very sharp images will be accepted.   *   * The default value is 80.   */  sharpnessAcceptanceFactor?: number;}

Machine-readable Zone Scanner (MRZ Scanner)#

ScanbotSdk.UI.startMrzScanner(configuration: MrzScannerConfiguration)#

Opens a Scanner for machine-readable zones.

alt

Returns#

The promise resolves to an object with the following properties:

  • status - 'OK' if MRZ data was scanned, 'CANCELED' if the user canceled the scanner UI.
  • fields - an array of MRZ fields. Each field is an object with the following properties:
    • field.name - the field type
    • field.value - the value of the field
    • field.confidence - confidence in the accuracy of value
Options:#

The finder window must have a width-to-height of 5, otherwise the detection process will fail. All other settings are optional.

export interface MrzScannerConfiguration{    bottomButtonsActiveColor?: string;    bottomButtonsInactiveColor?: string;    /**    * Background color outside of the finder window.    */    cameraOverlayColor?: string;    /**    * Title of the cancel button.    */    cancelButtonTitle?: string;    /**    * Title of the button that opens the screen where the user can allow    * the usage of the camera by the app.    */    enableCameraButtonTitle?: string;    /**    * Text that will be displayed when the app    * is not allowed to use the camera, prompting the user    * to enable the usage of the camera.    */    enableCameraExplanationText?: string;    /**    * Height of the finder window in pixels.    */    finderHeight?: number;    /**    * Color of the finder window's outline.    */    finderLineColor?: string;    /**    * Thickness of the finder window's outline.    */    finderLineWidth?: number;    /**    * Text hint shown under the finder window.    */    finderTextHint?: string;    /**    * Color of the text hint under the finder window.    */    finderTextHintColor?: string;    /**    * Width of the finder window in pixels.    */    finderWidth?: number;    flashButtonTitle?: string;    /**    * Controls whether the flash should be initially enabled.    * The default value is FALSE.    */    flashEnabled?: boolean;    /**    * Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.    * By default the camera orientation is not locked.    */    orientationLockMode?: CameraOrientationMode;    /**    * Controls whether to play a beep sound after a successful detection.    * Default value is TRUE.    */    successBeepEnabled?: boolean;    /**    * Background color of the top toolbar.    */    topBarBackgroundColor?: string;    /**    * Color of the titles of all buttons in the top toolbar.    */    topBarButtonsColor?: string;    /**     * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.     * Android only.     */    useButtonsAllCaps?: boolean;}

European Health Insurance Card Scanner (EHIC Scanner)#

ScanbotSdk.UI.startEHICScanner(configuration: HealthInsuranceCardScannerConfiguration)#

Opens a Scanner for European Health Insurance Cards

alt

The EHIC Scanner is based on the OCR feature and thus requires the proper installation of the OCR language files deu.traineddata and eng.traineddata (aka. blob files). For more details on how to set up OCR language files please refer to the OCR section.

Use the API method ScanbotSdk.UI.startEHICScanner(configuration: HealthInsuranceCardScannerConfiguration) to start the EHIC Scanner UI.

Options:#
export interface HealthInsuranceCardScannerConfiguration{    /**     * Allowed orientations for automatic interface rotations. *     */    allowedInterfaceOrientations?: UIInterfaceOrientationMask;    /**     * Foreground color of the flash button when flash is on.     */    bottomButtonsActiveColor?: string;    /**     * Foreground color of the flash button when flash is off.     */    bottomButtonsInactiveColor?: string;    /**     * Background color of the detection overlay.     */    cameraOverlayColor?: string;    /**     * Whether the cancel button is hidden or not.     */    cancelButtonHidden?: boolean;    /**     * String being displayed on the cancel button.     */    cancelButtonTitle?: string;    /**     * The receiver's delegate.     */    delegate?: any;    /**     * String being displayed when health insurance card was not found.     */    detectionStatusFailedDetectionText?: string;    /**     * String being displayed when health insurance card was found but not recognized.     */    detectionStatusFailedValidationText?: string;    /**     * String being displayed when health insurance card was found and recognized.     */    detectionStatusSuccessText?: string;    /**     * Foreground color of the detection overlay.     */    finderLineColor?: string;    /**     * Width of finder frame border. Default is 2.     */    finderLineWidth?: number;    /**     * String being displayed as description.     */    finderTextHint?: string;    /**     * Foreground color of the description label.     */    finderTextHintColor?: string;    /**     * String being displayed on the flash button.     */    flashButtonTitle?: string;    /**     * Whether flash is toggled on or off.     */    flashEnabled?: boolean;    /**     * Enables or disables the machine readable zones detection.     */    recognitionEnabled?: boolean;    /**     * Background color of the top bar.     */    topBarBackgroundColor?: string;    /**     * Foreground color of the cancel button.     */    topBarButtonsColor?: string;    /**     * The type of health insurance card validation.     */    validationType?: HealthInsuranceCardValidationType;    /**     * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.     * Android only.     */    useButtonsAllCaps?: boolean;}

Returns#

The promise resolves to an object with the following properties:

  • status - 'OK' if EHIC data was scanned, 'CANCELED' if the user canceled the scanner UI.
  • fields - an array of EHIC data fields. Each field is an object with the following properties:
    • field.type - the field type
    • field.value - the value of the field
    • field.confidence - confidence in the accuracy of value

NFC Passport Reader#

ScanbotSdk.UI.startNFCPassportReader(configuration: NFCPassportReaderConfiguration)#

Opens a scanner and reader UI for passport's NFC chip

alt alt

Options:#
export interface NFCPassportReaderConfiguration {    /**    * Allowed orientations for automatic interface rotations. *    */    allowedInterfaceOrientations?: UIInterfaceOrientationMask;    /**    * A title for the error, when NFC reader failed to perform authentication.    */    authenticationErrorTitle?: string;    /**    * Background color of the detection overlay.    */    cameraOverlayColor?: string;    /**    * Whether the cancel button is hidden or not.    */    cancelButtonHidden?: boolean;    /**    * String being displayed on the cancel button.    */    cancelButtonTitle?: string;    /**    * A title for the error, when NFC reader failed to download the data.    */    downloadErrorTitle?: string;    /**    * A hint that notifies about downloading datagroups.    */    downloadingDataTitle?: string;    /**    * Foreground color of the detection overlay.    */    finderLineColor?: string;    /**    * Width of inner finder frame border. Default is 2.    */    finderLineWidth?: number;    /**    * String being displayed as description.    */    finderTextHint?: string;    /**    * Foreground color of the description label.    */    finderTextHintColor?: string;    /**    * Whether flash is toggled on or off.    */    flashEnabled?: boolean;    /**    * String being displayed as a hint to hold device over the NFC chip.    */    holdOverTheChipTitle?: string;    /**    * A title for the state when there is no NFC chip installed on the device, or it is not available.    */    noChipErrorTitle?: string;    /**    * The owner's photo image URL. Storage for this URL can be controlled with SBSDKUINFCPassportReaderStorage.    */    photoImageURL?: string;    /**    * Color of the progress bar.    */    progressBarColor?: string;    /**    * Defines if photo image should be stored in internal storage (SBSDKUINFCPassportReaderStorage) on disk.    */    shouldSavePhotoImageInStorage?: boolean;    /**    * Whether scanner screen should make a sound on successful MRZ detection.    */    successBeepEnabled?: boolean;    /**    * Background color of the top bar.    */    topBarBackgroundColor?: string;    /**    * Foreground color of the cancel button and selected flash button.    */    topBarButtonsColor?: string;    /**    * Foreground color of the flash button when the flash is off.    */    topBarButtonsInactiveColor?: string;}

Returns#

The promise resolves to an object with the following properties:

  • status - 'OK' if NFC data was read, 'CANCELED' if the user canceled the scanner UI.
  • passportResult - a dictionary of NFC fields. Each field is an object with the following properties:
    • datagroupDG1 - Data group 1 or DG1. Contains general information about the passport and its holder. -key - The key of the element in the passport's data group. -value - The value of the element in the passport's data group.
    • datagroupDG2 - Data group 2 or DG2. Contains visual biometric data of the passport's holder. -key - The key of the element in the passport's data group. -value - The value of the element in the passport's data group.

Vehicle License Plate Scanner#

ScanbotSdk.UI.startLicensePlateScanner(configuration: LicensePlateScannerConfiguration)#

Opens a Scanner for Vehicle License Plates

alt alt

Options:#
export interface LicensePlateScannerConfiguration {    /** Foreground color of the top bar buttons when they are active. */    topBarButtonsColor?: string;
    /** Foreground color of the top bar buttons when they are inactive. */    topBarButtonsInactiveColor?: string;
    /** Background color of the top bar. */    topBarBackgroundColor?: string;
    /** Foreground color of the detection overlay. */    finderLineColor?: string;
    /** Width of finder frame border. Default is 2. */    finderLineWidth?: number;
    /** Foreground color of the description label. */    finderTextHintColor?: string;
    /** Background color of the detection overlay. */    cameraOverlayColor?: string;
    /** Whether the cancel button is hidden or not. */    cancelButtonHidden?: boolean;
    /** Allowed orientations for automatic interface rotations. **/    allowedInterfaceOrientations?: UIInterfaceOrientationMask;
    /** Whether the flash light is toggled on or off. */    flashEnabled?: boolean;
    /**     * The maximum number of accumulated video frames before the current recognition result is returned. Defaults to 3.     */    maximumNumberOfAccumulatedFrames?: number;
    /**     * The minimum equal results in accumulated video frames to count as valid. Defaults to 2.     */    minNumberOfRequiredFramesWithEqualRecognitionResult?: number;
    /** The detector mode used to find a license plate in an image (CLASSIC or ML_BASED). Default value is ML_BASED. */    detectorMode?: LicensePlateDetectorMode;
    /** The string being displayed on the cancel button. */    cancelButtonTitle?: string;
    /** The string being displayed as description. */    finderTextHint?: string;
    /** The title of the confirmation dialog. */    confirmationDialogTitle?: string;
    /** The message text of the confirmation dialog. */    confirmationDialogMessage?: string;
    /** The title of the confirmation dialog retry button. */    confirmationDialogRetryButtonTitle?: string;
    /** The title of the confirmation dialog confirm button. */    confirmationDialogConfirmButtonTitle?: string;
    /** Whether the confirm button of the confirmation dialog should be filled or not */    confirmationDialogConfirmButtonFilled?: boolean;
    /** The text of the confirm button in the confirmation dialog when the button is filled */    confirmationDialogConfirmButtonFilledTextColor?: string;
    /** The accent color used for styling the confirmation dialog */    confirmationDialogAccentColor?: string;
    /**     * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.     * Android only.     */    useButtonsAllCaps?: boolean;}

Returns#

The promise resolves to an object with the following properties:

  • status - 'OK' if the License Plate was scanned, 'CANCELED' if the user canceled the scanner UI.
  • licensePlate - the License Plate detected by the scanner
  • confidence - confidence in the accuracy of the detection (0 - 100)
  • countryCode - the Country Code on the License Plate as detected by the scanner
  • rawText- the entire raw text detected on the License Plate by the scanner
  • isValidationSuccessful - true if the validation of the scanned license plate was successful, false otherwise (iOS only)

Text Data Scanner#

ScanbotSdk.UI.startTextDataScanner(configuration: TextDataScannerConfiguration): Promise#

Opens a Scanning UI to perform OCR and detect text data.

alt text

The Text Data Scanner is based on the OCR feature and thus requires the proper installation of the corresponding OCR language files (e.g. for English please add the file eng.traineddata). For more details on how to set up OCR language files please refer to the OCR section.

Use the API method ScanbotSdk.UI.startTextDataScanner(configuration: TextDataScannerConfiguration): Promise to start the Text Data Scanner UI.

Result:#

The promise resolves to a result object with the following properties:

  • status - 'OK' If any text was detected; 'CANCELED' if the user canceled the operation (tapped on the "cancel" button).
  • result
    • text - the recognized text
    • confidence - confidence in the accuracy of the detection (0 - 100)

Options:#

All configuration options are optional.

export interface TextDataScannerConfiguration {
    /**     * Allowed orientations for automatic interface rotations. *     */    allowedInterfaceOrientations?: UIInterfaceOrientationMask;    /**     * A string (list) of accepted characters during text recognition.     * If empty or nil, all characters are accepted.     * Defaults to nil.     */    allowedSymbols?: string[];    /**     * The aspect ratio for the workflow steps region of interest and, equally, for the finder view.     * Defaults to 5:1.     */    aspectRatio?: FinderAspectRatio;    /**     * Background color of the detection overlay.     */    cameraOverlayColor?: string;    /**     * Whether the cancel button is hidden or not.     */    cancelButtonHidden?: boolean;    /**     * String being displayed on the cancel button.     */    cancelButtonTitle?: string;    /**     * Foreground color of the detection overlay.     */    finderLineColor?: string;    /**     * Width of finder frame border. Default is 2.     */    finderLineWidth?: number;    /**     * Foreground color of the description label.     */    finderTextHintColor?: string;    /**     * Foreground color of the flash button when flash is off.     */    flashButtonInactiveColor?: string;    /**     * Whether flash is toggled on or off.     */    flashEnabled?: boolean;    /**     * A user guidance hint for this workflow step.     * The guidance hint is displayed while the workflow step is active.     */    guidanceText?: string;    /**     * The maximum number of accumulated video frames before the current recognition result is returned.     */    maximumNumberOfAccumulatedFrames?: any;    /**     * The minimum equal results in accumulated video frames to count as valid.     */    minimumNumberOfRequiredFramesWithEqualRecognitionResult?: any;    /**     * Maximum image side length (height or width) for OCR processing.     * If the initial image has longer side - it will be downscaled to the limit.     * Setting to 0 means no limit. Default is 0.     * Using this parameter might be useful for slower devices or to reduce processing load.     */    ocrResolutionLimit?: any;    /**     * Sets a validation pattern to validate to automatically validate recognized text.     * &lsquo;?&rsquo; = any character     * &lsquo;#&rsquo; - any digit     * All other characters represent themselves.     */    pattern?: string;    /**     * The cameras zoom level preferred for this step. The actual zoom might be different from the preferred one     * to avoid clipping of finder area and maintain its aspect ratio and height;     */    preferredZoom?: number;    /**     * Enables or disables the recognition.     */    recognitionEnabled?: boolean;    /**     * If set to YES pattern validation also validates successfully if only a part of the whole recognized text matches     * the the validation pattern.     * If set to NO, the whole text must match the validation pattern.     * Applies to pattern validation only. Defaults to NO.     */    shouldMatchSubstring?: boolean;    /**     * ! EXPERIMENTAL !     * Callback to clean a recognized text prior to validation. Filter out unwanted phrases and textual noise here.     * Default is nil.     * eg.     *      * (text) => {     *   let out = text.toUpperCase();     *   if (out[0] === 'X') {     *      out = out.replace('X', '');     *   }     *   return out;     * }     *      * Notes:      * • Use JSStringToStringTextFunctionBuilder! Do not set this manually;     * • Do not reference any external library or any variable that is declared outside of the      *   scope of the function     */    stringSanitizerBlock?: JSStringToStringTextFunction;    /**     * A string of two-letter ISO 639-1 language codes, separated by &lsquo;+&rsquo;,     * the OCR engine should use for recognition. E.g. &ldquo;de+en&rdquo;     * (german and english) &ldquo;ar+he+ja&rdquo; (arabic, hebrew and japanese).     * If the string is invalid or nil the user preferred languages are used.     * Ignores white spaces, invalid languages and invalid characters.     */    supportedLanguages?: string;    /**     * The title of the step.     * By default it is an empty.     */    title?: string;    /**     * Recognition strategy for the text. Default is 'Document'.     */    textFilterStrategy?: TextFilterStrategy;    /**     * Background color of the top bar.     */    topBarBackgroundColor?: string;    /**     * Foreground color of the cancel button and when flash button is on.     */    topBarButtonsColor?: string;    /**     * The preferred height of the finder for zoom scale 1.0 (unzoomed).     * The actual finder height might change to maintain aspect ratio and to not clip the screen.     * Defaults to 40 points.     */    unzoomedFinderHeight?: number;    /**     * ! EXPERIMENTAL !     * Callback block for recognized text validation. If pattern validation is not powerful enough, you can     * specify your own validation block here. Defaults to nil.     * eg.     *      * (text) => {     *   let firstLetter = text[0].toUpperCase();     *   let length = text.length;     *   return firstLetter === 'A' && length >= 4 && length < 20;     * }     *      * Notes:      * • Use JSStringToBoolTextFunctionBuilder! Do not set this manually;     * • Do not reference any external library or any variable that is declared outside of the      *   scope of the function     */    validationBlock?: JSStringToBoolTextFunction;    /**     * The color of the word boxes. It is recommended to use colors with alpha &lt; 0.5.     */    wordBoxHighlightColor?: string;    /**     * Whether the word boxes should be shown.     */    wordBoxHighlightEnabled?: boolean;}

Page Operations#

ScanbotSdk.createPage(imageUri: string): Promise<Page>#

Creates a page from an image (presumably the image of an uncropped document).

Returns#

The promise resolves to a page object. As the page has not been cropped yet, the documentImageFileUri and documentPreviewImageFileUri properties will be empty.

ScanbotSdk.setDocumentImage(page: Page, imageUri: string): Promise<Page>#

Replaces the document image of a page. The passed image file will be copied into the internal page file storage.

  • page - the page to modify.
  • imageUri - the URI of an image file with which to overwrite the page's document image.

Returns#

The promise resolves to a page object with the replaced document image.

ScanbotSdk.detectDocumentOnPage(page: Page): Promise<Page>#

Runs document detection on the original image of the given page. The detection status, polygon and cropped document image are returned as a new page object in the returned promise.

ScanbotSdk.applyImageFilterOnPage(page: Page, filter: ImageFilter): Promise<Page>#

Applies a filter to the unfiltered document image of a page.

  • page - the page to filter.
  • imageFilter - the image filter to apply. The special value 'NONE' will remove any previously applied filter from the document image.

ScanbotSdk.getFilteredDocumentPreviewUri(page: Page, imageFilter: ImageFilter): Promise<string>#

Creates a preview image of a filter applied onto the document of a page. Does not modify the document image of the passed page.

  • page - the page for which to create a filtered document preview.
  • imageFilter - the image filter to apply. The special value 'NONE' will remove any previously applied filter from the document image.

Returns#

A file URI with the preview image of the filtered document page.

ScanbotSdk.rotatePage(page: Page, times: number)#

Rotates a page counter-clockwise in increments of 90 degrees.

  • page - the page to rotate.
  • times - the number of counter-clockwise 90 degree rotations to apply.

ScanbotSdk.removePage(page: Page): Promise#

Removes all images of a page from the file storage.

Raw Image Operations#

Document Detection#

ScanbotSDK.detectDocument(imageFileUri: string): Promise#

The Scanbot SDK uses digital image processing algorithms to find rectangular, document like, polygons in a digital image. This function applies edge dectection and processes all image operations in a background thread. There will be no UI started. As input, a file URI of an image must be passed. The output contains the Detection Result as a string and on success the cropped and perspective corrected image as a new file as well as the detected polygon. If there was no document detected the result enum provides the exact reason (noisy background, too dark, etc). The input image file will not be modified.

Returns#

Returns object with the following fields

  • documentImageFileUri - File URI of the detected and cropped/warped document image as JPEG ('file:///...'). May be null if detection was not successfull.
  • polygon - Contains the detected polygon as an array. May be empty if detection was not successful.
  • detectionResult - The Detection Result.

Detect Barcodes on an Image#

This function will detect barcodes/QR codes in the given image. As input a file URI of an image must be passed. The output returns a BarcodeResult containing an array of all the barcodes/QR codes that have been detected on the given image.

ScanbotSDK.detectBarcodesOnImage(args: DetectBarcodesOnImageArguments): Promise<BarcodeResult>

Arguments

export interface DetectBarcodesOnImageArguments {  /**   * The input image file URI   */  imageFileUri: string;  /**   * Accepted barcode formats   */  barcodeFormats?: BarcodeFormat[];  /**   * An optional array of barcode document formats that act as a detection filter.   * By default all supported document formats will be detected.   */  acceptedDocumentFormats?: BarcodeDocumentFormat[];  /**   * Optional minimum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  minimumTextLength?: number;  /**   * Optional maximum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  maximumTextLength?: number;  /**   * Optional minimum required quiet zone on the barcode.   * Measured in modules (the size of minimal bar on the barcode).   * The default is 10.   * NOTE: This feature works on ITF barcodes only.   */  minimum1DBarcodesQuietZone?: number;  /**   * With this option enabled, the scanner removes checks digits for UPC, EAN and MSI Plessey codes.   * Has no effect if both single and double digit MSI Plessey checksums are enabled.   * The default is `false`   */  stripCheckDigits?: boolean;}

Returns#

Returns object with the following fields

  • status - 'OK' or 'ERROR' in all error cases.
  • barcodes - the array of detected barcodes.
    • type - the detected BarcodeFormat
    • text - text value of detected barcode/QR code.

Detect Barcodes on Multiple Images#

This function will detect barcodes/QR codes in the given images. As input an array of image file URIs must be passed. The output returns a DetectBarcodesOnImagesResult containing an array of all the barcodes/QR codes that have been detected on the given images.

ScanbotSDK.detectBarcodesOnImages(args: DetectBarcodesOnImagesArguments): Promise<DetectBarcodesOnImagesResult>

Arguments

export interface DetectBarcodesOnImagesArguments {  /**   * The input image files URIs   */  imageFileUris: string[];  /**   * Accepted barcode formats   */  barcodeFormats?: BarcodeFormat[];  /**   * An optional array of barcode document formats that act as a detection filter.   * By default all supported document formats will be detected.   */  acceptedDocumentFormats?: BarcodeDocumentFormat[];  /**   * Optional minimum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  minimumTextLength?: number;  /**   * Optional maximum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  maximumTextLength?: number;  /**   * Optional minimum required quiet zone on the barcode.   * Measured in modules (the size of minimal bar on the barcode).   * The default is 10.   * NOTE: This feature works on ITF barcodes only.   */  minimum1DBarcodesQuietZone?: number;  /**   * With this option enabled, the scanner removes checks digits for UPC, EAN and MSI Plessey codes.   * Has no effect if both single and double digit MSI Plessey checksums are enabled.   * The default is `false`   */  stripCheckDigits?: boolean;}

Returns#

Returns object with the following fields

  • status - 'OK' or 'ERROR' in all error cases.
  • results - the array of results
    • imageFileUri - the imageFileUri on which the detection was executed
    • barcodeResults - the array of barcodes that have been detected in the image
      • type - the detected BarcodeFormat
      • text - text value of detected barcode/QR code.
    • error - an optional string that contains an error description when the detection fails

Rotate Image#

ScanbotSDK.rotateImage(imageFileUri: string, degrees: number): Promise<string>#

Rotates an image by given degrees value. As input, a file URI of the image must be passed. The output image will be a new file. The input image file will not be modified.

Returns#

Promise returning the file URI of the rotated result image.

Apply Image Filter#

ScanbotSDK.applyImageFilter(imageFileUri: string, filter: ImageFilter): Promise<string>#

Applies filter to an image. As input, a file URI of the image must be passed. The output image will be a new file. The input image file will not be modified.

  • imageFileUri - file URI of the image to rotate
  • filter - ImageFilter string value

Returns#

File URI to the rotated image file.

Estimate Blur#

ScanbotSdk.estimateBlur(options: {imageFileUri: string}): Promise#

Estimates image blurriness. Less is sharper, more is blurred.

In broad terms, consider blur values as follows:

  • 0.0-0.3: This image is not blurry at all
  • 0.3-0.6: Somewhat blurry, should be ok
  • 0.6-1.0: I am skeptical of the usefulness of the image

However, this is not as easy as it seems. If a scanned document has a predominantly white background, it will be considered a very blurred image. It is therefore best to use blur estimator in conjunction with a finder view or on an already cropped document.

Options#

var options = {  imageFileUri: 'file:///...',};

Result#

  • status - 'OK' or 'ERROR' in all error cases.
  • message - Contains the error message as string.
  • blur - numeric blur value, as explained above.

PDF Creation#

ScanbotSDK.createPDF(imageFileUris: string[], pageSize: PDFPageSize): Promise#

The Scanbot SDK renders given images into a PDF document and stores it as a file. For each image a separate page is generated.

  • imageFileUris - Input images as an array of file URIs in proper order (image element 1 => page 1, etc).
  • pageSize - PDFPageSize enum value to specify the output page size.

Returns#

Returns an object with the following properties:

  • pdfFileUri - file URI with the path to the created PDF file

TIFF Creation#

ScanbotSDK.writeTIFF(imageFileUris: string[], options): Promise#

The Scanbot SDK renders the given images into a multi-page TIFF file and stores it as a file. For each image a separate page is generated.

  • imageFileUris - Input images as an array of file URIs in proper order (image element 1 => page 1, etc).
  • options - An object containing some of the following properties:
    • oneBitEncoded - if true, the input images will be binarized and the output TIFF file will be saved with one bit per pixel. If false, the input images will be stored as-is. The default value is false.
    • dpi - Optional integer value for Dots Per Inches. The default value is 200 dpi.
    • compression - Optional TIFF compression type. The default value depends on the oneBitEncoded flag. CCITT_T6 (CCITT Fax 4) is the default value for binarized (oneBitEncoded=true) images. For color images (oneBitEncoded=false) the default value is ADOBE_DEFLATE (ZIP).

Returns#

Returns an object with the following properties:

  • tiffFileUri - file URI with the path to the created TIFF file

TIFF Compression Types#

Following TIFF compression types are supported:

  • NONE : No compression.
  • CCITT_T6 : "CCITT Fax 4" compression type. Most common and recommended type for binarized (1-bit) black and white images to achieve a small TIFF file size.
  • ADOBE_DEFLATE : "ZIP" compression type. Most common type for color images.
  • CCITTRLE
  • CCITTFAX3
  • CCITT_T4
  • CCITTFAX4
  • CCITTRLEW
  • LZW
  • PACKBITS
  • DEFLATE

⚠️ Please note that the following compression types are only compatible for binarized images (1-bit encoded black & white images): CCITTRLE, CCITTFAX3, CCITT_T4, CCITTFAX4, CCITT_T6, CCITTRLEW.

Extract Images from PDF#

This API function allows you to extract JPG images from a PDF file.

ScanbotSDK.extractImagesFromPdf(    args: ExtractImagesFromPdfArguments): Promise<ExtractImagesFromPdfResult>

Arguments

interface ExtractImagesFromPdfArguments {  /**   * The location of the PDF file   */  pdfFilePath: string;  /**   * The quality that each extracted image should have.   * This tweaks the compression, affecting the final image file size.   * (100: maximum quality, 0: minimum quality)   *   * Default value is 90   */  quality?: number;  /**   * Integer scaling factor applied to the PDF media box frame while extracting.   * Affects the output image quality.   * In most cases the recommended value is 2 or higher.   *   * Default value is 2.   */  scaling?: number;}

Returns

Returns an object with the following properties:

  • status - The status of the operation (OK or CANCELED)
  • imageFilesUrls - A list containing the file URLs for the extracted images, or undefined if the extraction failed

Extract Pages from PDF#

This API function allows you to extract pages from a PDF file.

ScanbotSDK.extractPagesFromPdf(    args: ExtractPagesFromPdfArguments): Promise<ExtractPagesFromPdfResult>

Arguments

interface ExtractPagesFromPdfArguments {  /**   * The location of the PDF file   */  pdfFilePath: string;  /**   * The quality that each extracted image should have.   * This tweaks the compression, affecting the final image file size.   * (100: maximum quality, 0: minimum quality)   *   * Default value is 90   */  quality?: number;  /**   * Integer scaling factor applied to the PDF media box frame while extracting.   * Affects the output image quality.   * In most cases the recommended value is 2 or higher.   *   * Default value is 2.   */  scaling?: number;}

Returns

Returns an object with the following properties:

  • status - The status of the operation (OK or CANCELED)
  • pages - A list containing the extracted pages, or undefined if the extraction failed

OCR - Optical Character Recognition#

The Scanbot SDK RN Module provides a simple and convenient API to run Optical Character Recognition (OCR) on images. The OCR feature is a part of the Scanbot SDK Package II. It is based on the Tesseract OCR Engine with some modifications and enhancements.

Preconditions to achieve a good OCR result#

Conditions while scanning

A perfect document for OCR is flat, straight, in the highest possible resolution and does not contain large shadows, folds, or any other objects that could distract the recognizer. Our UI and algorithms do their best to help you meet these requirements. But as in photography, you can never fully get the image information back that was lost during the shot.

Languages

You can use multiple languages for OCR. But since the recognition of characters and words is a very complicated process, increasing the number of languages lowers the overall precision. With more languages, there are more results where the detected word could match. We suggest using as few languages as possible. Make sure that the language you are trying to detect is supported by the SDK and added to the project.

Size and position

Put the document on a flat surface. Take the photo from straight above in parallel to the document to make sure that the perspective correction does not need to be applied much. The document should fill most of the camera frame while still showing all of the text that needs to be recognized. This results in more pixels for each character that needs to be detected and hence, more detail. Skewed pages decrease the recognition quality.

Light and shadows

More ambient light is always better. The camera takes the shot at a lower ISO value, which results in less grainy photos. You should make sure that there are no visible shadows. If you have large shadows, it is better to take the shot at an angle instead. We also do not recommend using the flashlight - from this low distance it creates a light spot at the center of the document which decreases the recognition quality.

Focus

The document needs to be properly focused so that the characters are sharp and clear. The autofocus of the camera works well if you meet the minimum required distance for the lens to be able to focus. This usually starts at 5-10cm.

Typefaces

TThe OCR trained data is optimized for common serif and sans-serif font types. Decorative or script fonts drastically decrease the quality of the recognition.

OCR Languages and Data Files#

The OCR engine supports a wide variety of languages. For each desired language a corresponding OCR training data file (.traineddata) must be provided. Furthermore the special data file osd.traineddata is required (used for orientation and script detection).

The Scanbot SDK RN Module ships with no training data files by default to keep the package small in size. You have to download and provide the desired language files in your app.

Download and Provide OCR Language Files#

You can find a list of all supported OCR languages and download links on the Tesseract wiki page.

Download#

⚠️️️ Please choose and download the proper version of the language data files:

Provide#

Option 1 - Provide the Language Files in the App Package:

Download the desired language files as well as the osd.traineddata file and make sure they will be packaged in your app as:

  • for Android: as assets in the sub-folder ocr_blobs/
  • for iOS: as resources in the sub-folder ScanbotSDKOCRData.bundle/

Option 2 - Provide the Language Files On-Demand:

Alternatively, to keep the app package small, you can download and provide the language files in your app on run-time. Implement a suitable download functionality of the desired language files + osd.traineddata file and place them in the languageDataPath directory which can be determined by the getOCRConfigs method on run-time.

Language Codes#

The Tesseract language data files are identified by a 3-letter language code. For example:

  • eng - English
  • deu - German
  • etc.

The Scanbot SDK API uses a 2-letter ISO code:

  • en - English
  • de - German
  • etc.
Example:#

If you want to perform OCR with languages English and German, you have to download and install the following data files:

  • eng.traineddata - language file for English
  • deu.traineddata - language file for German
  • osd.traineddata - special data file for orientation and script detection

Then, in the Scanbot SDK module use languages: ["en", "de"].

OCR API#

ScanbotSDK.performOCR(imageFileUris: string[], languages: string[], options): Promise#

This function takes an array of images and performs Optical Character Recognition on each of the images. The recognized text can be returned as plain text or a composed PDF file containing selectable and searchable text.

  • imageFileUris - Input images as an array of file URIs in proper order (image element 1 => page 1, etc).
  • languages - An array with OCR languages of the text to be recognized (e.g. ["en", "de"]). The number of languages has an impact on the performance - the more languages, the slower the recognition process. The OCR operation will fail with an error if some of the specified languages are missing. Please use the getOCRConfigs function to make sure that desired languages are installed.
  • options - an object containing some of the following properties:

Returns#

The promise resolves to an object with the following properties:

  • plainText - Contains the recognized plain text if chosen.
  • pdfFileUri - File URI of the composed PDF file ('file:///...') if chosen.
  • jsonData - Structured OCR JSON result as OCR pages, words, lines, and paragraphs.

OCR Output Format Values#

The following output formats can be specified for OCR result:

  • PLAIN_TEXT - Returns the recognized text as plain text only.
  • PDF_FILE - Creates a composed PDF file containing selectable and searchable text.
  • RESULT_JSON - Returns the OCR result as a JSON file.
  • FULL_OCR_RESULT - Full result: composed PDF file and recognized plain text.

Example of an OCR result as JSON:

{   "pages":[      {         "text":"Ut enim ad minim veniam, quis nostrud exercitation\nullamco laboris nisi ut aliquip ex ea commodo\nconsequat\n",         "words":[            {               "boundingBox":{                  "y":0.46182008368200839,                  "x":0.011823899371069183,                  "width":0.040000000000000001,                  "height":0.070606694560669453               },               "text":"Ut",               "confidence":96.546516418457031            },            {               "boundingBox":{                  "y":0.46443514644351463,                  "x":0.064402515723270437,                  "width":0.091320754716981131,                  "height":0.06903765690376569               },               "text":"enim",               "confidence":95.442947387695312            },            ...            {               "boundingBox":{                  "y":0.68462343096234313,                  "x":0.010817610062893081,                  "width":0.22213836477987423,                  "height":0.13702928870292888               },               "text":"consequat",               "confidence":23.432151794433594            }         ],         "lines":[            {               "boundingBox":{                  "y":0.41684100418410042,                  "x":0.011823899371069183,                  "width":0.98037735849056606,                  "height":0.14225941422594143               },               "text":"Ut enim ad minim veniam, quis nostrud exercitation\n",               "confidence":95.124320983886719            },            {               "boundingBox":{                  "y":0.57112970711297073,                  "x":0.011572327044025157,                  "width":0.86792452830188682,                  "height":0.1192468619246862               },               "text":"ullamco laboris nisi ut aliquip ex ea commodo\n",               "confidence":95.142372131347656            },            {               "boundingBox":{                  "y":0.68462343096234313,                  "x":0.010817610062893081,                  "width":0.22213836477987423,                  "height":0.13702928870292888               },               "text":"consequat\n",               "confidence":23.432151794433594            }         ],         "paragraphs":[            {               "boundingBox":{                  "y":0.41684100418410042,                  "x":0.011320754716981131,                  "width":0.98088050314465414,                  "height":0.34884937238493724               },               "text":"Ut enim ad minim veniam, quis nostrud exercitation\nullamco laboris nisi ut aliquip ex ea commodo\nconsequat\n",               "confidence":90.915626525878906            }         ]      }      ...   ]}

ScanbotSDK.getOCRConfigs(): Promise#

Use this function to get Scanbot SDK OCR properties of the current App installation.

Returns#

Returns an object with the following properties:

  • languageDataPath - Contains absolute file URI of the directory where to place the OCR training data files. You have to copy the corresponding *.traineddata files into this directory. The directory is a part of your App. If you uninstall the app, this directory will also be removed.
  • installedLanguages - Returns an array of current installed OCR languages (e.g. ["en", "fr"]). The Scanbot SDK uses the languageDataPath directory to determine installed OCR languages.

Cleanup#

ScanbotSDK.cleanup(): Promise#

By calling ths function all temporary output files generated by the Scanbot SDK module will be deleted.

File Handling & Storage Concept#

The Scanbot SDK module works with file URIs. That means all input and output files (images, PDFs, etc) are identified by a file URI. Please note that a file URI is not just a file path : "file:///some/file/path/.." vs. "/some/file/path/.."

Examples of valid file URIs:

  • On Android: file:///storage/emulated/0/Android/data/my.awesome.app/cache/sbsdk-temp/ce8de3c4-3c96-4ce1-b285-483d01e1dc9a.jpg

  • On iOS: file:///var/mobile/Containers/Data/Application/D2BF9FB2-1024-4418-99B2-3709AB2C171E/Documents/sbsdk-temp/05719BF8-63DB-4C8A-9A57-25B233AED33C.jpg

All output files generated by the Scanbot SDK module are temporary files. We recommend copying, moving or deleting the files you get from callbacks to an appropriate storage place.

There is no automatic file clean mechanism in the module, because only your App can decide when the perfect time is to remove a file.

To avoid storage space issues caused by temporary files please implement a suitable hook for the cleanup function in your App.

Page Image Source#

  • UNKNOWN - Used by default. If the source is not defined. For example, an image was imported
  • MANUAL_SNAP - If the source image was captured manually. For example, when the user pressed the Snap button
  • AUTO_SNAP - If the source image was captured automatically. For example, by auto snapping functions
  • CAMERA_FRAME - If the source image was taken from the camera frame

Detection Result Values#

  • OK - Document detection was successful. The detected contour looks like a valid document.
  • OK_BUT_BAD_ANGLES - Document was detected, but the perspective is not perfect.
  • OK_BUT_BAD_ASPECT_RATIO - Document was detected, but it has a wrong rotation relative to the camera sensor.
  • OK_BUT_TOO_SMALL - Document was detected, but it does not fill the desired area in the image rect.
  • ERROR_TOO_DARK - Document was not found, most likely due to bad lighting conditions.
  • ERROR_TOO_NOISY - Document was not found, most likely because there is too much background noise (maybe too many other objects on the table, or background texture is not monotonic).
  • ERROR_NOTHING_DETECTED - No document was found.

Barcode Format Values#

  • AZTEC - Identifies a AZTEC barcode
  • CODABAR - Identifies a CODABAR barcode
  • CODE_39 - Identifies a CODE_39 barcode
  • CODE_93 - Identifies a CODE_93 barcode
  • CODE_128 - Identifies a CODE_128 barcode
  • DATA_MATRIX - Identifies a DATA_MATRIX barcode
  • EAN_8 - Identifies a EAN_8 barcode
  • EAN_13 - Identifies a EAN_13 barcode
  • ITF - Identifies a ITF barcode
  • PDF_417 - Identifies a PDF_417 barcode
  • QR_CODE - Identifies a QR_CODE barcode
  • RSS_14 - Identifies a RSS_14 barcode
  • RSS_EXPANDED - Identifies a RSS_EXPANDED barcode
  • UPC_A - Identifies a UPC_A barcode
  • UPC_E - Identifies a UPC_E barcode
  • UNKNOWN - Identifies a barcode type that has not been recognized or is not available

Barcode Document Format Values#

  • AAMVA - Identifies an AAMVA Driver License
  • BOARDING_PASS - Identifies a Boarding Pass
  • DE_MEDICAL_PLAN - Identifies a German Medical Plan Code
  • DISABILITY_CERTIFICATE - Identifies a Disability Certificate Code
  • ID_CARD_PDF_417 - Identifies a PDF417 code (eg. ID card, passport, driver license)
  • SEPA - Identifies a SEPA QR Code
  • SWISS_QR - Identifies a Swiss QR Code
  • VCARD - Identifier a VCARD QR Code

ID Card Document Type Values#

  • DeIdBack - Identifies the back of a german ID Card
  • DeIdFront - Identifies the front of a german ID Card
  • DePassport - Identifies the german passport

Image Filter values#

Supported image filters:

  • COLOR_ENHANCED - Optimizes colors, contrast and brightness.
  • GRAYSCALE - Grayscale filter.
  • BINARIZED - Standard binarization filter with contrast optimization. Creates an 8-bit grayscale image with mostly black or white pixels.
  • COLOR_DOCUMENT - MagicColor filter. Fixes white balance and cleans up the background.
  • PURE_BINARIZED - A filter for binarizing an image. Creates an image with pixel values set to either pure black or pure white.
  • BACKGROUND_CLEAN - Cleans up the background and tries to preserve photos within the image.
  • BLACK_AND_WHITE - Black and white filter with background cleaning. Creates an 8-bit grayscale image with mostly black or white pixels.
  • OTSU_BINARIZATION - A filter for black and white conversion using OTSU binarization.
  • DEEP_BINARIZATION - A filter for black and white conversion primary used for low-contrast documents.
  • EDGE_HIGHLIGHT - A filter that enhances edges in low-contrast documents.
  • LOW_LIGHT_BINARIZATION - Binarization filter primarily intended for use on low-contrast documents with heavy shadows.
  • LOW_LIGHT_BINARIZATION_2 - Binarization filter primarily intended for use on low-contrast documents with heavy shadows.

Page Size values#

  • PDFPageSize.A4: The page has the aspect ratio of the image, but is fitted into A4 size. Whether portrait or landscape depends on the image's aspect ratio.
  • PDFPageSize.FIXED_A4: The page has A4 size. The image is fitted and centered within the page. Whether portrait or landscape depends on the image's aspect ratio.
  • PDFPageSize.US_LETTER: The page has the aspect ratio of the image, but is fitted into US letter size. Whether portrait or landscape depends on the image's aspect ratio.
  • PDFPageSize.FIXED_US_LETTER: The page has US letter size. The image is fitted and centered within the page. Whether portrait or landscape depends on the image's aspect ratio.
  • PDFPageSize.AUTO: For each page the best matching format (A4 or US letter) is used. Whether portrait or landscape depends on the image's aspect ratio.
  • PDFPageSize.AUTO_LOCALE: Each page of the result PDF will be of US letter or A4 size depending on the current locale. Whether portrait or landscape depends on the image's aspect ratio.
  • PDFPageSize.FROM_IMAGE: Each page is as large as its image at 72 dpi.

Polygon#

The Scanbot SDK polygon is a list with 4 float points (one for each corner). Each point has coordinates in range [0..1], representing position relative to image size. For instance, if a point has the coordinates (0.5, 0.5), it means that it is located exactly in the center of the image.

Example code of a detected polygon as JSON result:

"polygon": [    {"y":0.046, "x":0.13066667},    {"y":0.035, "x":0.91066664},    {"y":0.92, "x":0.9346667},    {"y":0.916, "x":0.10666667}]

Native Components#

You can use native components to embed our Barcode Scanning functionalities directly into your React layouts, allowing you to customize the user interface and experience in great detail and precision.

Note: Native Components are bundled with react-native-scanbot-sdk starting from v4.10.0

Barcode Camera View#

The Barcode Camera View component (ScanbotBarcodeCameraView) exposes a configurable camera view that allows you to detect barcodes in real time.

Usage#

import {ScanbotBarcodeCameraView} from 'react-native-scanbot-sdk';

You can then include it in your layout as you would normally do with other React components:

render() {  return (    <>      <SafeAreaView>        <ScanbotBarcodeCameraView style={this.styles.cameraView}/>      </SafeAreaView>    </>  );}

Detecting Barcodes#

You can use the onBarcodeScannerResult property to handle the detection results.

render() {  return (    <>      <SafeAreaView>        <ScanbotBarcodeCameraView           style={{this.styles.cameraView}}          onBarcodeScannerResult={(result: ScanbotBarcodeCameraViewResult) => {              console.log(result);          }}          />      </SafeAreaView>    </>  );}

Result Object#

  • status -> OK or CANCELED
  • barcodes -> the array of barcodes that have been detected
    • text -> the barcode text
    • type -> the barcode type

Configuration#

You can customise the UI and Behavior of the Barcode Camera View by using the component configuration property. Every property is optional and it falls back to its default value when not specified.

  /**   * The finder view is a rectangular overlay view that clips the camera view,   * so that the detection will focus just a specific area. You can specify   * the size and positioning, as well as other UI properties.   * Set this property to `true` if you want to use the Finder View, `false` otherwise (default: false)   */  shouldUseFinderView?: boolean;  /**   * The finder view rectangular overlay border width   */  finderLineWidth?: number;  /**   * The finder view rectangular overlay border color   */  finderLineColor?: string;  /**   * The overlay background color, around the finder view rectangle   */  finderBackgroundColor?: string;  /**   * The overlay background color opacity, around the finder view rectangle   */  finderBackgroundOpacity?: number;  /**   * The finder view rectangle aspect ratio   */  finderAspectRatio?: FinderAspectRatio;  /**   * The finder view minimum padding from the bounds of the screen   */  finderMinimumPadding?: number;  /**   * How many pixel units the finder view should be moved vertically;   *    * Positive values -> (UP); Negative values -> (DOWN)   */  finderVerticalOffset?: number;  /**  * Whether flash is toggled on or off.  */  flashEnabled?: boolean;  /**   * List of accepted Barcode Formats; any formats that are not included in this   * list will not be detected by the `BarcodeCameraView`. By default, the list   * includes all supported barcode types.   */  barcodeFormats?: BarcodeFormat[];  /**   * List of accepted Document Formats; any document formats that are not included   * in this list will be ignored by the `BarcodeCameraView`. By default, the list   * includes all supported document types.   */  acceptedDocumentFormats?: BarcodeDocumentFormat[];  /**   * The checksum algorithm for MSI Plessey barcodes.   * The default value is `Mod10'   */  msiPlesseyChecksumAlgorithm?: MSIPlesseyChecksumAlgorithm;  /**   * The engine mode of the barcode recognizer. Defaults to NEXT_GEN.   * To use legacy recognizer, please specify LEGACY   */  engineMode?: EngineMode;  /**   * The relative initial zoom level of the camera in the range [0,1], where 0 is zoomed out and 1 is zoomed in.   * The default value is 0.   */  cameraZoomFactor?: number;  /**   * When set to `true`, the scanner assumes that the barcode can be a GS1 barcode.   * Turn it off, if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).   * The default value is `true`.   * NOTE: Currently works for CODE128 barcodes only.   */  gs1DecodingEnabled?: boolean;  /**   * Optional minimum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  minimumTextLength?: number;  /**   * Optional maximum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF barcodes only.   */  maximumTextLength?: number;

Example

<ScanbotBarcodeCameraView    configuration={{    shouldUseFinderView: true,    finderAspectRatio: {      width: 2,      height: 1    },    finderLineWidth: 2.0,    finderLineColor: '#ffffff',    finderBackgroundColor: '#000000',    finderBackgroundOpacity: 0.66,    finderMinimumPadding: 16,    finderVerticalOffset: -300,    barcodeFormats: ["CODE_128", "EAN_13"]  }}    onBarcodeScannerResult={(result: ScanbotBarcodeCameraViewResult) => {    console.log(result);  }}
  style={this.styles.cameraView} />

Building Production Apps#

iOS#

The native Scanbot SDK iOS Framework (ScanbotSDK.framework) is installed as a CocoaPods dependency ScanbotSDK. It contains the architectures arm64 and x86_64. You can thus run it on most iOS devices as well as on simulators during the development phase. To be able to submit a production build to App Store Connect (App Store / TestFlight) the architecture x86_64 must be removed (striped out) from the Scanbot SDK Framework. This architecture is only for simulators and is not allowed to be submitted to App Store Connect. In a CocoaPods powered project this is typically done by CocoaPods, so no manual action is required here.

However, if you get this error while uploading your app, the following manual configuration steps must be done to fix it:

ERROR ITMS-90087: "Unsupported Architectures. The executable for [...].app/Frameworks/ScanbotSDK.framework contains unsupported architectures '[x86_64]'."

We provide a script strip-SBSDK-Framework.sh as a part of the ScanbotSDK.framework and it can be easily integrated in the build process. This script removes the unnecessary architectures from the frameworks binary, code signs the framework and adds the crash symbols (dSYM) file to your app's archive. To add this script in your build process, you will need to open the Xcode workspace .xcworkspace and apply a few changes there:

  1. Go to TARGETS settings and open the tab Build Phases. Add a new Run Script Phase via "+" button.
  2. Adjust this Run Script Phase with the following script data:

Script code:

bash "${PODS_ROOT}/ScanbotSDK/ScanbotSDK.framework/strip-SBSDK-Framework.sh"

Script Input File:

${PODS_ROOT}/ScanbotSDK/ScanbotSDK.framework.dSYM

alt text

Android#

The Scanbot SDK uses native libraries under the hood and supports the following ABIs: armeabi-v7a, arm64-v8a, x86 and x86_64.

By default the native libraries of all these architectures will be included in the app package (APK), which will result in a big APK file. Please consider removing support for x86 and x86_64 architectures. In most cases both “x86” architectures can be removed for the release (production) build, since they are only used on emulators and on some rare devices with the Intel Atom architecture.

To exclude certain ABIs from the APK, use the abiFilters property in the Android Gradle settings of your project.

Please check and adjust the abiFilters configuration in your build.gradle file accordingly:

android {  ...  defaultConfig {    ...    ndk {      // a typical production configuration:      abiFilters "armeabi-v7a", "arm64-v8a"    }  }}

💡 However, if you need to support all architectures and to optimize the APK size, we highly recommend checking out the Android App Bundle approach. It allows you to create and distribute dedicated and smaller APKs via the PlayStore (basically it is similar to the iOS App Store approach).