# Class: DocumentScanner

[Mobile Document Scanner API Reference](../index.md) / DocumentScanner

# Class: DocumentScanner

Defined in: [src/DocumentScanner.ts:451](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/src/DocumentScanner.ts#L451)

Main class for document scanning functionality with camera capture, document detection, perspective correction, and result management.

## Remarks

The `DocumentScanner` class provides a complete document scanning solution that integrates camera access, real-time document boundary detection, manual boundary adjustment, and image perspective correction. It orchestrates three main views:
- [DocumentScannerView](DocumentScannerView.md): Camera interface with document detection and capture modes
- [DocumentCorrectionView](DocumentNormalizerView.md): Manual boundary adjustment interface
- [DocumentResultView](DocumentResultView.md): Result preview and action interface

The class supports both single-scan and continuous scanning modes. In continuous mode, the scanner loops back after each successful scan, allowing multiple documents to be captured in sequence.

## Examples

Basic usage with default configuration:
```javascript
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE"
});

const result = await documentScanner.launch();
if (result?.correctedImageResult) {
    const canvas = result.correctedImageResult.toCanvas();
    document.body.appendChild(canvas);
}
```

Continuous scanning mode:
```javascript
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE",
    enableContinuousScanning: true,
    onDocumentScanned: async (result) => {
        // Process each scanned document
        await uploadToServer(result.correctedImageResult);
    }
});

await documentScanner.launch();
```

Process an existing image file:
```javascript
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE"
});

const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const result = await documentScanner.launch(file);
```

## Constructors

### Constructor

> **new DocumentScanner**(`config`): `DocumentScanner`

Defined in: [src/DocumentScanner.ts:531](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/src/DocumentScanner.ts#L531)

Create a DocumentScanner instance with settings specified by a [DocumentScannerConfig](../interfaces/DocumentScannerConfig.md) object.

#### Parameters

##### config

[`DocumentScannerConfig`](../interfaces/DocumentScannerConfig.md)

The [DocumentScannerConfig](../interfaces/DocumentScannerConfig.md) to set all main configurations, including UI toggles, data workflow callbacks, etc. You must set a valid license key with the `license` property. See [DocumentScannerConfig](../interfaces/DocumentScannerConfig.md) for a complete description.

#### Returns

`DocumentScanner`

#### Example

HTML:
```html
<div id="myDocumentScannerContainer" style="width: 80vw; height: 80vh;"></div>
```
JavaScript:
```javascript
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key
    scannerViewConfig: {
        container: document.getElementById("myDocumentScannerViewContainer") // Use this container for the scanner view
    }
});
```

## Methods

### dispose()

> **dispose**(): `void`

Defined in: [src/DocumentScanner.ts:1118](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/src/DocumentScanner.ts#L1118)

Clean up and release all resources used by the DocumentScanner.

#### Returns

`void`

#### Remarks

**This method is called automatically at the end of [launch](#launch), so manual invocation is typically only needed if you want to clean up resources before the scanning workflow completes.**

This method performs comprehensive cleanup by:
- Disposing all view components (scanner, correction, result)
- Releasing Dynamsoft Capture Vision resources (camera, router)
- Clearing all container elements
- Resetting internal state

After calling dispose, you can create a new DocumentScanner instance if you need to scan again.

#### Example

Manual cleanup:
```javascript
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE"
});

await documentScanner.launch();

// Clean up is automatic after launch completes
// But you can also call it manually if needed:
documentScanner.dispose();
console.log("Scanner resources released");
```

***

### initialize()

> **initialize**(): `Promise`\<\{ `components`: \{ `correctionView?`: [`DocumentNormalizerView`](DocumentNormalizerView.md); `scannerView?`: [`DocumentScannerView`](DocumentScannerView.md); `scanResultView?`: [`DocumentResultView`](DocumentResultView.md); \}; `resources`: `SharedResources`; \}\>

Defined in: [src/DocumentScanner.ts:570](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/src/DocumentScanner.ts#L570)

Initialize the DocumentScanner by setting up Dynamsoft Capture Vision resources and view components.

#### Returns

`Promise`\<\{ `components`: \{ `correctionView?`: [`DocumentNormalizerView`](DocumentNormalizerView.md); `scannerView?`: [`DocumentScannerView`](DocumentScannerView.md); `scanResultView?`: [`DocumentResultView`](DocumentResultView.md); \}; `resources`: `SharedResources`; \}\>

A promise that resolves to an object containing:
- `resources`: The `SharedResources` object containing camera, router, and state
- `components`: An object with references to the initialized view components ([scannerView](DocumentScannerView.md), [correctionView](DocumentNormalizerView.md), [scanResultView](DocumentResultView.md))

#### Remarks

**This method is called automatically by [launch](#launch) and typically does not need to be invoked manually.**

This method performs the following initialization steps:
1. Validates and processes the configuration provided to the constructor
2. Initializes Dynamsoft Capture Vision engine resources (license, camera, router)
3. Creates and initializes the configured view components (scanner, correction, result)
4. Sets up shared resources and callbacks for communication between views

The method is idempotent - calling it multiple times will return the same resources and components without re-initialization.

#### Throws

If initialization fails due to invalid configuration, missing license, or resource loading errors

#### Example

Manual initialization (**rarely needed**):
```javascript
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE"
});

try {
    const { resources, components } = await documentScanner.initialize();
    console.log("Scanner initialized successfully");
} catch (error) {
    console.error("Initialization failed:", error);
}
```

***

### launch()

> **launch**(`file?`): `Promise`\<[`DocumentResult`](../interfaces/DocumentResult.md)\>

Defined in: [src/DocumentScanner.ts:1487](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/src/DocumentScanner.ts#L1487)

Start the document scanning workflow.

#### Parameters

##### file?

[`File`](https://developer.mozilla.org/en-US/docs/Web/API/File)

Optional image file to process instead of using the camera

#### Returns

`Promise`\<[`DocumentResult`](../interfaces/DocumentResult.md)\>

Promise resolving to the [DocumentResult](../interfaces/DocumentResult.md), which includes:
- `status`: Scan status (success, cancelled, or failed)
- `correctedImageResult`: Perspective-corrected document image
- `originalImageResult`: Original captured image
- `detectedQuadrilateral`: Detected document boundaries

#### Remarks

This is the primary method for initiating document scanning. It performs the following:
1. Automatically calls [initialize](#initialize) if not already initialized
2. Opens the camera and displays the [DocumentScannerView](DocumentScannerView.md) (unless a file is provided)
3. Guides the user through the configured workflow (scan → correction → result)
4. Returns the final [DocumentResult](../interfaces/DocumentResult.md) when the workflow completes
5. Automatically calls [dispose](#dispose) to clean up resources

**Scanning Modes:**
- **Single-scan mode (default)**: Captures one document and returns the result
- **Continuous scanning mode** ([DocumentScannerConfig.enableContinuousScanning](../interfaces/DocumentScannerConfig.md#enablecontinuousscanning)): Invokes [DocumentScannerConfig.onDocumentScanned](../interfaces/DocumentScannerConfig.md#ondocumentscanned) with each scan, and loops back to capture another document whenever the user taps "Scan More". The loop ends when the user taps "Done", clicks the close button (X), or [stopContinuousScanning](#stopcontinuousscanning) is called. Returns the last scanned result.

**File Processing:**
Passing a [File](https://developer.mozilla.org/en-US/docs/Web/API/File) object allows processing an existing image file, bypassing camera input and the [DocumentScannerView](DocumentScannerView.md).

#### Throws

If a capture session is already in progress

#### Examples

Basic single-scan usage:
```javascript
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE"
});

const result = await documentScanner.launch();

if (result?.correctedImageResult) {
    resultContainer.innerHTML = "";
    const canvas = result.correctedImageResult.toCanvas();
    resultContainer.appendChild(canvas);
} else {
    resultContainer.innerHTML = "<p>No image scanned. Please try again.</p>";
}
```

Process an existing image file:
```javascript
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE"
});

const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const result = await documentScanner.launch(file);
```

Continuous scanning mode:
```javascript
const scannedDocs = [];
const documentScanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE",
    enableContinuousScanning: true,
    onDocumentScanned: async (result) => {
        scannedDocs.push(result);
        console.log(`Scanned ${scannedDocs.length} documents`);
    }
});

// This will return the last scanned result when user exits
const lastResult = await documentScanner.launch();
```

***

### stopContinuousScanning()

> **stopContinuousScanning**(): `void`

Defined in: [src/DocumentScanner.ts:1083](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/src/DocumentScanner.ts#L1083)

Stop continuous scanning and exit the scanning loop.

#### Returns

`void`

#### Remarks

When called with [DocumentScannerConfig.enableContinuousScanning](../interfaces/DocumentScannerConfig.md#enablecontinuousscanning) enabled and [launch](#launch) running, signal the scanner to stop looping and return from [launch](#launch) with the last scanned result.

This provides an alternative to using the close button (X) for exiting continuous scanning mode,
allowing you to implement custom exit logic based on conditions such as:
- Maximum number of scanned documents reached
- Time limits
- User interaction with custom UI elements
- External events or triggers

#### Examples

Stop after scanning 5 documents:
```javascript
let scannedCount = 0;
const scanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE",
    enableContinuousScanning: true,
    onDocumentScanned: async (result) => {
        scannedCount++;
        console.log(`Scanned document ${scannedCount}`);

        if (scannedCount >= 5) {
            scanner.stopContinuousScanning();
        }
    }
});

await scanner.launch(); // Exits after 5 scans
```

Stop from external button:
```javascript
const scanner = new Dynamsoft.DocumentScanner({
    license: "YOUR_LICENSE_KEY_HERE",
    enableContinuousScanning: true,
    onDocumentScanned: async (result) => {
        // Process each scanned document
        saveDocument(result);
    }
});

// Bind to custom stop button
document.getElementById('stopBtn').addEventListener('click', () => {
    scanner.stopContinuousScanning();
});

await scanner.launch(); // Will exit when stopBtn is clicked
```
