Capacitor tutorial: Integrating the Scanbot Document Scanner SDK with Ionic

In this tutorial, we’re going to show you how to integrate document scanning into your mobile app using Capacitor with Ionic.

app store

Updated on May 16, 2024

What is Capacitor?

Capacitor is an open-source, cross-platform app runtime maintained by Ionic and its community. The framework enables you to develop modern hybrid apps using HTML, CSS, and JavaScript. Capacitor comes with a number of native APIs and its own plug-in system. In addition, it’s backwards-compatible with Cordova plugins.

In this step-by-step tutorial, we’re going to show you how you can rapidly integrate our Document Scanner SDK to benefit from advanced document scanning features in your Capacitor app.

Getting Started

Requirements

  • Node & npm

For Android apps

  • Android Studio with the Android SDK installed

For iOS apps

  • Xcode
  • Xcode Command Line Tools
  • Homebrew
  • CocoaPods

💡 Make sure to take a look at how to set up your development environment for Capacitor and Ionic.

Installation

We are going to use Capacitor with the Ionic framework. Ionic ships with Capacitor, and new Ionic apps are set up with it by default, so we don’t have to install it or add it to an app separately.

Install Ionic

npm install -g @ionic/cli native-run

Then create an empty Ionic app:

ionic start myCapacitorApp blank

💡 The Ionic framework enables app development using Angular, React, and Vue. In our example, we’ll use Angular, but you’re welcome to select your preferred framework. The process is the same regardless of your choice.

Adding Android and iOS as platforms

Once Capacitor is initialized, we add Android and iOS as platforms:

ionic capacitor add android
ionic capacitor add ios

Your blank Capacitor app project is now ready to go. You can start your app with Android Studio or Xcode by opening the IDE with these commands:

ionic capacitor build android
ionic capacitor build ios

… and run the apps from there.

Note for iOS Development: Please ensure that you have added a development team for iOS before building the application. This is essential for proper provisioning and deployment on iOS devices or simulators.

Or you can run the app directly:

ionic capacitor run android
ionic capacitor run ios

🎉 Congrats! You should now see a blank sample app.

Installing the Scanbot SDK plugin

Let’s install the capacitor-plugin-scanbot-sdk to our project and synchronize it with Capacitor:

npm install capacitor-plugin-scanbot-sdk
ionic capacitor build
ionic capacitor sync

Please note that ionic capacitor sync is required to update the dependencies and copy the web assets to native projects (Android and iOS).

Adding Permissions

If you plan to use the Scanbot SDK to scan documents with the device’s camera, you must grant camera permission in your AndroidManifest.xml file (for Android) and Info.plist (for iOS).

AndroidManifest.xml

Add the following line:

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

Info.plist

Add the key NSCameraUsageDescription with a description explaining why your app needs access to the camera. 

After adding the required permissions, you can proceed with initializing the Scanbot SDK and using its features that require camera access.

Integrating the Scanbot SDK plugin

The Scanbot SDK must be initialized before usage. Use the ScanbotSDK.initializeSDK() method for that:

ScanbotSDK.initializeSDK({
    loggingEnabled: true,
    licenseKey: '', // see the license key notes!
    storageImageFormat: 'JPG',
    storageImageQuality: 80
}).then((result) => {
    console.log(result);
}).catch((err) => {
    console.error(err);
});

For the full API reference of the Scanbot SDK plugin, please refer to our Capacitor documentation.

License key

⚠️ Please note: The Scanbot SDK will run without a license key for one minute per session! After the trial period is over, all Scanbot SDK functions and its UI components will stop working or may be terminated.

You can get an unrestricted, no-strings-attached 7-day trial license for free. Please submit the Trial License Form on our website by using the app identifier (app ID / bundle ID) you specified when creating it (e.g., com.example.mycapacitorapp).

Once you have successfully implemented the initialization of Scanbot SDK, you are ready to call the UI components and perform some image operations.

Starting the document scanner

The Scanbot SDK provides a ready-to-use Document Scanner UI for guided, automatic document scanning. More configuration options can be applied to tailor it to your use case.

To launch it, use the async API method ScanbotSDK.startDocumentScanner().

In the HTML files:

<ion-button (click)="startDocumentScanner()">
    Open Document Scanner
</ion-button>

In the TypeScript files:

async startDocumentScanner() {
    const result = await ScanbotSDK.startDocumentScanner({
        // Customize colors, text resources, behavior, etc.
        cameraPreviewMode: 'FIT_IN',
        orientationLockMode: 'PORTRAIT',
        pageCounterButtonTitle: '%d Page(s)',
        multiPageEnabled: true
        // ...
    });


    if (result.status === 'CANCELED') {
        // user has canceled the scanning operation
        return;
    }

    // Get the scanned pages from result:
    this.pages = result.pages;
}

When making changes to the web code in a Capacitor project, you have to rebuild the web project. Update the Capacitor native projects with the transpiled JavaScript code and web assets by running:

ionic capacitor sync

After that, run the app in Android Studio / Xcode (or using ionic capacitor run android / ionic capacitor run ios).

You’re now ready to try the Document Scanner! This is how it will look like:

Showing the image results

The Document Scanner returns an array of Page objects which contain both the scanned document and original images. A document image is the cropped and perspective corrected image, while the original image is the unprocessed image.

Furthermore, a Page object provides preview images that can be used as thumbnails for displaying:

<ion-grid>
  <ion-row>
    <ion-col padding col-4 *ngFor='let page of pages'>
      <ion-img [src]='page.documentPreviewImageFileUri'/>
    </ion-col>
  </ion-row>
</ion-grid>

All images are stored as files and represented as file URIs (file:///…). You can configure the image storage to store the files in different formats and also set the desired image quality. In our code above, we specified JPG images at 80% quality. In addition, you can encrypt the image storage.

💡 Capacitor apps are served on a different protocol than device files. Sanitize the image path before displaying it with ion-img:

Capacitor.convertFileSrc(page.documentPreviewImageFileUri)

Starting the cropping UI

With our Cropping UI, you can enable users to manually correct the cropping of a scanned image. It’s based on document detection and contains smart UI elements like magnetic lines and a magnifier.

Use the async API method ScanbotSDK.startCroppingScreen() and pass an existing Page object along with the desired scanner configuration to launch the Cropping UI:

async startCroppingScreen(page: Page) {
    const result = await ScanbotSDK.startCroppingScreen({
        page: page,
        configuration: {
            // Customize colors, text resources, behavior, etc.
            doneButtonTitle: 'Save'
            // ...
        }
    });

    if (result.status === 'CANCELED') { return; }

    // handle the updated page object:
    this.updatePage(result.page);
}

Conclusion

You now have access to powerful document scanning features in your Capacitor app.

If you had trouble with this tutorial, we’re glad to help: We offer free integration support for the implementation and testing of the Scanbot SDK. If you encounter technical issues or want advice on choosing the appropriate framework or features, join our Slack or MS Teams or send us an email to receive your free support.

💡 Did you have trouble with this tutorial?

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

Developers, ready to get started?

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