Skip to main content

Getting started with the Web Document Scanner SDK's Classic UI

Configuration & styling

To start the Document Scanner Classic UI, first create a DocumentScannerViewConfiguration object, or simply a dictionary in vanilla JavaScript:

const config = {
containerId: containerId,
};

The only required property is the containerId string, which should match the container where you want the Document Scanner to appear.

DocumentScannerViewConfiguration inherits the base properties:

  • containerId: The id of the containing HTML element where the Document Scanner will be initialized. Required.
  • videoConstraints: The desired video resolution. Optional, defaults to 3840x2160.
  • mirrored: Whether the screen should be mirrored. Useful when using a user-facing camera. false by default.
  • preferredCamera: Camera label or camera device ID. If not available, a default camera is used as a fallback.
  • onError: Callback when something went wrong. Optional.

The configuration object also accepts the following parameters (values displayed are defaults):

autoCaptureSensitivity: 0.66,
autoCaptureEnabled: true,
ignoreBadAspectRatio: true,
useImageCaptureAPI: false,
scannerConfiguration: new DocumentScannerConfiguration()

Please refer to the API documentation for a description of all the fields of DocumentScannerParameters.

You can also use the configuration object for React-like styling. It accepts the following parameters for the document outline, hint text label and capture button color (values displayed are defaults):

style: {
outline: {
polygon: {
strokeCapturing: "green",
strokeSearching: "yellow",
fillCapturing: "transparent",
fillSearching: "transparent",
strokeWidth: "2px"
},
label: {
position: "absolute",
top: "90%",
left: "50%",
transform: "translate(-50%, -50%)",
textAlign: "center",
backgroundColor: "rgba(0, 0, 0, 0.7)",
color: "white",
borderRadius: "0.25em",
padding: "0.5em",
fontFamily: "sans-serif",
fontSize: "1em"
},
path: {
stroke: "green";
strokeWidth: 4;
}
},
captureButton: {
color: "white"
}
};

Moreover, the hint texts can also be configured via the same configuration object (values displayed are defaults):

text: {
hint: {
NOT_ACQUIRED: "Detection has not yet happened.",
OK: "An acceptable document was detected.",
OK_BUT_TOO_SMALL: "A document was detected, but it is too small.",
OK_BUT_BAD_ANGLES: "A document was detected, but it has too much perspective distortion.",
OK_BUT_BAD_ASPECT_RATIO: "A document was detected, but its aspect ratio is not acceptable.",
OK_BUT_ORIENTATION_MISMATCH: "A document was detected, but its orientation does not match the input image orientation.",
OK_BUT_OFF_CENTER: "A document was detected, but its center is too far away from the input image center.",
OK_BUT_TOO_DARK: "A document was detected, but it is too dark.",
ERROR_NOTHING_DETECTED: "No document was detected.",
ERROR_TOO_DARK: "No document was detected, likely because the input image is too dark.",
ERROR_TOO_NOISY: "No document was detected, likely because the input image is too noisy or has a complex background."

}
};

The Document Scanner works at the maximum available camera resolution for the highest quality scans by default.

You can further configure the camera video stream by specifying the videoConstraints property of the Document Scanner configuration. Most video constraints are directly given to getUserMedia.

The default video constraints are as follows:

videoConstraints: MediaTrackConstraints = {
facingMode: "environment",
resizeMode: "none",
width: { ideal: 3840 },
height: { ideal: 2160 },
experimental: {
focusMode: "continous",
focusDistance: 0
},
};

Everything except experimental is passed directly to getUserMedia. Since these are advanced constraints, they will not work on all browsers and thus require special application. All advanced constraints, however, are passed to the video stream in the same fashion.

You can add additional advanced constraints.

Callbacks

To receive detection results, define onDocumentDetected in the configuration:

onDocumentDetected: result => {
console.log("Detected Document:", result);
}

Please refer to the API documentation for a description of all fields of the result object.

Note that this will be called every time a document is detected until you stop detection or dispose of the camera.

The scanner object

To open the Document Scanner, simply call the relevant SDK function with your configuration object:

scanner = await scanbotSDK.createDocumentScanner(config);

An exception is thrown if camera streaming is not supported or the user blocks the camera.

Handling automatic capture

There is the option to disable automatic capture on the fly (e.g., when processing images between document captures).

You can also use these calls to create your own custom auto-capture on/off switch.

Call to disable auto-capture:

scanner.disableAutoCapture();

When processing is complete or the switch is toggled, re-enable it with the following command:

scanner.enableAutoCapture();

To verify whether auto-capture is enabled or not, call:

scanner.isAutoCaptureEnabled();

Switching to a specific available camera

scanner.fetchAvailableCameras(): Promise<CameraInfo[]>;
scanner.switchCamera(deviceId: string, mirrored?: boolean): void;
scanner.getActiveCameraInfo(): CameraInfo | undefined;
interface CameraInfo {
deviceId: string;
label: string;
facingMode?: CameraFacingMode;
supportsTorchControl?: boolean;
}

type CameraFacingMode = 'front' | 'back' | 'unknown';

You can search for available cameras on the running browser by using the fetchAvailableCameras method of a scanner.

You can retrieve the label, device ID, and the camera facing mode information of the active camera of a scanner by using the getActiveCameraInfo method.

You can also switch to another available camera by utilizing its device ID with the switchCamera method.

// There can be no cameras available, so check if cameras is not null
const cameras = await scanner.fetchAvailableCameras()
// Current camera info can be unavailable, so check if currentCameraInfo is not null
const currentCameraInfo = scanner.getActiveCameraInfo();
const cameraIndex = cameras.findIndex((cameraInfo) => {
return cameraInfo.deviceId == currentCameraInfo.deviceId;
});
const newCameraIndex = (cameraIndex + 1) % (cameras.length);
scanner.switchCamera(cameras[newCameraIndex].deviceId);

Controlling the torch (flashlight)

On some mobile devices, the browser can control the torch (flashlight). Check scanner.getActiveCameraInfo().supportsTorchControl to see if the browser can control the torch for the currently active camera. If true, you can control the torch by using the setTorchState method of the scanner.

scanner.setTorchState(state: boolean): Promise<void>;
info

On Android devices, only Chrome supports torch control. Starting with iOS 17.4, all supported browsers on iOS offer torch control functionality.

Disposal

As with all scanners included in the Scanbot SDK, this one should be properly disposed of when you have detected and processed the relevant data. This ensures the camera instance as well as lingering SDK functions are properly disposed of to prevent memory leaks.

await scanner.dispose();

Want to scan longer than one minute?

Generate a free trial license to test the Scanbot SDK thoroughly.

Get free trial license