Skip to content

Xamarin Document Scanner Tutorial – SDK integration step by step for iOS and Android

Integrating the Scanbot SDK for cross-platform app development for both Android and iOS…

Ivan March 1, 2024 9 mins read
app store

Getting started

Requirements

For Android apps

For iOS apps

  • macOS with the latest version of Xcode

Create a “Hello World” Xamarin.Forms app

1. Open Visual Studio

2. Select Create a new Project

3. Select Multiplatform > App > Blank Forms App and click Next.

4. Enter “MyAwesomeXamarinApp” as App Name, and “com.example” as Organization Identifier. Make sure that both Android and iOS are checked as Target Platforms and click Next.

5. On the last screen, click Create.

Test run

Next, let’s connect a mobile device via USB and run the app.

Android

In Visual Studio, under MyAwesomeXamarinApp, right-click on MyAwesomeXamarinApp.Android and select “Set As Startup Project“. Then select your target device and hit the “Run” button.

iOS

In Visual Studio, under MyAwesomeXamarinApp, right-click on MyAwesomeXamarinApp.iOS and select “Set As Startup Project“. Then select your target device and hit the “Run” button.

Or

In Visual Studio, Under MyAwesomeXamarinApp.iOS open the Info.plist file and select the Application tab. Here adjust the “Signing & Capabilities”  settings of iOS by selecting your Apple developer account. Then select your target device and hit the “Run” button.

Add the Scanbot SDK

The Scanbot SDK for Xamarin.Forms is available as the NuGet package ScanbotSDK.Xamarin.Forms

You can install it directly in the Visual Studio IDE: Click on the menu item Project > Manage NuGet Packages. Make sure nuget.org is selected as a source, then search for the package name ScanbotSDK.Xamarin.Forms.

Pick the right package and click on Add Package. On the next screen, select all projects to install and add the Scanbot SDK package to all projects.

Furthermore, we need to add the library “Mono.Android.Export” as a reference to our Android project. Double-click on References in the MyAwesomeXamarinApp.Android project, find and select the “Mono.Android.Export” assembly, then click OK to confirm.

Android settings

Enable Multi-Dex

Double-click the Android project, go to Android Build, then check Enable Multi-Dex.

Permissions

Required permissions for Android

Make sure to add the Camera permission in your MyAwesomeXamarinApp.Android/Properties/AndroidManifest.xml file. Right-click on this file > Open With > Source Code Editor and add the following lines:

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

Required permissions for iOS

Add the following property to your MyAwesomeXamarinApp.iOS/Info.plist file:

NSCameraUsageDescription "Privacy - Camera Usage Description"

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

It’s coding time

Initialize the Scanbot SDK


The Scanbot SDK must be initialized before usage. We will use the SDK API method SBSDKInitializer.Initialize() for that. 

Make sure to run the initialization as early as possible. We recommend implementing the initialization in the Application class of the Android app, and in the AppDelegate class of the iOS app.

Android

By default, Visual Studio does not generate an Application class for the Android project, so we need to take care of it ourselves.

Create a new C# file MainApplication.cs in the MyAwesomeXamarinApp.Android project and add the following content:

using System;
using Android.App;
using Android.Runtime;
using ScanbotSDK.Xamarin.Forms; 

namespace MyAwesomeXamarinApp.Droid
{    
	[Application(LargeHeap = true)]    
  public class MainApplication : Application    
  {        
  	const string LICENSE_KEY = null; // see the license key notes below!         
    public MainApplication(IntPtr javaReference, JniHandleOwnership transfer)            
    	: base(javaReference, transfer) { }         
    
    public override void OnCreate()        
    {            
    	var configuration = new SBSDKConfiguration            
      {                
      	EnableLogging = true,                
        DetectorType = DocumentDetectorType.MLBased,            
      };            
      SBSDKInitializer.Initialize(this, LICENSE_KEY, configuration);        
    }    
  }
}

iOS

The iOS project already contains the AppDelegate class in the MyAwesomeXamarinApp.iOS/AppDelegate.cs file.

Open it and add the SDK initialization code as follows:

using System;
...
using ScanbotSDK.Xamarin.Forms;

[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    const string LICENSE_KEY = null; // see the license key notes below!
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        var configuration = new SBSDKConfiguration
        {
            EnableLogging = true,
            DetectorType = DocumentDetectorType.MLBased,
        };
        SBSDKInitializer.Initialize(app, LICENSE_KEY, configuration);
 
        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());
        return base.FinishedLaunching(app, options);
    }

💡 For the full API reference of the Scanbot SDK for Xamarin.Forms, please check out the documentation.

Integrate the Document Scanner UI

The Scanbot SDK for Xamarin.Forms provides a Scanner UI for document scanning. 

This Document Scanner is a complete and ready-to-use screen component and can be easily integrated with just a few lines of code using the API method SBSDK.UI.LaunchDocumentScannerAsync().

To do that, we will now switch to the Xamarin.Forms project MyAwesomeXamarinApp, where we will integrate the document scanner as cross-platform code.

First, we create a simple UI by adding a Button and an Image element to the main page of our app. The Button will start the document scanner, while the Image element will show the last scanned document image.

Open the file MyAwesomeXamarinApp/<strong>MainPage.xaml</strong> and change the StackLayout element to read as follows:

<StackLayout Padding="20">
    <Button Text="Scan Document" Clicked="ScanDocumentButtonClicked" />
    <Image x:Name="ScannedDocumentImage" />
</StackLayout>

The code Clicked="ScanDocumentButtonClicked" defines the name of the method for the click event. We will implement this method in the next step.

The image attribute x:Name=”ScannedDocumentImage” defines the name of the variable we will use to display the scanned image. To do that, we make use of the Data Binding technique of Xamarin.Forms.

Now let’s implement the document scanner call. Modify the file MyAwesomeXamarinApp/<strong>MainPage.xaml.cs</strong> as follows:

using System;
using Xamarin.Forms;
using ScanbotSDK.Xamarin.Forms;
 
namespace MyAwesomeXamarinApp
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        async void ScanDocumentButtonClicked(object sender, EventArgs args)
        {
            var config = new DocumentScannerConfiguration()
            {
                MultiPageEnabled = false,
                IgnoreBadAspectRatio = true,
            };
 
            var result = await SBSDK.UI.LaunchDocumentScannerAsync(config);
 
            if (result.Status == OperationResult.Ok)
            {
                ScannedDocumentImage.Source = result.Pages[0].DocumentPreview;
            }
        }
    }
}

The function SBSDK.UI.LaunchDocumentScannerAsync(config) starts the document scanner and awaits the result of the scan.

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

As a result, the document scanner returns an array of scanned page objects. These objects contain the scanned document and original images. A document image is the cropped and perspective corrected image (hi-res), while the original image is the unprocessed image (hi-res). 

All images are stored as JPG files by default. Additionally, the page object provides preview images (low-res), which should be used as thumbnails for displaying.

For simplicity, in this example, we have disabled the multipage feature of the document scanner via the config parameter MultiPageEnabled = false. This means that the scanner UI will automatically close after one single scan. Once it’s done, we can use the first page element from the array –result.Pages[0] – to display its cropped document image.

Now let’s take a look at the following line:

ScannedDocumentImage.Source = result.Pages[0].DocumentPreview;

Here, we take the first scanned page and set the ScannedDocumentImage we defined on the UI screen to display it.

That’s it! Now run the complete project in Visual Studio. The app should allow you to scan and display a document image:

Complete example projects

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

Scanbot SDK (trial) license key

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

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

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

To request one license key for both platforms, Android and iOS, for this tutorial app, make sure the app IDs are the same.

Where to find the app identifier:

  • For Android: double-click the Android project “MyAwesomeXamarinApp.Android” in Visual Studio > Build > Android Application > Package name
  • For iOS: Open the Info.plist file in the iOS project “MyAwesomeXamarinApp.iOS” and check the property Bundle Identifier

💡 Did you have trouble with this tutorial?

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