Skip to main content

Features | Flutter Document Scanner

Storage#

By default the native Scanbot SDKs as well as the Plugin itself use the internal and secure storage locations for all produced files (JPG, PNG, PDF, TIFF, etc).

  • 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 Plugin. The initializeSdk method can take an optional parameter storageBaseDirectory to set a custom storage location.

Directory storageDirectory;if (Platform.isAndroid) {  storageDirectory = await getExternalStorageDirectory();}if (Platform.isIOS) {  storageDirectory = await getApplicationDocumentsDirectory();}
// Please note: getExternalStorageDirectory() and getApplicationDocumentsDirectory()// are provided via 3rd-party plugins like "path_provider".
var config = ScanbotSdkConfig(  storageBaseDirectory: "${directory.path}/my_custom_storage",  ...);await ScanbotSdk.initScanbotSdk(config);

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 Plugin will try to create it. To work with the file system we recommend the Flutter Plugin path_provider

For the full demo code please checkout our example app on GitHub.

⚠️ 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 Encryption#

The Scanbot SDK provides the ability to store the generated image files (JPG, PNG), PDF, and TIFF 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:

  • password: A secure password or passphrase to derive the AES key for encryption/decryption.
  • mode: Encryption mode, AES128 or AES256 (default and recommended).
 var config = ScanbotSdkConfig(          encryptionParameters : EncryptionParameters(password: "password",                                                      mode: FileEncryptionMode.AES256)); await ScanbotSdk.initScanbotSdk(config);

By activating the storage encryption the native Scanbot SDKs will use the built-in 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 device storage.

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 them again.

Also see Handle Encrypted Images.

Storage Cleanup#

There is no automatic file clean mechanism in this Plugin. Your app should decide when the perfect time is to remove the files produced by this Plugin (images, PDFs, etc).

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

  • deletePage method to delete a certain Page object with all its files.
  • cleanupStorage method to remove all generated files by this Plugin (scanned and imported images, exported files like PDF, TIFF, etc).

Ready-To-Use UI Screen Components#

The Scanbot SDK provides Ready-To-Use UI (RTU UI) screen components, like Document Scanner UI, Cropping UI, Barcode Scanner UI, etc.

Page Model#

All SDK components (UI and non-UI) which generate or modify scanned documents use the notion of a Page as a data model.

A Page object represents a scanned document page and has the following fields:

Page (  String pageId;  List<PolygonPoint>? polygon;  DetectionStatus? detectionStatus;  ImageFilterType? filter;  Size? documentImageSizeLimit;  Uri? originalImageFileUri;  Uri? documentImageFileUri;  Uri? originalPreviewImageFileUri;  Uri? documentPreviewImageFileUri;)

The fields are:

  • pageId - a unique, random string (UUID) 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.
  • detectionStatus - the detection status of the document detection operation that produced the page (either the document scanner or detectDocument()).
  • filter - the image filter type which was applied on the document image of this page.
  • documentImageSizeLimit - limits the maximum resolution (width, height) of the document image. If null is passed, this property is effectively ignored. If specified, width and height must be > 0.
  • 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, rotatePageClockwise() overwrites the page's image files with their rotated versions.

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}. This 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 their absolute file paths have changed.

To obtain the new absolute paths, the API method refreshImageUris(pages) has been introduced in the plugin version 2.1.0. Please use this method to refresh all image file URIs for affected pages:

List<Page> loadedPages = ... // load page objects from DBvar refreshedPages = await ScanbotSdk.refreshImageUris(loadedPages);

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

Document Scanner#

ScanbotSdkUi.startDocumentScanner(config)#

Starts the Document Scanner for guided, automatic document scanning.

alt text

var config = DocumentScannerConfiguration(  multiPageEnabled: true,  bottomBarBackgroundColor: Colors.blueAccent,  pageCounterButtonTitle: "%d Page(s)",  ...);var result = await ScanbotSdkUi.startDocumentScanner(config);
if (result.operationResult == OperationResult.SUCCESS) {  print('Document Scanner Result: ' + jsonEncode(result));  // see the array result.pages[] of scanned pages}
  • result.operationResult -
    • SUCCESS if some pages were snapped
    • ERROR if an error occurred
    • CANCELED if the user canceled the request
  • result.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 result.status is SUCCESS, this array contains one object.
DocumentScannerConfiguration#

All UI configuration options are optional.

   Color? topBarBackgroundColor;
   /// The color of all inactive toggle buttons in the toolbar.   Color? topBarButtonsInactiveColor;
   /// The color of all active toggle buttons in the toolbar.   Color? topBarButtonsActiveColor;
   /// The color of the camera background (relevant only when the camera preview mode is CameraPreviewMode.FIT_IN).   Color? cameraBackgroundColor;
   /// The background color of the user guidance hints.   Color? userGuidanceBackgroundColor;
   /// The text color of the user guidance hints.   Color? userGuidanceTextColor;
   /// The background color of the bottom shutter-bar.   Color? bottomBarBackgroundColor;
   /// The color of the title of all buttons in the bottom shutter-bar (Cancel button, etc.),   /// as well as the camera permission prompt button.   Color? bottomBarButtonsColor;
   /// The foreground color of the shutter button in auto-snapping mode.   Color? shutterButtonAutoInnerColor;
   /// The background color of the shutter button in auto-snapping mode.   Color? shutterButtonAutoOuterColor;
   /// The background color of the shutter button in manual mode.   Color? shutterButtonManualOuterColor;
   /// The foreground color of the shutter button in manual mode.   Color? shutterButtonManualInnerColor;
   /// The color of the detected document outline when the document's angle, size or aspect ratio   /// is not yet acceptable   /// (All detection statuses in net.doo.snap.lib.detector.DetectionResult that have the OK_BUT_XXX prefix).   Color? polygonColor;
   /// The color of the detected document outline when we are ready to snap net.doo.snap.lib.detector.DetectionResult.OK.   Color? polygonColorOK;
   /// The background color of the detected document outline when the document's angle, size or aspect ratio   /// is not yet acceptable   /// (All net.doo.snap.lib.detector.DetectionResult with OK_BUT_XXX).   Color? polygonBackgroundColor;
   /// The background color of the detected document outline when we are ready to snap net.doo.snap.lib.detector.DetectionResult.OK.   Color? polygonBackgroundColorOK;
   Color? shutterButtonIndicatorColor;
   /// Controls whether the multi-page toggle button is hidden or not.   bool? multiPageButtonHidden;
   /// Controls whether the flash toggle button is hidden or not.   bool? flashButtonHidden;
   /// 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.   bool? shutterButtonHidden;
   /// Controls whether the auto-snapping toggle button is hidden or not.   bool? autoSnappingButtonHidden;
   bool? cancelButtonHidden;
   /// Width of the detected document outline.   int? polygonLineWidth;
   /// Max number of pages available to scan;   int? maxNumberOfPages;
   /// The minimum score in percent (0 - 100) of the perspective distortion to accept a detected document.   /// Default is 75.0.   double? acceptedAngleScore;
   /// The minimum document width or height in percent (0 - 100) of the screen size to accept a detected document.   /// Default is 80.0.   double? acceptedSizeScore;
   /// 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 capturing by 3 seconds.   /// The default value is 0.66 (2 seconds)   double? autoSnappingSensitivity;
   /// Limits the maximum size of the document image. If width or height are zero, this property is effectively ignored.   prefix0.Size? documentImageSizeLimit;
   /// Preview mode of the camera: Fit-In or Fill-In.   /// Optional, default is Fit-In.   CameraPreviewMode? cameraPreviewMode;
   /// Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.   /// By default the camera orientation is not locked.   CameraOrientationMode? orientationLockMode;
   /// Sets whether to ignore the net.doo.snap.lib.detector.DetectionResult.OK_BUT_BAD_ASPECT_RATIO detection status.   /// By default BadAspectRatio is not ignored.   bool? ignoreBadAspectRatio;
   /// Controls whether the flash should be initially enabled.   /// The default value is FALSE.   bool? flashEnabled;
   /// 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.   bool? multiPageEnabled;
   /// 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.   bool? autoSnappingEnabled;
   String? multiPageButtonTitle;
   /// Title of the cancel button.   String? cancelButtonTitle;
   /// Title of the flash toggle button.   String? flashButtonTitle;
   /// Title of the auto-snapping toggle button.   String? autoSnappingButtonTitle;
   /// 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.   String? pageCounterButtonTitle;
   /// The text being displayed on the user-guidance label   /// when the scanner's energy saver is activated.   /// iOS only.   String? textHintEnergySavingActive;
   /// Text hint that will be shown when the current detection status   /// is net.doo.snap.lib.detector.DetectionResult.ERROR_NOTHING_DETECTED   String? textHintNothingDetected;
   /// Text hint that will be shown when the current detection status   /// is net.doo.snap.lib.detector.DetectionResult.ERROR_TOO_NOISY   String? textHintTooNoisy;
   /// Text hint that will be shown when the current detection status   /// is net.doo.snap.lib.detector.DetectionResult.ERROR_TOO_DARK   String? textHintTooDark;
   /// Text hint that will be shown when the current detection status   /// is net.doo.snap.lib.detector.DetectionResult.OK_BUT_BAD_ANGLES   String? textHintBadAngles;
   /// Text hint that will be shown when the current detection status   /// is net.doo.snap.lib.detector.DetectionResult.OK_BUT_BAD_ASPECT_RATIO   String? textHintBadAspectRatio;
   /// Text hint that will be shown when the current detection status   /// is net.doo.snap.lib.detector.DetectionResult.OK_BUT_TOO_SMALL   String? textHintTooSmall;
   /// The background color of the top toolbar.   String? textHintOffCenter;
   /// Text hint that will be shown when the current detection   /// status is net.doo.snap.lib.detector.DetectionResult.OK   String? textHintOK;
   /// String being displayed on the label describing that app is in split mode   /// and needs to go fullscreen to work with camera. (iOS-only)   String? cameraUnavailableExplanationText;
   /// Title of the button that opens the screen where the user can allow   /// the usage of the camera by the app.   String? enableCameraButtonTitle;
   /// 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.   String? enableCameraExplanationText;

Cropping UI#

ScanbotSdkUi.startCroppingScreen(page,config)#

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

var config = CroppingScreenConfiguration(  bottomBarBackgroundColor: Colors.redAccent,  cancelButtonTitle: 'Cancel',  doneButtonTitle: 'Save',  ...);var result = await ScanbotSdkUi.startCroppingScreen(page, config);// result.page ...
  • result.operationResult
    • SUCCESS if the user applied changes to the image (tapped on the "done" button)
    • ERROR if an error occurred
    • CANCELED if the user has canceled the operation (tapped on the "cancel" button)
  • result.page - the cropped page.
CroppingScreenConfiguration#

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

All UI configuration settings are optional.

  /// Background color of the main screen.  Color? backgroundColor;
  /// Background color of the bottom toolbar.  Color? bottomBarBackgroundColor;
  /// The color of the titles of all buttons in the bottom toolbar (Rotate button).  Color? bottomBarButtonsColor;
  /// Title of the cancel button.  String? cancelButtonTitle;
  /// Title of the Done button.  String? doneButtonTitle;
  /// Default color of the cropping outline.  Color? polygonColor;
  /// Outline color of magnetically snapped edges.  Color? polygonColorMagnetic;
  /// Width of the cropping outline.  int? polygonLineWidth;
  /// Title of the Rotate button.  String? rotateButtonTitle;
  /// Background color of the top toolbar.  Color? topBarBackgroundColor;
  /// The color of the titles of all buttons in the top toolbar (Cancel and Done buttons).  Color? topBarButtonsColor;
  /// Title in the top bar (iOS only).  String? topBarTitle;
  /// The color of the title in the top bar (iOS only).  Color? titleColor;
  /// Title of the Detect button.  String? detectButtonTitle;
  /// Title of the Reset button.  String? resetButtonTitle;
  /// Controls whether the Rotate button is hidden or not.  bool? rotateButtonHidden;
  /// Controls whether the Detect/Reset button is hidden or not.  bool? detectResetButtonHidden;
  /// UI orientation lock mode: PORTRAIT, LANDSCAPE, etc.  /// By default the UI is not locked.  CameraOrientationMode? orientationLockMode;

Barcode and QR Code Scanning UI#

ScanbotSdkUi.startBarcodeScanner(config)#

Opens a Scanning UI for barcodes and QR codes.

alt

var config = BarcodeScannerConfiguration(  barcodeFormats: [BarcodeFormat.CODE_128, BarcodeFormat.DATA_MATRIX],  topBarBackgroundColor: Colors.blueAccent,  finderTextHint: "Please align a barcode in the frame to scan it.",  cancelButtonTitle: "Cancel",  flashEnabled: true,  ...);var result = await ScanbotSdkUi.startBarcodeScanner(config);// result.barcodeItems[n].barcodeFormat// result.barcodeItems[n].text// result.barcodeItems[n].formattedResult
  • result.operationResult:
    • SUCCESS if a barcode was detected
    • ERROR if an error occurred
    • CANCELED if the user has canceled the operation (tapped on the "cancel" button)
  • barcodeItems[n] - a list of detected barcodes/QR codes as BarcodeItems:
    • item.barcodeFormat - Format of detected barcode/QR code (e.g. "CODE_128", "EAN_13", "QR_CODE", etc).
    • item.text - Raw text value of detected barcode/QR code.
    • item.rawBytes - Raw bytes of detected barcode/QR code.
    • item.formattedResult - Optional, formatted/parsed result. See implementations of BarcodeFormattedResult.
BarcodeScannerConfiguration#

All settings are optional.

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

  • Further configs:

  /// Background color of the top toolbar.  Color? topBarBackgroundColor;
  /// The color of the titles of all buttons in the top toolbar.  Color? topBarButtonsColor;
  /// Background color outside the finder window.  Color? cameraOverlayColor;
  /// The color of the finder window's outline.  Color? finderLineColor;
  /// The color of the text hint under the finder window.  Color? finderTextHintColor;
  bool? cancelButtonHidden;
  /// Title of the cancel button.  String? cancelButtonTitle;
  /// Title of the button that opens the screen where the user can allow  /// the usage of the camera by the app.  String? enableCameraButtonTitle;
  /// 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.  String? enableCameraExplanationText;
  /// Text hint shown under the finder window.  String? finderTextHint;
  /// The color of the titles of all inactive buttons in the top toolbar.  Color? topBarButtonsInactiveColor;
  /// Cancel scanning and close view on timeout.  int? autoCancelTimeout;
  /// Aspect ratio of finder view.  FinderAspectRatio? finderAspectRatio;
  /// Thickness of the finder window's outline.  int? finderLineWidth;
  /// Controls whether to play a beep sound after a successful detection.  /// Default value is TRUE.  bool? successBeepEnabled;
  /// Controls whether the flash should be initially enabled.  /// The default value is FALSE.  bool? flashEnabled;
  /// Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.  /// By default the camera orientation is not locked.  CameraOrientationMode? orientationLockMode;
  /// Barcode formats which need to be recognized.  List<BarcodeFormat>? barcodeFormats;
  /// Additional parameters for tweaking the detection of barcodes.  BarcodeAdditionalParameters? additionalParameters;
  /// Param that handle whether we need to save image from camera preview or make a snapshot while snapping barcode  /// image uri will be returned in [BarcodeScanningResult.snappedImage] property  BarcodeImageGenerationType barcodeImageGenerationType
  /// Type of engine to be used in barcode scanner  EngineMode engineMode;
  ///Set current zoom by a linear zoom value ranging from 0f to 1.0f. Optical Zoom Level 0f represents the minimum zoom while Optical Zoom Level 1.0f represents the maximum zoom.  ///Default value is 0f.  double? cameraZoomFactor;

Barcode additional params details:

  /// With this option, the scanner assumes that the barcode can be a GS1 barcode, and modifies the behavior as needed.  /// You can set it to FALSE, if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).  /// The default is TRUE.  bool? enableGS1Decoding;
  /// Minimum required text length of the detected barcode.  /// The default is 0.  /// NOTE: Currently works for ITF barcodes only!  int? minimumTextLength;
  /// Maximum text length of the detected barcode. Setting to zero removes the limit.  /// The default is 0.  /// NOTE: Currently works for ITF barcodes only!  int? maximumTextLength;
  /// Minimum required quiet zone on the barcode. Measured in modules (the size of minimal bar on the barcode).  /// The default is 10.  /// NOTE: Currently works for ITF barcodes only!  int? minimum1DBarcodesQuietZone;

ScanbotSdk.startBatchBarcodeScanner(config)#

Opens a scanning UI for scanning and collecting multiple barcodes.

alt

var config = BatchBarcodeScannerConfiguration(  barcodeFormats: [BarcodeFormat.CODE_128, BarcodeFormat.DATA_MATRIX],  topBarBackgroundColor: Colors.blueAccent,  finderTextHint: "Please align a barcode in the frame to scan it.",  flashEnabled: true,  ...);var result = await ScanbotSdk.startBatchBarcodeScanner(config);// result.barcodeItems[n] ...

Result:

  • result.operationResult - SUCCESS if a barcode was detected, ERROR if the user has canceled the operation (tapped on the "cancel" button).
  • result.barcodeItems - List of recognized barcodes as items of BarcodeItem type.

BarcodeItem structure:

  • barcodeFormat - Format of detected barcode/QR code (e.g. "CODE_128", "EAN_13", "QR_CODE", etc).
  • text - Raw text value of detected barcode/QR code.
  • rawBytes - Raw bytes of detected barcode/QR code.
  • formattedResult - Optional, formatted/parsed result. See implementations of BarcodeFormattedResult.
BatchBarcodeScannerConfiguration#

Use this configuration class to customize the UI and the behavior of the Batch Barcodes Scanner UI. All config properties are optional.

BatchBarcodeScannerConfiguration:

  /// Change data representation for scanned list items  BarcodeDataFormatter? barcodeFormatter;
  /// The background color of the top toolbar.  Color? topBarBackgroundColor;
  /// The color of the titles of all buttons in the top toolbar.  Color? topBarButtonsColor;
  /// The color of the titles of all inactive buttons in the top toolbar.  Color? topBarButtonsInactiveColor;
  /// The color of barcodes count text  Color? barcodesCountTextColor;
  /// The color of barcodes details action  Color? detailsActionColor;
  /// The color of barcodes details background  Color? detailsBackgroundColor;
  /// The color of barcodes details background  Color? detailsPrimaryColor;
  /// The background color outside the finder window.  Color? cameraOverlayColor;
  /// The color of the finder window's outline.  Color? finderLineColor;
  /// The color of the text hint under the finder window.  Color? finderTextHintColor;
  /// To hide cancel button or not.  bool? cancelButtonHidden;
  /// Title of the cancel button.  String? cancelButtonTitle;
  /// Title of the button that opens the screen where the user can allow  /// the usage of the camera by the app.  String? enableCameraButtonTitle;
  /// 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.  String? enableCameraExplanationText;
  /// Text hint shown under the finder window.  String? finderTextHint;
  /// Text of submit button.  String? submitButtonTitle;
  /// Text of clear button.  String? clearButtonTitle;
  /// Text of count text.  String? barcodesCountText;
  /// Text of fetch state text.  String? fetchingStateText;
  /// Text when there are no scanned barcodes yet.  String? noBarcodesTitle;
  /// Aspect ratio of finder view.  FinderAspectRatio? finderAspectRatio;
  /// Thickness of the finder window's outline.  int? finderLineWidth;
  /// Controls whether to play a beep sound after a successful detection.  /// Default value is TRUE.  bool? successBeepEnabled;
  /// Controls whether the flash should be initially enabled.  /// The default value is FALSE.  bool? flashEnabled;
  /// Additional parameters for tweaking the detection of barcodes.  BarcodeAdditionalParameters? additionalParameters;
  /// Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.  /// By default the camera orientation is not locked.
  CameraOrientationMode? orientationLockMode;
  /// Barcode formats which need to be recognized.  List<BarcodeFormat>? barcodeFormats;
  /// Type of engine to be used in barcode scanner  EngineMode engineMode;

Barcode additional params details:

  /// With this option, the scanner assumes that the barcode can be a GS1 barcode, and modifies the behavior as needed.  /// You can set it to FALSE, if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).  /// The default is TRUE.  bool? enableGS1Decoding;
  /// Minimum required text length of the detected barcode.  /// The default is 0.  /// NOTE: Currently works for ITF barcodes only!  int? minimumTextLength;
  /// Maximum text length of the detected barcode. Setting to zero removes the limit.  /// The default is 0.  /// NOTE: Currently works for ITF barcodes only!  int? maximumTextLength;
  /// Minimum required quiet zone on the barcode. Measured in modules (the size of minimal bar on the barcode).  /// The default is 10.  /// NOTE: Currently works for ITF barcodes only!  int? minimum1DBarcodesQuietZone;

Machine Readable Zone Scanner#

ScanbotSdkUi.startMrzScanner(config)#

Opens a scanner to scan and extract MRZ data (Machine Readable Zones) on ID cards, passports, etc.

alt

var config = MrzScannerConfiguration(  topBarBackgroundColor: Colors.pink,  cancelButtonTitle: "Cancel",  ...);var result = await ScanbotSdkUi.startMrzScanner(config);// result.fields ...
  • result.operationResult
    • SUCCESS if MRZ data was detected
    • CANCELED if the user canceled the operation (tapped on the "cancel" button)
    • ERROR if an error occurred
  • result.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.caverageRecognitionConfidence - confidence in the accuracy of value
MrzScannerConfiguration#

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

  /// Background color of the top toolbar.  Color? topBarBackgroundColor;
  /// The color of the titles of all buttons in the top toolbar.  Color? topBarButtonsColor;
  /// Background color outside the finder window.  Color? cameraOverlayColor;
  /// The color of the finder window's outline.  Color? finderLineColor;
  /// The color of the text hint under the finder window.  Color? finderTextHintColor;
  /// The color of the bottom button in active state  Color? bottomButtonsActiveColor;
  /// The color of the bottom button in inactive state  Color? bottomButtonsInactiveColor;
  /// Title of the cancel button.  String? cancelButtonTitle;
  /// Title of the button that opens the screen where the user can allow  /// the usage of the camera by the app.  String? enableCameraButtonTitle;
  /// 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.  String? enableCameraExplanationText;
  /// Text hint shown under the finder window.  String? finderTextHint;
  /// Aspect ratio of finder view.  FinderAspectRatio? finderAspectRatio;
  /// Thickness of the finder window's outline.  int? finderLineWidth;
  /// Controls whether to play a beep sound after a successful detection.  /// Default value is TRUE.  bool? successBeepEnabled;
  /// Controls whether the flash should be initially enabled.  /// The default value is FALSE.  bool? flashEnabled;
  String? flashButtonTitle;
  /// Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.  /// By default the camera orientation is not locked.  CameraOrientationMode? orientationLockMode;
  bool? cancelButtonHidden;

European Health Insurance Card Scanner#

ScanbotSdkUi.startEhicScanner(config)#

Opens a scanner to scan and extract data from the back side of European Health Insurance Cards (EHIC).

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 plugin API method ScanbotSdkUi.startEhicScanner(config) to start the EHIC Scanner UI.

var config = HealthInsuranceScannerConfiguration(  topBarBackgroundColor: Colors.pink,  topBarButtonsColor: Colors.white70,  ...);var result = await ScanbotSdkUi.startEhicScanner(config);// result.fields ...
  • result.operationResult -

    • SUCCESS if EHIC data was detected
    • ERROR if an error occurred
    • CANCELED if the user canceled the operation (tapped on the "cancel" button)
  • result.fields - an array of recognized EHIC fields. Each field is an object with the following properties:

  • status - one of folowing values SUCCESS,FAILED_DETECTION,FAILED_VALIDATION.

HealthInsuranceScannerConfiguration#
  /// The background color of the top toolbar.  Color? topBarBackgroundColor;
  /// The color of the titles of all buttons in the top toolbar.  Color? topBarButtonsColor;
  /// The background color outside the finder window.  Color? cameraOverlayColor;
  /// The color of the finder window's outline.  Color? finderLineColor;
  /// The color of the bottom button in active state  Color? bottomButtonsActiveColor;
  /// The color of the bottom button in inactive state  Color? bottomButtonsInactiveColor;
  bool? cancelButtonHidden;
  /// Title of the cancel button.  String? cancelButtonTitle;
  String? detectionStatusFailedDetectionText;
  String? detectionStatusFailedValidationText;
  String? detectionStatusSuccessText;
  /// Title of the button that opens the screen where the user can allow  /// the usage of the camera by the app.  String? enableCameraButtonTitle;
  /// 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.  String? enableCameraExplanationText;
  /// Text hint shown under the finder window.  String? finderTextHint;
  String? flashButtonTitle;
  /// Thickness of the finder window's outline.  int? finderLineWidth;
  /// Controls whether the flash should be initially enabled.  /// The default value is FALSE.  bool? flashEnabled;
  /// Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.  /// By default the camera orientation is not locked.  CameraOrientationMode? orientationLockMode;

EU License Plate Scanner#

ScanbotSdkUi.startLicensePlateScanner(config)#

Opens scanner that extracts country code and the license plate number from the European car license plate.

alt

var config = LicensePlateScannerConfiguration(        topBarBackgroundColor: Colors.pink,        topBarButtonsColor: Colors.white70,        confirmationDialogAccentColor: Colors.green);var result = await ScanbotSdkUi.startLicensePlateScanner(config);
  • result.operationResult

    • SUCCESS if License Plate data was detected
    • CANCELED if the user canceled the operation (tapped on the "cancel" button)
    • ERROR if an error occurred
  • result.countryCode - country code of the license plate

  • result.licensePlate - number on the license plate

  • result.rawText - raw value detected on the license plate

  • result.confidence - confidence of the recognition

LicensePlateScannerConfiguration#

  /// The background color of the top toolbar.  Color? topBarBackgroundColor;
  /// The color of the inactive buttons on the toolbar.  Color? topBarButtonsInactiveColor;
  /// The color of the titles of all buttons in the top toolbar.  Color? topBarButtonsColor;
  /// The background color outside the finder window.  Color? cameraOverlayColor;
  /// The color of the finder window's outline.  Color? finderLineColor;
  /// The color of the text hint under the finder window.  Color? finderTextHintColor;
  /// The title of the cancel button.  String? cancelButtonTitle;
  /// The title of the dialog with scanned plate confirmation.  String? confirmationDialogTitle;
  /// Message of the dialog with scanned plate confirmation.  String? confirmationDialogMessage;
  /// Text on the retry scanning button of the dialog with scanned plate confirmation.  String? confirmationDialogRetryButtonTitle;
  /// Text on the confirm scanning button of the dialog with scanned plate confirmation.  String? confirmationDialogConfirmButtonTitle;
  /// The color of buttons of the dialog with scanned plate confirmation.  Color? confirmationDialogAccentColor;
  /// Whether the confirmation button should be filled with color, or should rather only be a text button  bool? confirmationDialogConfirmButtonFilled;
  /// If the confirmation button is filled, then this option selects the color of the text for this button  Color? confirmationDialogConfirmButtonFilledTextColor;
  /// The minimum number of sequentially recognized frames where the result is equal  int? minNumberOfRequiredFramesWithEqualRecognitionResult;
  /// Maximum number of accumulated frames to inspect before the actual result is returned  int? maximumNumberOfAccumulatedFrames;
  /// The title of the button that opens the screen where the user can allow  /// the usage of the camera by the app.  String? enableCameraButtonTitle;
  /// 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.  String? enableCameraExplanationText;
  /// The text hint shown under the finder window.  String? finderTextHint;
  /// Width of the finder frame border.  int? finderLineWidth;
  /// Controls whether the flash should be initially enabled.  /// The default value is FALSE.  bool? flashEnabled;
  /// Whether we need to show buttons text in caps mode or not  /// Android only  bool? useButtonsAllCaps;
  /// Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.  /// By default the camera orientation is not locked.  CameraOrientationMode? orientationLockMode;

NFC Passport Reader#

ScanbotSdkUi.startNfcPassportReader(config)#

Opens a passport reader that extracts passport data from nfc chip by using MRZ data from that passport.

alt

Notes for iOS:

  • Requires iOS 13.0+
  • Your app needs to add the "Near Field Communication Tag Reading" entitlement
  • Your apps info.plist needs to define the passport nfc application ID. To do so add the following entry: "com.apple.developer.nfc.readersession.iso7816.select-identifiers" and as the first element add the passport application ID "A0000002471001"

Example:

var config = NfcPassportReaderConfiguration(  topBarBackgroundColor: Colors.pink,  topBarButtonsColor: Colors.white70,  ...);var result = await ScanbotSdkUi.startNfcPassportReader(config);
  • result.operationResult -

    • SUCCESS if EHIC data was detected
    • ERROR if an error occurred
    • CANCELED if the user canceled the operation (tapped on the "cancel" button)
  • result.dataGroup1 - data group 1, that contains general information about the passport and its holder.

  • result.dataGroup2 - data group 2, that contains visual biometric data of the passports holder.

  • result.photoUri - URI with image from NFC chip.

NfcPassportReaderConfiguration#
   /// The background color of the top toolbar.    Color? topBarBackgroundColor;
    /// The color of the titles of all buttons in the top toolbar.    Color? topBarButtonsColor;
    /// The background color outside the finder window.    Color? cameraOverlayColor;
    /// The color of the finder window's outline.    Color? finderLineColor;
    /// The color of the text hint under the finder window.    Color? finderTextHintColor;
    /// Foreground color of the flash button when the flash is off.    Color? topBarButtonsInactiveColor;
    /// The color of the progress bar.    Color? progressBarColor;
    /// Thickness of the finder window's outline.    int? finderLineWidth;
    /// Whether the cancel button is hidden or not.    bool? cancelButtonHidden;
    /// Orientation lock mode of the camera: PORTRAIT or LANDSCAPE.    /// By default the camera orientation is not locked.    CameraOrientationMode? orientationLockMode;

    /// Title of the cancel button.    String? cancelButtonTitle;
    /// Title of the button that opens the screen where the user can allow    /// the usage of the camera by the app.    String? enableCameraButtonTitle;
    /// 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.    String? enableCameraExplanationText;
    /// Text hint shown under the finder window.    String? finderTextHint;
    /// String being displayed as a hint to hold device over the NFC chip.    String? holdOverTheChipTitle;
    /// A hint that notifies about downloading datagroups.    String? downloadingDataTitle;
    /// A title for the state when there is no NFC chip installed on the device, or it is not available.    String? noChipErrorTitle;
    /// A title for the error, when NFC reader failed to perform authentication.    String? authenticationErrorTitle;
    /// A title for the error, when NFC reader failed to download the data.    String? downloadErrorTitle;
    /// Android only. A title for the retry button.    String? retryButtonTitle;
    /// Android only. A title for the state when the NFC chip is disabled on the device    String? chipDisabledErrorTitle;
    /// Android only. A title for the screen of passport scanning.    String? scanPassportTitle;
    /// Controls whether to play a beep sound after a successful detection.    /// The default value is TRUE.    bool? successBeepEnabled;
    /// Controls whether the flash should be initially enabled.    /// The default value is FALSE.    bool? flashEnabled;
    /// Defines, if photo image should be stored in internal storage on disk.    /// If set to `FALSE`, the result `NfcPassportReaderResult` will not have `photoImageUri`.    /// The default value is `FALSE`.    bool? shouldSavePhotoImageInStorage;

Page Operations#

ScanbotSdk.createPage(originalImageFileUri, shouldDetectDocument)#

Creates a page object from an image. If the encryption parameters are set during the SDK initialization, then the page's images will be stored encrypted with given parameters.

Uri originalImageFileUri = ... // "file:///some/image.jpg"var page = await ScanbotSdk.createPage(originalImageFileUri, true);
Options:#
  • originalImageFileUri - the file URI of the original image to create a page and optionally run document detection on.
  • shouldDetectDocument - flag to specify whether the auto document detection should be performed and the (cropped) DOCUMENT image should be created.

ScanbotSdk.detectDocument(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.

var updatedPage = await ScanbotSdk.detectDocument(page);
Options:#
  • options.page - a valid page object with an original image to process.

ScanbotSdk.applyImageFilter(page, filter)#

Applies an image filter on the cropped DOCUMENT image of a page.

var updatedPage = await ScanbotSdk.applyImageFilter(page, ImageFilterType.LOW_LIGHT_BINARIZATION_2);
Options:#
  • page - a valid page object with a DOCUMENT image.
  • filter - the image filter to apply. The special value NONE will remove any previously applied filter from the document image.

ScanbotSdk.getFilteredDocumentPreviewUri(page, filter)#

Creates a preview image file of the DOCUMENT image by given image filter. Please note that this method does not modify the actual hi-res DOCUMENT image of the passed page object. Use the applyImageFilter(page, filter) method to finally apply an image filter on the hi-res DOCUMENT image of a page.

var previewImageFileUri = await ScanbotSdk.getFilteredDocumentPreviewUri(page, ImageFilterType.BINARIZED);// use previewImageFileUri to display a preview/thumbnail image
Options:#
  • page - the page for which to create a filtered document preview.
  • filter - the image filter to apply on the preview image. The special value NONE will remove any previously applied filter from the document image.

ScanbotSdk.rotatePageClockwise(page, rotationsCount)#

Rotates a page clockwise in increments of 90 degrees.

var updatedPage = await ScanbotSdk.rotatePageClockwise(page, 2);
Options:#
  • page - the page to rotate.
  • rotationsCount - the number of clockwise 90 degree rotations to apply.

ScanbotSdk.deletePage(page)#

Removes a page with all its files (original image, document image, thumbnails, filtered images, etc) from the internal file storage. This method does not remove any export files (PDF, TIFF) which were generated based on this page object.

await ScanbotSdk.deletePage(page);

Other features#

PDF Creation#

ScanbotSdk.createPdf(pages, options)#

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

List<Page> pages = ...var options = PdfRenderingOptions(PdfRenderSize.A4);Uri pdfFileUri = await ScanbotSdk.createPdf(pages, options);
Arguments:#
  • pages - a list of valid Page objects. Each page should have the cropped DOCUMENT image.
  • options - PdfRenderingOptions(PdfRenderSize renderPageSize)

TIFF Creation#

ScanbotSdk.createTiff(pages, options);#

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

List<Page> pages = ...var options = TiffCreationOptions(binarized: true, dpi: 300, compression: TiffCompression.CCITT_T6);Uri tiffFileUri = await ScanbotSdk.createTiff(pages, options);
Arguments:#
  • pages - a list of valid Page objects. Each page should have the cropped DOCUMENT image.
  • options - TiffCreationOptions:
    • binarized : Optional boolean flag to create binarized (one bit encoded) black-and-white images. 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 true.
    • dpi : Dots Per Inch as an optional integer value. The default value is 200 dpi. Please note that the DPI value is just meta data. It does not affect the quality or the resolution of the TIFF image file. The resolution of the output TIFF images will stay the same as that of the input images.
    • compression : Optional TIFF compression type. Default value is LZW. See supported types below.

Supported TIFF compression types:

  • TiffCompression.CCITTRLE
  • TiffCompression.CCITTFAX3
  • TiffCompression.CCITT_T4
  • TiffCompression.CCITTFAX4
  • TiffCompression.CCITT_T6
  • TiffCompression.CCITTRLEW
  • TiffCompression.LZW
  • TiffCompression.PACKBITS
  • TiffCompression.DEFLATE
  • TiffCompression.ADOBE_DEFLATE

⚠️️️ Please note that some compression types are only compatible for binarized images (1-bit encoded black & white images)!

See the list PredefinedCompressionTypes.binarizedOnlyCompressionTypes().

OCR - Optical Character Recognition#

The Scanbot SDK Plugin 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 as much 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

The 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 plugin ships with no training data files by default to keep the plugin 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 Tesseract's 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

In the Scanbot SDK plugin use languages: ["en", "de"].

OCR API#

ScanbotSdk.getOcrConfigs()#

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

Call:#
var result = await ScanbotSdk.getOcrConfigs();// result.installedLanguages ...// result.languageDataPath ...
  • result.languageDataPath - Contains the absolute file URI of the directory where to place the OCR training data files on run-time.
  • result.installedLanguages - Returns an array of current installed OCR languages (e.g. ["en", "fr"]). The Scanbot SDK uses the languageDataPath directory to determine current installed OCR languages.

ScanbotSdk.performOcr(pages, options)#

This function takes an array of pages and performs Optical Character Recognition on each DOCUMENT image of those pages. As result the recognized text can be returned as plain text or a composed PDF file containing selectable and searchable text.

List<Page> pages = ...var options = OcrOptions(languages: ["en", "de"], shouldGeneratePdf: true);var result = await ScanbotSdk.performOcr(pages, options);
  • result.plainText - Contains the recognized plain text of all images.
  • result.pdfFileUri - File URI of the composed PDF file ('file:///...').
  • result.pages - A list of OcrPages with OCR data. Each OcrPage represents OCR result of given scanned Page document image. You can get bounding boxes and values of recognized words, lines and paragraphs.
Options:#
var options = OcrOptions(languages, shouldGeneratePdf);
  • pages - An array with valid Page objects. Each page object should contain a cropped DOCUMENT image.
  • options.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.shouldGeneratePdf - Whether to generate the PDF file or return plain text only.

Barcode Detection from Still Images#

ScanbotSdk.detectBarcodeFromImageFile(Uri file, List<BarcodeFormat> barcodeFormats) This method provides the functionality of detecting barcodes from a still image, e.g. a JPG image from Photo Library or other source. The image must be passed as a file URI.

Parameters:

  • Uri file - A valid file URI of the image (e.g. file:///some/path/image-with-barcodes.jpg). Supported image formats are JPG and PNG. Please make sure your app has the read permission to access this file.
  • List<BarcodeFormat> barcodeFormats - Optional list of barcode formats to recognize.

Result:

  • result.barcodeItems - List of recognized barcodes as items of BarcodeItem type.

Estimate Image Blurriness#

ScanbotSdk.estimateBlurOnPage(Page: page)#

Estimate blurriness on a given page. The document image will be analyzed, if possible. If there is no document image - then the original image will be used. Returns the value between 0.0 and 1.0. Values closer to 0.0 mean that the image is sharper, values closer to 1.0 - the image is blurred.

  • page - The page to estimate blurriness.
var blurValue = await ScanbotSdk.estimateBlurOnPage(page);

Refresh Image URIs#

ScanbotSdk.refreshImageUris(pages)#

API: static Future<List<Page>> refreshImageUris(List<Page> pages) async

See the section Persistence of Page Objects

Cleanup#

ScanbotSdk.cleanupStorage()#

By calling this function all output files generated by the native Scanbot SDKs or by this Plugin will be deleted, including the image files of all scanned or imported Page objects, all produced PDF files, TIFF files, etc.

Call:#
await ScanbotSdk.cleanupStorage();

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 that there is the API function getDecryptedDataFromFile(imageFileUri: string):

Page page = ... // scanned page object// use the low-res image "documentPreviewImageFileUri" for the preview:var decryptedImageData = await ScanbotEncryptionHandler.getDecryptedDataFromFile(page.documentPreviewImageFileUri);Image image = Image.memory(decryptedImageData); //use image widget to show preview

👉 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) Or alternatively, get the decrypted image data as Base64 on the mobile device by using the getDecryptedDataFromFile(imageFileUri: Uri) function and use this data for the upload process:

Examples:

// For a Page image file:Page page = ... // scanned page object// use the final hi-res image "documentImageFileUri" for the upload process:var decryptedImageData = await ScanbotEncryptionHandler.getDecryptedDataFromFile(page.documentImageFileUri);yourCustomUploadFunction(decryptedImageData);
// For a PDF or TIFF file generated by the Scanbot SDK:Uri fileUri = ... // Uri of the generated PDF or TIFF filevar decryptedFileData = await ScanbotEncryptionHandler.getDecryptedDataFromFile(fileUri);yourCustomUploadFunction(decryptedFileData);

File & Directory Handles#

The Scanbot SDK plugin works with file URIs. This means all input and output files (images, PDFs, etc) as well as directories are identified by file URIs. 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/some-sub-folder/ce8de3c4-3c96-4ce1-b285-483d01e1dc9a.jpg

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

Detection Status values#

ScanbotSdk.DetectionStatus#

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

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 primary intended to use on low-contrast documents with heavy shadows.
  • LOW_LIGHT_BINARIZATION_2 - Binarization filter primary intended to use on low-contrast documents with heavy shadows.

Page Size values#

  • PdfRenderSize.A4: The page has the aspect ratio of the image, but is fitted within A4 size. Portrait or landscape orientation is determined by the image's aspect ratio.
  • PdfRenderSize.FIXED_A4: The page is A4 in size. The image is fitted and centered within the page. Portrait or landscape orientation is determined by the image's aspect ratio.
  • PdfRenderSize.US_LETTER: The page has the aspect ratio of the image, but is fitted within US letter size. Portrait or landscape orientation is determined by the image's aspect ratio.
  • PdfRenderSize.FIXED_US_LETTER: The page is US letter in size. The image is fitted and centered within the page. Portrait or landscape orientation is determined by the image's aspect ratio.
  • PdfRenderSize.AUTO: For each page the best matching format (A4 or US letter) is used. Portrait or landscape orientation is determined by the image's aspect ratio.
  • PdfRenderSize.AUTO_LOCALE: Each page of the result PDF will be of US letter or A4 size depending on the current locale. Portrait or landscape orientation is determined by the image's aspect ratio.
  • PdfRenderSize.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 the range [0..1], representing a position relative to the 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 dart result:

var polygon = [     PolygonPoint(0.046,0.1306),     PolygonPoint(0.087,0.346),     PolygonPoint(0.021,0.678),     PolygonPoint(0.34,0.90),];

Barcode Format#

The following barcode formats are currently supported.

1D Barcodes#

2D Barcodes#

tip

You might also be interested in an overview in our blog post Types of barcodes and their usage.

BarcodeFormattedResult - Barcode Data Parsers#

The following parsed barcode data results (implementations of the BarcodeFormattedResult) are currently supported:

  • AAMVA: Parse the AAMVA data format from PDF-417 barcodes on US driver’s licenses - see AAMVADocument.
  • Boarding pass data from PDF-417 barcodes - see BoardingPassDocument.
  • Parser for German Medical Certificates (aka. Disability Certificate or AU-Bescheinigung) coded in a PDF-417 barcode - see DisabilityCertificateDocument.
  • Data from PDF-417 barcodes on ID Cards - see IDCardPDF417Document.
  • Parse and extract data from XML of Data Matrix barcodes on German Medical Plans (Medikationsplan). See DEMedicalPlanDocument.
  • Data parser of QR-Code values printed on SEPA pay forms - see SEPADocument.
  • vCard data from a QR-Code (e.g. on business cards) - see VCardDocument.

Camera Orientation Mode#

Supported Camera Orientation modes:

- NONE- PORTRAIT- PORTRAIT_UPSIDE_DOWN- LANDSCAPE_LEFT- LANDSCAPE_RIGHT- LANDSCAPE

Image Format#

Supported image formats:

- JPG- PNG

Building Production Apps#

iOS#

The Scanbot SDK iOS Framework (included in this Flutter Plugin) contains 64-bit architectures (arm64, x86_64). You can thus run it on all commonly used iOS devices as well as on simulators during the development phase. To be able to submit a production build to the App Store or a test build for TestFlight you have to remove (strip away) the architectures x86_64 and i386 from the Scanbot SDK Framework. These architectures are only for simulators and not allowed to be submitted to iTunes Connect.

Android#

The Scanbot Android 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 large 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/app/build.gradle file of your project:

android {  ...  defaultConfig {    ...    ndk {      abiFilters "armeabi-v7a", "arm64-v8a"        // Please add "x86" and "x86_64" if you would like to test on an emulator        // or if you need to support some rare devices with the Intel Atom architecture.    }  }}

In this example we defined abiFilters for armeabi-v7a and arm64-v8a, so x86 and x86_64 architectures will be excluded.

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