Appearance
Mobile Document Scanner API Reference / DocumentScanner
Class: DocumentScanner
Defined in: src/DocumentScanner.ts:451
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: Camera interface with document detection and capture modes
- DocumentCorrectionView: Manual boundary adjustment interface
- DocumentResultView: 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
Create a DocumentScanner instance with settings specified by a DocumentScannerConfig object.
Parameters
config
The DocumentScannerConfig 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 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
Clean up and release all resources used by the DocumentScanner.
Returns
void
Remarks
This method is called automatically at the end of 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;scannerView?:DocumentScannerView;scanResultView?:DocumentResultView; };resources:SharedResources; }>
Defined in: src/DocumentScanner.ts:570
Initialize the DocumentScanner by setting up Dynamsoft Capture Vision resources and view components.
Returns
Promise<{ components: { correctionView?: DocumentNormalizerView; scannerView?: DocumentScannerView; scanResultView?: DocumentResultView; }; resources: SharedResources; }>
A promise that resolves to an object containing:
resources: TheSharedResourcesobject containing camera, router, and statecomponents: An object with references to the initialized view components (scannerView, correctionView, scanResultView)
Remarks
This method is called automatically by launch and typically does not need to be invoked manually.
This method performs the following initialization steps:
- Validates and processes the configuration provided to the constructor
- Initializes Dynamsoft Capture Vision engine resources (license, camera, router)
- Creates and initializes the configured view components (scanner, correction, result)
- 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>
Defined in: src/DocumentScanner.ts:1487
Start the document scanning workflow.
Parameters
file?
Optional image file to process instead of using the camera
Returns
Promise<DocumentResult>
Promise resolving to the DocumentResult, which includes:
status: Scan status (success, cancelled, or failed)correctedImageResult: Perspective-corrected document imageoriginalImageResult: Original captured imagedetectedQuadrilateral: Detected document boundaries
Remarks
This is the primary method for initiating document scanning. It performs the following:
- Automatically calls initialize if not already initialized
- Opens the camera and displays the DocumentScannerView (unless a file is provided)
- Guides the user through the configured workflow (scan → correction → result)
- Returns the final DocumentResult when the workflow completes
- Automatically calls dispose to clean up resources
Scanning Modes:
- Single-scan mode (default): Captures one document and returns the result
- Continuous scanning mode (DocumentScannerConfig.enableContinuousScanning): Invokes DocumentScannerConfig.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 is called. Returns the last scanned result.
File Processing: Passing a File object allows processing an existing image file, bypassing camera input and the DocumentScannerView.
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
Stop continuous scanning and exit the scanning loop.
Returns
void
Remarks
When called with DocumentScannerConfig.enableContinuousScanning enabled and launch running, signal the scanner to stop looping and return from 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 scansStop 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