diff --git a/_data/product_version.yml b/_data/product_version.yml index 5af6478..f3769dd 100644 --- a/_data/product_version.yml +++ b/_data/product_version.yml @@ -1,7 +1,8 @@ useGroupedVersion: true version_info_list: - - value: 1.3.1 MDS (latest version) + - value: 1.4.0 MDS (latest version) + - value: 1.3.1 MDS - value: 3.1 MWC (MDS 1.1) - value: 3.0 MWC (MDS 1.0) - value: 2.0 MWC diff --git a/_includes/sidelist-api-v1.3.1.html b/_includes/sidelist-api-v1.3.1.html new file mode 100644 index 0000000..d81558c --- /dev/null +++ b/_includes/sidelist-api-v1.3.1.html @@ -0,0 +1,2 @@ +
  • API Reference +
  • diff --git a/_includes/sidelist-code-gallery-v1.3.1.html b/_includes/sidelist-code-gallery-v1.3.1.html new file mode 100644 index 0000000..47205ab --- /dev/null +++ b/_includes/sidelist-code-gallery-v1.3.1.html @@ -0,0 +1,10 @@ +
  • Code Gallery + +
  • diff --git a/_includes/sidelist-full-tree-v1.3.1.html b/_includes/sidelist-full-tree-v1.3.1.html new file mode 100644 index 0000000..ca98c69 --- /dev/null +++ b/_includes/sidelist-full-tree-v1.3.1.html @@ -0,0 +1,5 @@ +{%- include liquid_searchVersionTreeFile.html ver=include.ver curPath=include.curPath targetRelativePath="sidelist-introduction-v1.3.1.html" -%} +{%- include liquid_searchVersionTreeFile.html ver=include.ver curPath=include.curPath targetRelativePath="sidelist-guide-v1.3.1.html" -%} +{%- include liquid_searchVersionTreeFile.html ver=include.ver curPath=include.curPath targetRelativePath="sidelist-code-gallery-v1.3.1.html" -%} +{%- include liquid_searchVersionTreeFile.html ver=include.ver curPath=include.curPath targetRelativePath="sidelist-api-v1.3.1.html" -%} +{%- include liquid_searchVersionTreeFile.html ver=include.ver curPath=include.curPath targetRelativePath="sidelist-release-notes.html" -%} diff --git a/_includes/sidelist-guide-v1.3.1.html b/_includes/sidelist-guide-v1.3.1.html new file mode 100644 index 0000000..5d7dcb7 --- /dev/null +++ b/_includes/sidelist-guide-v1.3.1.html @@ -0,0 +1,7 @@ +
  • Developer Guide + +
  • diff --git a/_includes/sidelist-introduction-v1.3.1.html b/_includes/sidelist-introduction-v1.3.1.html new file mode 100644 index 0000000..a4b6880 --- /dev/null +++ b/_includes/sidelist-introduction-v1.3.1.html @@ -0,0 +1 @@ +
  • Introduction
  • diff --git a/api/index-v1.3.1.md b/api/index-v1.3.1.md new file mode 100644 index 0000000..d9f70f8 --- /dev/null +++ b/api/index-v1.3.1.md @@ -0,0 +1,444 @@ +--- +layout: default-layout +needAutoGenerateSidebar: true +needGenerateH3Content: true +noTitleIndex: false +title: Mobile Document Scanner JS Edition - API Reference +keywords: Documentation, Mobile Document Scanner, Web, JS Edition, Dynamsoft Document Scanner, API, APIs +breadcrumbText: API References +description: Mobile Document Scanner JS Edition - API Reference +--- + +# Mobile Document Scanner API Reference + +The `DocumentScanner` class handles the document scanning process, including image capture, correction, and result display. + + + +## Constructor + +### `DocumentScanner` + +#### Syntax +```typescript +new DocumentScanner(config: DocumentScannerConfig) +``` + +#### Parameters +- `config` ([`DocumentScannerConfig`](#documentscannerconfig)) : Configuration settings for the scanner, including license, container, view settings and more. + +#### Example + +```html +
    +``` + +```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 + +### `launch()` + +Starts the **document scanning workflow**. + +#### Syntax +```typescript +async launch(file?: File): Promise +``` + +#### Returns +- A `Promise` resolving to a [`DocumentResult`](#documentresult) object. + +#### Example +```javascript +const result = await documentScanner.launch(); + +if (result?.correctedImageResult) { + resultContainer.innerHTML = ""; + const canvas = result.correctedImageResult.toCanvas(); + resultContainer.appendChild(canvas); +} else { + resultContainer.innerHTML = "

    No image scanned. Please try again.

    "; +} +``` + +### `dispose()` + +Cleans up resources and hides UI components. + +#### Syntax +```typescript +dispose(): void +``` + +#### Example +```javascript +documentScanner.dispose(); +console.log("Scanner resources released."); +``` + +## Configuration Interfaces + +### `DocumentScannerConfig` + +#### Syntax +```typescript +interface DocumentScannerConfig { + license?: string; + container?: HTMLElement | string; + scannerViewConfig?: DocumentScannerViewConfig; + resultViewConfig?: DocumentResultViewConfig; + correctionViewConfig?: DocumentCorrectionViewConfig; + templateFilePath?: string; + utilizedTemplateNames?: UtilizedTemplateNames; + engineResourcePaths: EngineResourcePaths; +} +``` + +#### Properties + +| Property | Type | Description | +| ----------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `license` | `string` | The license key for using the `DocumentScanner`. | +| `container` | ``HTMLElement | string`` | The container element or selector for the `DocumentScanner` UI. | +| `scannerViewConfig` | [`DocumentScannerViewConfig`](#documentscannerviewconfig) | Configuration settings for the scanner view. | +| `resultViewConfig` | [`DocumentResultViewConfig`](#documentresultviewconfig) | Configuration settings for the result view. | +| `correctionViewConfig` | [`DocumentCorrectionViewConfig`](#documentcorrectionviewconfig) | Configuration settings for the correction view. | +| `templateFilePath` | `string` | The file path to the document template used for scanning. You may set custom paths to self-host the template, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | +| `utilizedTemplateNames` | [`UtilizedTemplateNames`](#utilizedtemplatenames) | Specifies detection and correction templates. You may set custom names to self-host resources, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | +| `engineResourcePaths` | [`EngineResourcePaths`](#engineresourcepaths) | Paths to the necessary resources for the scanning engine. You may set custom paths to self-host resources, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | + +#### Example +```javascript +const config = { + license: "YOUR_LICENSE_KEY_HERE", + scannerViewConfig: { + cameraEnhancerUIPath: "./dist/document-scanner.ui.html", // Use the local file + }, + engineResourcePaths: { + std: "./dist/libs/dynamsoft-capture-vision-std/dist/", + dip: "./dist/libs/dynamsoft-image-processing/dist/", + core: "./dist/libs/dynamsoft-core/dist/", + license: "./dist/libs/dynamsoft-license/dist/", + cvr: "./dist/libs/dynamsoft-capture-vision-router/dist/", + ddn: "./dist/libs/dynamsoft-document-normalizer/dist/", + }, +}; +``` + +### `DocumentScannerViewConfig` + +Configures the scanner view for capturing documents. + +#### Syntax +```typescript +interface DocumentScannerViewConfig { + templateFilePath?: string; + cameraEnhancerUIPath?: string; + container?: HTMLElement | string; + utilizedTemplateNames?: UtilizedTemplateNames; + enableAutoCropMode?: boolean; + enableSmartCaptureMode?: boolean; + scanRegion: ScanRegion; + minVerifiedFramesForAutoCapture: number; + showSubfooter?: boolean; + showPoweredByDynamsoft?: boolean; +} +``` + +#### Properties + +| Property | Type | Description | +| --------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `templateFilePath` | `string` | Path to a Capture Vision template for scanning configuration. | +| `cameraEnhancerUIPath` | `string` | Path to the UI (`.html` template file) for the scanner view. You may set custom paths to self-host or customize the template, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | +| `container` | `HTMLElement` | The container element for the scanner view. | +| `utilizedTemplateNames` | [`UtilizedTemplateNames`](#utilizedtemplatenames) | Capture Vision template names for detection and correction. | +| `enableAutoCropMode` | `boolean` | The default auto-crop mode state. | +| `enableSmartCaptureMode` | `boolean` | The default smart capture mode state. | +| `scanRegion` | [`ScanRegion`](#scanregion) | Defines the region within the viewport to detect documents. | +| `minVerifiedFramesForAutoCapture` | `number` | The minimum number of camera frames to detect document boundaries on Smart Capture mode. | +| `showSubfooter` | `boolean` | Mode selector menu visibility. | +| `showPoweredByDynamsoft` | `boolean` | Visibility of the Dynamsoft branding message. | + +#### Example +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace with your actual license key + scannerViewConfig: { + cameraEnhancerUIPath: "../dist/document-scanner.ui.html", // Use the local file + }, +}); +``` + +### `DocumentCorrectionViewConfig` + +Configures the correction view for adjusting scanned documents, including toolbar buttons and event handlers for completion. + +#### Syntax +```typescript +interface DocumentCorrectionViewConfig { + container?: HTMLElement; + toolbarButtonsConfig?: DocumentCorrectionViewToolbarButtonsConfig; + onFinish?: (result: DocumentResult) => void; +} +``` + +#### Properties + +| Property | Type | Description | +| ---------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------- | +| `container` | `HTMLElement` | The container element for the correction view. | +| `toolbarButtonsConfig` | [`DocumentCorrectionViewToolbarButtonsConfig`](#documentcorrectionviewtoolbarbuttonsconfig) | Configuration for toolbar buttons in the correction view. | +| `onFinish` | `(result: DocumentResult) => void` | Callback function triggered when correction is finished. | + +#### Example +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + correctionViewConfig: { + onFinish: (result) => { + const canvas = result.correctedImageResult.toCanvas(); + resultContainer.appendChild(canvas); + } + } +}); +``` + +### `DocumentResultViewConfig` + +Configures the result view for reviewing scanned documents, including toolbar buttons and event handlers for uploads and completion. + +#### Syntax +```typescript +interface DocumentResultViewConfig { + container?: HTMLElement; + toolbarButtonsConfig?: DocumentResultViewToolbarButtonsConfig; + onDone?: (result: DocumentResult) => Promise; + onUpload?: (result: DocumentResult) => Promise; +} +``` + +#### Properties + +| Property | Type | Description | +| ---------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| `container` | `HTMLElement` | The container element for the result view. | +| `toolbarButtonsConfig` | [`DocumentResultViewToolbarButtonsConfig`](#documentresultviewtoolbarbuttonsconfig) | Configuration for toolbar buttons in the result view. | +| `onDone` | `(result: DocumentResult) => Promise` | Callback function triggered when scanning is done. | +| `onUpload` | `(result: DocumentResult) => Promise` | Callback function triggered when uploading the scan result. | + +#### Example +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + resultViewConfig: { + onDone: async (result) => + { + const canvas = result.correctedImageResult.toCanvas(); + resultContainer.appendChild(canvas); + } + } +}); +``` + +### `DocumentResult` + +Represents the output of a scan, including the original and corrected images, detected boundaries, and scan status. + +#### Syntax +```typescript +interface DocumentResult { + status: ResultStatus; + correctedImageResult?: NormalizedImageResultItem | DSImageData; + originalImageResult?: OriginalImageResultItem["imageData"]; + detectedQuadrilateral?: Quadrilateral; +} +``` + +#### Properties + +| Property | Type | Description | +| ----------------------- | ------------------------------------------- | ------------------------------------------------------------ | +| `status` | `ResultStatus` | The status of the document scan (success, failed, canceled). | +| `originalImageResult` | `OriginalImageResultItem["imageData"]` | The original captured image before correction. | +| `correctedImageResult` | ``NormalizedImageResultItem | DSImageData`` | The processed (corrected) image. | +| `detectedQuadrilateral` | `Quadrilateral` | The detected document boundaries. | + +### `ScanRegion` + +Describes the scan region within the viewfinder for document scanning: + +1. Use the `ratio` property to set the height-to-width of the rectangular scanning region, then scale the rectangle up to fit within the viewfinder. +2. Translate the rectangular up by the number of pixels specified by `regionBottomMargin`. +3. Create a visual border for the scanning region boundary on the viewfinder with a given stroke width in pixels, and a stroke color. + +#### Syntax +```typescript +interface ScanRegion { + ratio: { + width: number; + height: number; + }; + regionBottomMargin: number; // Bottom margin calculated in pixel + style: { + strokeWidth: number; + strokeColor: string; + }; +} +``` + +#### Properties + +| Property | Type | Description | +| -------------------- | -------- | ---------------------------------------------------------- | +| `ratio` | `object` | The aspect ratio of the rectangular scan region. | +| »`height` | `number` | The height of the rectangular scan region. | +| »`width` | `number` | The width of the rectangular scan region. | +| `regionBottomMargin` | `number` | Bottom margin below the scan region measured in pixels. | +| `style` | `object` | The styling for the scan region outline in the viewfinder. | +| »`strokeWidth` | `number` | The pixel width of the outline of the scan region. | +| »`strokeColor` | `string` | The color of the outline of the scan region. | + +#### Example + +Create a scan region with a height-to-width ratio of 3:2, translated upwards by 20 pixels, with a green, 3 pixel-wide border in the viewfinder: + +```javascript +scanRegion { + ratio: { + width: 2, + height: 3, + }, + regionBottomMargin: 20, + style: { + strokeWidth: 3, + strokeColor: "green", + }, +} +``` + +## Toolbar Button Configurations + +### `ToolbarButtonConfig` + +A simplified configuration type for toolbar buttons. + +#### Syntax +```typescript +export type ToolbarButtonConfig = Pick<"icon" | "label" | "isHidden">; +``` + +#### Properties + +| Property | Type | Description | +| ---------- | -------------------- | ----------------------------------- | +| `icon` | `string` | The icon displayed on the button. | +| `label` | `string` | The text label for the button. | +| `isHidden` | `boolean` (optional) | Determines if the button is hidden. | + +#### Example +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + correctionViewConfig: { + toolbarButtonsConfig: { + fullImage: { + isHidden: true + }, + detectBorders: { + icon: "path/to/new_icon.png", // Change to the actual path of the new icon + label: "Custom Label" + } + } + } +}); +``` + +### Configurable Buttons Per Each View + +#### DocumentCorrectionViewToolbarButtonsConfig + +##### Syntax +```typescript +interface DocumentCorrectionViewToolbarButtonsConfig { + fullImage?: ToolbarButtonConfig; + detectBorders?: ToolbarButtonConfig; + apply?: ToolbarButtonConfig; +} +``` + +#### DocumentResultViewToolbarButtonsConfig + +##### Syntax +```typescript +interface DocumentResultViewToolbarButtonsConfig { + retake?: ToolbarButtonConfig; + correct?: ToolbarButtonConfig; + share?: ToolbarButtonConfig; + upload?: ToolbarButtonConfig; + done?: ToolbarButtonConfig; +} +``` + +## Assisting Interfaces + +### `UtilizedTemplateNames` + +[Dynamsoft Capture Vision template](https://www.dynamsoft.com/capture-vision/docs/core/parameters/file/capture-vision-template.html?lang=javascript) names for detection and correction. This typically does not need to be set, as DDS uses the default template. + +#### Syntax +```typescript +interface UtilizedTemplateNames { + detect: string; + normalize: string; +} +``` + +### `EngineResourcePaths` + +Paths to extra resources such as `.wasm` engine files. The default paths point to CDNs and so may be left unset. You may set custom paths to self-host resources, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. + +#### Syntax +```typescript +interface EngineResourcePaths { + "rootDirectory"?: string; + "std"?: string | PathInfo; + "dip"?: string | PathInfo; + "dnn"?: string | PathInfo; + "core"?: string | PathInfo; + "license"?: string | PathInfo; + "cvr"?: string | PathInfo; + "utility"?: string | PathInfo; + "dbr"?: string | PathInfo; + "dlr"?: string | PathInfo; + "ddn"?: string | PathInfo; + "dcp"?: string | PathInfo; + "dce"?: string | PathInfo; + "dlrData"?: string | PathInfo; + "ddv"?: string | PathInfo; + "dwt"?: string | DwtInfo; +} +``` diff --git a/api/index.md b/api/index.md index d9f70f8..7274996 100644 --- a/api/index.md +++ b/api/index.md @@ -11,13 +11,15 @@ description: Mobile Document Scanner JS Edition - API Reference # Mobile Document Scanner API Reference -The `DocumentScanner` class handles the document scanning process, including image capture, correction, and result display. +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. @@ -34,45 +37,98 @@ The `DocumentScanner` class handles the document scanning process, including ima ### `DocumentScanner` +Create a DocumentScanner instance with settings specified by a `DocumentScannerConfig` object. + +The `DocumentScanner` class 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. + #### Syntax ```typescript new DocumentScanner(config: DocumentScannerConfig) ``` #### Parameters -- `config` ([`DocumentScannerConfig`](#documentscannerconfig)) : Configuration settings for the scanner, including license, container, view settings and more. +- `config` ([`DocumentScannerConfig`](#documentscannerconfig)) : Configuration settings for the scanner. You must set a valid license key with the `license` property. See [`DocumentScannerConfig`](#documentscannerconfig) for a complete description. #### Example +HTML: ```html
    ``` +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 + container: document.getElementById("myDocumentScannerContainer") // Use this container for the scanner view } }); ``` +#### Example: 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(); +``` + ## Methods ### `launch()` -Starts the **document scanning workflow**. +Start the document scanning workflow. + +This is the primary method for initiating document scanning. It performs the following: +1. Automatically calls `initialize()` if not already initialized +2. Opens the camera and displays the `DocumentScannerView` (unless a file is provided) +3. Guides the user through the configured workflow (scan → correction → result) +4. Returns the final `DocumentResult` when the workflow completes +5. Automatically calls `dispose()` to clean up resources + +#### Scanning Modes +- **Single-scan mode (default)**: Captures one document and returns the result +- **Continuous scanning mode** (`enableContinuousScanning`): Loops after each scan, invoking `onDocumentScanned` with each result. The loop continues until the user 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`. #### Syntax ```typescript async launch(file?: File): Promise ``` +#### Parameters +- `file` (optional): Image file to process instead of using the camera + #### Returns -- A `Promise` resolving to a [`DocumentResult`](#documentresult) object. +- A `Promise` resolving to a [`DocumentResult`](#documentresult) object, which includes: + - `status`: Scan status (success, cancelled, or failed) + - `correctedImageResult`: Perspective-corrected document image + - `originalImageResult`: Original captured image + - `detectedQuadrilateral`: Detected document boundaries -#### Example +#### Throws +- `Error` if a capture session is already in progress + +#### Example: Basic Single-Scan Usage ```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE" +}); + const result = await documentScanner.launch(); if (result?.correctedImageResult) { @@ -84,58 +140,224 @@ if (result?.correctedImageResult) { } ``` +#### Example: 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); +``` + +#### Example: 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(); +``` + +### `initialize()` + +> [!NOTE] +> This method is called automatically by `launch()` and typically does not need to be invoked manually. + +Initialize the DocumentScanner by setting up Dynamsoft Capture Vision resources and view components. + +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. + +#### Syntax +```typescript +async initialize(): Promise<{ + resources: SharedResources; + components: { + scannerView?: DocumentScannerView; + correctionView?: DocumentCorrectionView; + scanResultView?: DocumentResultView; + }; +}> +``` + +#### Returns +- 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`, `correctionView`, `scanResultView`) + +#### Throws +- `Error` 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); +} +``` + +### `stopContinuousScanning()` + +Stop continuous scanning and exit the scanning loop. + +When called with `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 + +#### Syntax +```typescript +stopContinuousScanning(): void +``` + +#### Example: 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 +``` + +#### Example: 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 +``` + ### `dispose()` -Cleans up resources and hides UI components. +> [!NOTE] +> 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. + +Clean up and release all resources used by the DocumentScanner. + +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. #### Syntax ```typescript dispose(): void ``` -#### Example +#### 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."); +console.log("Scanner resources released"); ``` ## Configuration Interfaces ### `DocumentScannerConfig` +The `DocumentScannerConfig` interface passes settings to the `DocumentScanner` constructor to apply a comprehensive set of UI and business logic customizations. + +Only advanced scenarios require editing the UI template or MDS source code. `license` is the only property required to instantiate a `DocumentScanner` object. MDS uses sensible default values for all other omitted properties. + #### Syntax ```typescript interface DocumentScannerConfig { license?: string; container?: HTMLElement | string; + templateFilePath?: string; + utilizedTemplateNames?: UtilizedTemplateNames; + engineResourcePaths?: EngineResourcePaths; scannerViewConfig?: DocumentScannerViewConfig; resultViewConfig?: DocumentResultViewConfig; correctionViewConfig?: DocumentCorrectionViewConfig; - templateFilePath?: string; - utilizedTemplateNames?: UtilizedTemplateNames; - engineResourcePaths: EngineResourcePaths; + showResultView?: boolean; + showCorrectionView?: boolean; + enableContinuousScanning?: boolean; + enableFrameVerification?: boolean; + onDocumentScanned?: (result: DocumentResult) => void | Promise; + onThumbnailClicked?: (result: DocumentResult) => void | Promise; } ``` #### Properties -| Property | Type | Description | -| ----------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `license` | `string` | The license key for using the `DocumentScanner`. | -| `container` | ``HTMLElement | string`` | The container element or selector for the `DocumentScanner` UI. | -| `scannerViewConfig` | [`DocumentScannerViewConfig`](#documentscannerviewconfig) | Configuration settings for the scanner view. | -| `resultViewConfig` | [`DocumentResultViewConfig`](#documentresultviewconfig) | Configuration settings for the result view. | -| `correctionViewConfig` | [`DocumentCorrectionViewConfig`](#documentcorrectionviewconfig) | Configuration settings for the correction view. | -| `templateFilePath` | `string` | The file path to the document template used for scanning. You may set custom paths to self-host the template, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | -| `utilizedTemplateNames` | [`UtilizedTemplateNames`](#utilizedtemplatenames) | Specifies detection and correction templates. You may set custom names to self-host resources, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | -| `engineResourcePaths` | [`EngineResourcePaths`](#engineresourcepaths) | Paths to the necessary resources for the scanning engine. You may set custom paths to self-host resources, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | - -#### Example +| Property | Type | Default | Description | +| -------------------------- | --------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `license` | `string` | - | **Required.** The license key for using the `DocumentScanner`. This is the only required property to instantiate a `DocumentScanner` object. | +| `container` | ``HTMLElement \| string`` | - | The container element or selector for the `DocumentScanner` UI. | +| `templateFilePath` | `string` | - | The file path to the Capture Vision template used for document scanning. You may set custom paths to self-host the template or fully self-host MDS - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | +| `utilizedTemplateNames` | [`UtilizedTemplateNames`](#utilizedtemplatenames) | See [UtilizedTemplateNames](#utilizedtemplatenames) | Capture Vision template names for document detection and normalization. This typically does not need to be set as MDS provides a default template for general use. You may set custom names to self-host resources or fully self-host MDS - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | +| `engineResourcePaths` | [`EngineResourcePaths`](#engineresourcepaths) | CDN URLs | Paths to the necessary engine resources (such as `.wasm` files) for the scanning engine. The default paths point to CDNs so this may be left unset. You may set custom paths to self-host resources or fully self-host MDS - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | +| `scannerViewConfig` | [`DocumentScannerViewConfig`](#documentscannerviewconfig) | - | Configuration settings for the `DocumentScannerView`. See [workflow customization]({{ site.guide }}index.html#workflow-customization) for details. | +| `resultViewConfig` | [`DocumentResultViewConfig`](#documentresultviewconfig) | - | Configuration settings for the `DocumentResultView`. See [workflow customization]({{ site.guide }}index.html#workflow-customization) for details. | +| `correctionViewConfig` | [`DocumentCorrectionViewConfig`](#documentcorrectionviewconfig) | - | Configuration settings for the `DocumentCorrectionView`. | +| `showResultView` | `boolean` | `true` | Sets the visibility of the `DocumentResultView`. | +| `showCorrectionView` | `boolean` | `true` | Sets the visibility of the `DocumentCorrectionView`. | +| `enableContinuousScanning` | `boolean` | `false` | Enable continuous scanning mode where the scanner loops back after each successful scan instead of exiting. `launch()` only resolves to the last scanned result. Use `onDocumentScanned` callback to get scan results. When enabled, the scanner automatically loops back to capture another document after each successful scan, the `onDocumentScanned` callback triggers after each scan with the result, users can exit by clicking the close button (X) or by calling `stopContinuousScanning()`, and the DocumentScanner only retains the most recent scan result. | +| `enableFrameVerification` | `boolean` | `true` | Enable automatic frame verification for best quality capture. When enabled, uses clarity detection and cross-filtering to automatically find the clearest frame. | +| `onDocumentScanned` | `(result: DocumentResult) => void \| Promise` | - | Callback invoked after each successful scan in continuous scanning mode. This callback is only called when `enableContinuousScanning` is true. The scanner loops back to capture another document after this callback completes. The callback receives a `DocumentResult` containing the original image, corrected image, detected boundaries, and scan status. | +| `onThumbnailClicked` | `(result: DocumentResult) => void \| Promise` | - | Callback invoked when the thumbnail preview is clicked in continuous scanning mode. This callback is only invoked when `enableContinuousScanning` is enabled, `showCorrectionView` is disabled, and `showResultView` is disabled. The thumbnail preview displays the most recently scanned document. By default, clicking it does nothing unless this callback is defined, allowing you to implement custom behavior such as re-editing the image. | + +#### Example: Basic Configuration ```javascript const config = { license: "YOUR_LICENSE_KEY_HERE", scannerViewConfig: { - cameraEnhancerUIPath: "./dist/document-scanner.ui.html", // Use the local file + cameraEnhancerUIPath: "./dist/document-scanner.ui.xml", // Use the local file }, engineResourcePaths: { std: "./dist/libs/dynamsoft-capture-vision-std/dist/", @@ -148,21 +370,53 @@ const config = { }; ``` +#### Example: Continuous Scanning with Callback +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + enableContinuousScanning: true, + onDocumentScanned: async (result) => { + // Process each scanned document + const canvas = result.correctedImageResult.toCanvas(); + document.getElementById("results").appendChild(canvas); + } +}); +``` + +#### Example: Thumbnail Click Handler +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + enableContinuousScanning: true, + showCorrectionView: false, + showResultView: false, + onThumbnailClicked: async (result) => { + // Handle thumbnail click event + console.log('Thumbnail clicked', result); + // Could open a custom editor, display metadata, etc. + } +}); +``` + ### `DocumentScannerViewConfig` -Configures the scanner view for capturing documents. +The `DocumentScannerViewConfig` interface passes settings to the `DocumentScanner` constructor through the `DocumentScannerConfig` to apply UI and business logic customizations for the `DocumentScannerView`. + +Simple scenarios do not require editing the UI template or MDS source code. MDS uses sensible default values for all omitted properties. #### Syntax ```typescript interface DocumentScannerViewConfig { - templateFilePath?: string; - cameraEnhancerUIPath?: string; container?: HTMLElement | string; + cameraEnhancerUIPath?: string; + templateFilePath?: string; utilizedTemplateNames?: UtilizedTemplateNames; - enableAutoCropMode?: boolean; + enableBoundsDetectionMode?: boolean; enableSmartCaptureMode?: boolean; - scanRegion: ScanRegion; - minVerifiedFramesForAutoCapture: number; + enableAutoCropMode?: boolean; + enableFrameVerification?: boolean; + scanRegion?: ScanRegion; + minVerifiedFramesForAutoCapture?: number; showSubfooter?: boolean; showPoweredByDynamsoft?: boolean; } @@ -170,49 +424,59 @@ interface DocumentScannerViewConfig { #### Properties -| Property | Type | Description | -| --------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `templateFilePath` | `string` | Path to a Capture Vision template for scanning configuration. | -| `cameraEnhancerUIPath` | `string` | Path to the UI (`.html` template file) for the scanner view. You may set custom paths to self-host or customize the template, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | -| `container` | `HTMLElement` | The container element for the scanner view. | -| `utilizedTemplateNames` | [`UtilizedTemplateNames`](#utilizedtemplatenames) | Capture Vision template names for detection and correction. | -| `enableAutoCropMode` | `boolean` | The default auto-crop mode state. | -| `enableSmartCaptureMode` | `boolean` | The default smart capture mode state. | -| `scanRegion` | [`ScanRegion`](#scanregion) | Defines the region within the viewport to detect documents. | -| `minVerifiedFramesForAutoCapture` | `number` | The minimum number of camera frames to detect document boundaries on Smart Capture mode. | -| `showSubfooter` | `boolean` | Mode selector menu visibility. | -| `showPoweredByDynamsoft` | `boolean` | Visibility of the Dynamsoft branding message. | +| Property | Type | Default | Description | +| --------------------------------- | ------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `container` | ``HTMLElement \| string`` | - | The HTML container element or selector for the `DocumentScannerView` UI. | +| `cameraEnhancerUIPath` | `string` | CDN URL | Path to the UI definition file (`.xml`) for the `DocumentScannerView`. This typically does not need to be set as MDS provides a default template for general use. You may set custom paths to self-host or customize the template, or fully self-host MDS - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | +| `templateFilePath` | `string` | - | Path to the Capture Vision template file for scanning configuration. | +| `utilizedTemplateNames` | [`UtilizedTemplateNames`](#utilizedtemplatenames) | See [UtilizedTemplateNames](#utilizedtemplatenames) | Capture Vision template names for document detection and normalization. This typically does not need to be set as MDS provides a default template for general use. You may set custom names to self-host resources or fully self-host MDS - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) and [DCV templates](https://www.dynamsoft.com/capture-vision/docs/core/parameters/file/capture-vision-template.html?lang=javascript) for details. | +| `enableBoundsDetectionMode` | `boolean` | `true` | Set the document Bounds Detection mode effective upon entering the `DocumentScannerView` UI. Bounds Detection mode gets enabled when Smart Capture mode is enabled. | +| `enableSmartCaptureMode` | `boolean` | `false` | Set the Smart Capture mode effective upon entering the `DocumentScannerView` UI. Enabling Smart Capture mode also enables Bounds Detection mode. Smart Capture mode is enabled when Auto-Capture mode is enabled. | +| `enableAutoCropMode` | `boolean` | `false` | Set the Auto-Crop mode effective upon entering the `DocumentScannerView` UI. Enabling Auto-Crop mode also enables Smart Capture mode. | +| `enableFrameVerification` | `boolean` | `true` | Enable automatic frame verification for best quality capture. When enabled, track clarity scores to find the clearest frame. | +| `scanRegion` | [`ScanRegion`](#scanregion) | - | Define the region within the viewport to detect documents. See [`ScanRegion`](#scanregion) for details. | +| `minVerifiedFramesForAutoCapture` | `number` | `2` | Set the minimum number of camera frames to detect document boundaries in Smart Capture mode. Accepts integer values between 1 and 5, inclusive. | +| `showSubfooter` | `boolean` | `true` | Set the visibility of the mode selector menu. | +| `showPoweredByDynamsoft` | `boolean` | `true` | Set the visibility of the Dynamsoft branding message. | #### Example ```javascript const documentScanner = new Dynamsoft.DocumentScanner({ license: "YOUR_LICENSE_KEY_HERE", // Replace with your actual license key scannerViewConfig: { - cameraEnhancerUIPath: "../dist/document-scanner.ui.html", // Use the local file + cameraEnhancerUIPath: "../dist/document-scanner.ui.xml", // Use the local file + enableSmartCaptureMode: true, // Enable smart capture by default + minVerifiedFramesForAutoCapture: 3 // Stricter boundary detection threshold }, }); ``` ### `DocumentCorrectionViewConfig` -Configures the correction view for adjusting scanned documents, including toolbar buttons and event handlers for completion. +The `DocumentCorrectionViewConfig` interface passes settings to the `DocumentScanner` constructor through the `DocumentScannerConfig` to apply UI and business logic customizations for the `DocumentCorrectionView`. + +Only rare and edge-case scenarios require editing MDS source code. MDS uses sensible default values for all omitted properties. #### Syntax ```typescript interface DocumentCorrectionViewConfig { - container?: HTMLElement; + container?: HTMLElement | string; toolbarButtonsConfig?: DocumentCorrectionViewToolbarButtonsConfig; + templateFilePath?: string; + utilizedTemplateNames?: UtilizedTemplateNames; onFinish?: (result: DocumentResult) => void; } ``` #### Properties -| Property | Type | Description | -| ---------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------- | -| `container` | `HTMLElement` | The container element for the correction view. | -| `toolbarButtonsConfig` | [`DocumentCorrectionViewToolbarButtonsConfig`](#documentcorrectionviewtoolbarbuttonsconfig) | Configuration for toolbar buttons in the correction view. | -| `onFinish` | `(result: DocumentResult) => void` | Callback function triggered when correction is finished. | +| Property | Type | Default | Description | +| ----------------------- | ------------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `container` | ``HTMLElement \| string`` | - | The HTML container element or selector for the `DocumentCorrectionView` UI. | +| `toolbarButtonsConfig` | [`DocumentCorrectionViewToolbarButtonsConfig`](#documentcorrectionviewtoolbarbuttonsconfig) | - | Configure the appearance and labels of the buttons for the `DocumentCorrectionView` UI. See [`DocumentCorrectionViewToolbarButtonsConfig`](#documentcorrectionviewtoolbarbuttonsconfig) for details. | +| `templateFilePath` | `string` | - | Path to the Capture Vision template file for scanning configuration. This typically does not need to be set as MDS provides a default template for general use. You may set custom paths to self-host resources or fully self-host MDS - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. | +| `utilizedTemplateNames` | [`UtilizedTemplateNames`](#utilizedtemplatenames) | See [UtilizedTemplateNames](#utilizedtemplatenames) | Capture Vision template names for document detection and normalization. This typically does not need to be set as MDS provides a default template for general use. You may set custom names to self-host resources or fully self-host MDS - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) and [DCV templates](https://www.dynamsoft.com/capture-vision/docs/core/parameters/file/capture-vision-template.html?lang=javascript) for details. | +| `onFinish` | `(result: DocumentResult) => void` | - | Handler called when the user clicks the "Apply" button. The handler receives a `DocumentResult` of the scan, including the original image, corrected image, detected boundaries, and scan status. | #### Example ```javascript @@ -229,12 +493,14 @@ const documentScanner = new Dynamsoft.DocumentScanner({ ### `DocumentResultViewConfig` -Configures the result view for reviewing scanned documents, including toolbar buttons and event handlers for uploads and completion. +The `DocumentResultViewConfig` interface passes settings to the `DocumentScanner` constructor through the `DocumentScannerConfig` to apply UI and business logic customizations for the `DocumentResultView`. + +Only rare and edge-case scenarios require editing MDS source code. MDS uses sensible default values for all omitted properties. #### Syntax ```typescript interface DocumentResultViewConfig { - container?: HTMLElement; + container?: HTMLElement | string; toolbarButtonsConfig?: DocumentResultViewToolbarButtonsConfig; onDone?: (result: DocumentResult) => Promise; onUpload?: (result: DocumentResult) => Promise; @@ -243,20 +509,19 @@ interface DocumentResultViewConfig { #### Properties -| Property | Type | Description | -| ---------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------- | -| `container` | `HTMLElement` | The container element for the result view. | -| `toolbarButtonsConfig` | [`DocumentResultViewToolbarButtonsConfig`](#documentresultviewtoolbarbuttonsconfig) | Configuration for toolbar buttons in the result view. | -| `onDone` | `(result: DocumentResult) => Promise` | Callback function triggered when scanning is done. | -| `onUpload` | `(result: DocumentResult) => Promise` | Callback function triggered when uploading the scan result. | +| Property | Type | Default | Description | +| ---------------------- | ----------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `container` | ``HTMLElement \| string`` | - | The HTML container element or selector for the `DocumentResultView` UI. | +| `toolbarButtonsConfig` | [`DocumentResultViewToolbarButtonsConfig`](#documentresultviewtoolbarbuttonsconfig) | - | Configure the appearance and labels of the buttons for the `DocumentResultView` UI. See [`DocumentResultViewToolbarButtonsConfig`](#documentresultviewtoolbarbuttonsconfig). | +| `onDone` | `(result: DocumentResult) => Promise` | - | Handler called when the user clicks the "Done" button. The handler receives a `DocumentResult` of the scan, including the original image, corrected image, detected boundaries, and scan status. | +| `onUpload` | `(result: DocumentResult) => Promise` | - | Handler called when the user clicks the "Upload" button. The handler receives a `DocumentResult` of the scan, including the original image, corrected image, detected boundaries, and scan status. | #### Example ```javascript const documentScanner = new Dynamsoft.DocumentScanner({ license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key resultViewConfig: { - onDone: async (result) => - { + onDone: async (result) => { const canvas = result.correctedImageResult.toCanvas(); resultContainer.appendChild(canvas); } @@ -266,34 +531,35 @@ const documentScanner = new Dynamsoft.DocumentScanner({ ### `DocumentResult` -Represents the output of a scan, including the original and corrected images, detected boundaries, and scan status. +Represent the output of a scan, including the original image, the corrected image, detected boundaries, and scan status. #### Syntax ```typescript interface DocumentResult { status: ResultStatus; - correctedImageResult?: NormalizedImageResultItem | DSImageData; - originalImageResult?: OriginalImageResultItem["imageData"]; + correctedImageResult?: DeskewedImageResultItem; + originalImageResult?: DSImageData; detectedQuadrilateral?: Quadrilateral; } ``` #### Properties -| Property | Type | Description | -| ----------------------- | ------------------------------------------- | ------------------------------------------------------------ | -| `status` | `ResultStatus` | The status of the document scan (success, failed, canceled). | -| `originalImageResult` | `OriginalImageResultItem["imageData"]` | The original captured image before correction. | -| `correctedImageResult` | ``NormalizedImageResultItem | DSImageData`` | The processed (corrected) image. | -| `detectedQuadrilateral` | `Quadrilateral` | The detected document boundaries. | +| Property | Type | Description | +| ----------------------- | -------------------------- | ------------------------------------------------------------ | +| `status` | [`ResultStatus`](#resultstatus) | The status of the document scan (success, failed, canceled). | +| `correctedImageResult` | `DeskewedImageResultItem` | The processed (corrected) image. | +| `originalImageResult` | `DSImageData` | The original captured image before correction. | +| `detectedQuadrilateral` | `Quadrilateral` | The detected document boundaries. | ### `ScanRegion` -Describes the scan region within the viewfinder for document scanning: +Set the scan region within the `DocumentScannerView` viewfinder for document scanning from the `DocumentScannerViewConfig`. -1. Use the `ratio` property to set the height-to-width of the rectangular scanning region, then scale the rectangle up to fit within the viewfinder. -2. Translate the rectangular up by the number of pixels specified by `regionBottomMargin`. -3. Create a visual border for the scanning region boundary on the viewfinder with a given stroke width in pixels, and a stroke color. +MDS determines the scan region with the following steps: +1. Use `ratio` to set the height-to-width ratio of the rectangular scanning region, then scale the rectangle up to fit within the viewfinder. +2. Translate the rectangle upward by the number of pixels specified by `regionBottomMargin`. +3. Create a visual border for the scanning region boundary on the viewfinder with a given stroke width in pixels and stroke color. #### Syntax ```typescript @@ -302,7 +568,7 @@ interface ScanRegion { width: number; height: number; }; - regionBottomMargin: number; // Bottom margin calculated in pixel + regionBottomMargin: number; // Bottom margin calculated in pixels style: { strokeWidth: number; strokeColor: string; @@ -315,8 +581,8 @@ interface ScanRegion { | Property | Type | Description | | -------------------- | -------- | ---------------------------------------------------------- | | `ratio` | `object` | The aspect ratio of the rectangular scan region. | -| »`height` | `number` | The height of the rectangular scan region. | | »`width` | `number` | The width of the rectangular scan region. | +| »`height` | `number` | The height of the rectangular scan region. | | `regionBottomMargin` | `number` | Bottom margin below the scan region measured in pixels. | | `style` | `object` | The styling for the scan region outline in the viewfinder. | | »`strokeWidth` | `number` | The pixel width of the outline of the scan region. | @@ -327,7 +593,7 @@ interface ScanRegion { Create a scan region with a height-to-width ratio of 3:2, translated upwards by 20 pixels, with a green, 3 pixel-wide border in the viewfinder: ```javascript -scanRegion { +scanRegion: { ratio: { width: 2, height: 3, @@ -346,18 +612,21 @@ scanRegion { A simplified configuration type for toolbar buttons. +This type allows you to customize the appearance and behavior of toolbar buttons by providing a subset of properties from the complete `ToolbarButton` interface. + #### Syntax ```typescript -export type ToolbarButtonConfig = Pick<"icon" | "label" | "isHidden">; +export type ToolbarButtonConfig = Pick; ``` #### Properties -| Property | Type | Description | -| ---------- | -------------------- | ----------------------------------- | -| `icon` | `string` | The icon displayed on the button. | -| `label` | `string` | The text label for the button. | -| `isHidden` | `boolean` (optional) | Determines if the button is hidden. | +| Property | Type | Description | +| ----------- | --------- | ----------------------------------------------------------------- | +| `icon` | `string` | Path or data URL to the button icon image. | +| `label` | `string` | Text label displayed below the button icon. | +| `className` | `string` | Additional CSS class name to apply to the button element. | +| `isHidden` | `boolean` | Flag indicating whether the button is hidden from the toolbar. | #### Example ```javascript @@ -377,20 +646,110 @@ const documentScanner = new Dynamsoft.DocumentScanner({ }); ``` +### `ToolbarButton` + +Interface defining the properties and behavior of a toolbar button. + +This interface is used internally to create toolbar buttons in the `DocumentResultView` and `DocumentCorrectionView`. While developers typically use `ToolbarButtonConfig` to customize buttons, this interface defines the complete button structure including the click handler. See [Configurable Buttons Per Each View](#configurable-buttons-per-each-view) for examples. + +#### Syntax +```typescript +interface ToolbarButton { + id: string; + icon: string; + label: string; + onClick?: () => void | Promise; + className?: string; + isDisabled?: boolean; + isHidden?: boolean; +} +``` + +#### Properties + +| Property | Type | Default | Description | +| ------------ | ----------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | `string` | - | Unique identifier for the button. | +| `icon` | `string` | - | Path or data URL to the button icon image. | +| `label` | `string` | - | Text label displayed below the button icon. | +| `onClick` | `() => void \| Promise` | - | Click handler function invoked when the button is clicked. This handler can be synchronous or asynchronous. When provided through `ToolbarButtonConfig`, it overrides the button's default behavior. | +| `className` | `string` | - | Additional CSS class name to apply to the button element. | +| `isDisabled` | `boolean` | `false` | Flag indicating whether the button is disabled (non-interactive). | +| `isHidden` | `boolean` | `false` | Flag indicating whether the button is hidden from the toolbar. | + ### Configurable Buttons Per Each View -#### DocumentCorrectionViewToolbarButtonsConfig +#### `DocumentCorrectionViewToolbarButtonsConfig` + +Configuration interface for customizing toolbar buttons in the `DocumentCorrectionView`. + +This interface allows you to customize the appearance and behavior of the toolbar buttons displayed in the `DocumentCorrectionView`. Each button can be configured using a `ToolbarButtonConfig` object to modify its icon, label, CSS class, or visibility. + +The behaviors described for each button below are the default behaviors. You can override the default behavior by providing a custom `onClick` handler through the `ToolbarButtonConfig`. ##### Syntax ```typescript interface DocumentCorrectionViewToolbarButtonsConfig { + retake?: ToolbarButtonConfig; fullImage?: ToolbarButtonConfig; detectBorders?: ToolbarButtonConfig; apply?: ToolbarButtonConfig; } ``` -#### DocumentResultViewToolbarButtonsConfig +##### Properties + +| Property | Type | Description | +| --------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `retake` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the retake button. **Default behavior:** returns to the `DocumentScannerView` to capture a new image. | +| `fullImage` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the full image button. **Default behavior:** sets the document boundaries to match the full image dimensions. | +| `detectBorders` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the detect borders button. **Default behavior:** automatically detects document boundaries using the document detection algorithm. | +| `apply` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the apply button. **Default behavior:** applies the current boundary adjustments and proceeds with the workflow. In continuous scanning mode (`enableContinuousScanning`) when `DocumentResultView` is disabled, this button is labeled "Keep Scan" by default and returns to the `DocumentScannerView` for the next scan. Otherwise, it is labeled "Apply" when `DocumentResultView` is shown, or labeled "Done" otherwise. | + +##### Example: Customize Button Appearance +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + correctionViewConfig: { + toolbarButtonsConfig: { + fullImage: { + isHidden: true + }, + detectBorders: { + icon: "path/to/new_icon.png", + label: "Custom Label" + } + } + } +}); +``` + +##### Example: Override Button Behavior +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + correctionViewConfig: { + toolbarButtonsConfig: { + apply: { + label: "Confirm", + onClick: async () => { + // Custom confirmation logic + await validateBoundaries(); + console.log("Boundaries confirmed!"); + } + } + } + } +}); +``` + +#### `DocumentResultViewToolbarButtonsConfig` + +Configuration interface for customizing toolbar buttons in the `DocumentResultView`. + +This interface allows you to customize the appearance and behavior of the toolbar buttons displayed in the `DocumentResultView`. Each button can be configured using a `ToolbarButtonConfig` object to modify its icon, label, CSS class, or visibility. + +The behaviors described for each button below are the default behaviors. You can override the default behavior by providing a custom `onClick` handler through the `ToolbarButtonConfig`. ##### Syntax ```typescript @@ -403,11 +762,66 @@ interface DocumentResultViewToolbarButtonsConfig { } ``` +##### Properties + +| Property | Type | Description | +| --------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `retake` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the retake button. **Default behavior:** returns to the `DocumentScannerView` to capture a new image. | +| `correct` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the correct button. **Default behavior:** enters the `DocumentCorrectionView` to adjust document boundaries. | +| `share` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the share button. **Default behavior:** shares or downloads the scanned document. On mobile devices with Web Share API support, this button triggers the native share dialog. On desktop or devices without share support, it downloads the image instead. | +| `upload` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the upload button. **Default behavior:** triggers the `onUpload` callback. This button is only visible when `onUpload` is defined. | +| `done` | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the done button. **Default behavior:** completes the scanning workflow. In continuous scanning mode (`enableContinuousScanning`), this button is labeled "Keep Scan" by default and returns to the `DocumentScannerView` for the next scan. | + +##### Example: Customize Button Appearance +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + resultViewConfig: { + toolbarButtonsConfig: { + retake: { + isHidden: true + }, + share: { + icon: "path/to/new_icon.png", + label: "Custom Label" + } + } + } +}); +``` + +##### Example: Override Button Behavior +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + resultViewConfig: { + toolbarButtonsConfig: { + done: { + label: "Save", + onClick: async () => { + // Custom save logic + await saveToServer(documentScanner.result); + console.log("Document saved!"); + } + }, + share: { + onClick: async () => { + // Custom share logic + await sendViaEmail(documentScanner.result); + } + } + } + } +}); +``` + ## Assisting Interfaces ### `UtilizedTemplateNames` -[Dynamsoft Capture Vision template](https://www.dynamsoft.com/capture-vision/docs/core/parameters/file/capture-vision-template.html?lang=javascript) names for detection and correction. This typically does not need to be set, as DDS uses the default template. +Capture Vision template names for document detection and normalization. + +You may set custom names to self-host resources or fully self-host MDS. See [self-hosting resources]({{ site.guide }}index.html#self-host-resources) and [DCV templates](https://www.dynamsoft.com/capture-vision/docs/core/parameters/file/capture-vision-template.html?lang=javascript) for details. #### Syntax ```typescript @@ -417,6 +831,54 @@ interface UtilizedTemplateNames { } ``` +#### Default Value +```javascript +{ + detect: "DetectDocumentBoundaries_Default", + normalize: "NormalizeDocument_Default" +} +``` + +### `ResultStatus` + +Represents the status of a document scanning operation. + +#### Syntax +```typescript +type ResultStatus = { + code: EnumResultStatus; + message?: string; +}; +``` + +#### Properties + +| Property | Type | Description | +| --------- | ------------------------------------------- | --------------------------------------------------- | +| `code` | [`EnumResultStatus`](#enumresultstatus) | Status code indicating success, cancellation, or failure. | +| `message` | `string` | Optional message providing additional details. | + +### `EnumResultStatus` + +Enumeration of possible result status codes. + +#### Syntax +```typescript +enum EnumResultStatus { + RS_SUCCESS = 0, + RS_CANCELLED = 1, + RS_FAILED = 2 +} +``` + +#### Values + +| Value | Code | Description | +| -------------- | ---- | ---------------------------------------------- | +| `RS_SUCCESS` | 0 | The scanning operation completed successfully. | +| `RS_CANCELLED` | 1 | The scanning operation was cancelled by user. | +| `RS_FAILED` | 2 | The scanning operation failed. | + ### `EngineResourcePaths` Paths to extra resources such as `.wasm` engine files. The default paths point to CDNs and so may be left unset. You may set custom paths to self-host resources, or host MDS fully offline - see [self-hosting resources]({{ site.guide }}index.html#self-host-resources) for details. diff --git a/guide/angular-v1.3.1.md b/guide/angular-v1.3.1.md new file mode 100644 index 0000000..523a394 --- /dev/null +++ b/guide/angular-v1.3.1.md @@ -0,0 +1,122 @@ +--- +layout: default-layout +needAutoGenerateSidebar: true +needGenerateH3Content: true +noTitleIndex: false +breadcrumbText: Angular Guide +title: Mobile Document Scanner JS Edition - Angular +keywords: Documentation, Mobile Document Scanner, Web, JS Edition, Dynamsoft Document Scanner, Angular +description: Mobile Document Scanner JS Edition Angular User Guide +--- + +# Mobile Document Scanner - Angular + +> [!IMPORTANT] +> This article builds on the prerequisite [MDS developer guide]({{ site.guide }}index.html) for plain JavaScript; please read it before proceeding. + +Mobile Document Scanner integrates easily with Angular applications. Just as in plain JavaScript, you can add document scanning in your **Angular application** in just a few lines of code, and achieve most customizations through the same accessible configuration object. + +## Features + +- Easy integration with pre-built UI +- Render MDS inside an Angular component +- **Standalone components** (modern Angular architecture) +- Capture and process documents from video stream +- Automatic document detection and cropping +- Mobile-optimized scanning interface +- TypeScript support with type definitions + +## Requirements + +- **Node.js 20.19.0 or later** +- [Base requirements]({{ site.introduction }}index.html#system-requirements) + +## License + +### Get a Trial License + +Try **MDS** by requesting a trial license through our [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?product=mwc&utm_source=github_angular_readme). You can renew the license twice for up to a total of two months of free access. + +### Get a Full License + +[Contact us](https://www.dynamsoft.com/company/contact?product=mwc&utm_source=github_angular_readme) to purchase a full license. + +## Quick Start + +We publish **MDS** library files on [npm](https://www.npmjs.com/package/dynamsoft-document-scanner) to make them simple to reference from a CDN. We reference the library files in our _ready-made_ Hello World sample for Angular included in our GitHub source repository: + +1. Download **MDS** from [GitHub](https://github.com/Dynamsoft/document-scanner-javascript) as a compressed folder. + +2. Extract the contents of the archive, and open the extracted directory in a code editor. + +3. Set your [license key](#get-a-trial-license) in the **Angular framework sample**: + 1. Open the sample at [`/samples/frameworks/angular/src/app/app.component.ts`](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/document-scanner-javascript-dev/samples/frameworks/angular/src/app/app.component.ts). + 2. Search for `"YOUR_LICENSE_KEY_HERE"`, then replace it with your actual license key. + +### Install Dependencies + +```bash +npm install +``` + +### Start the App + +```bash +ng serve +``` + +> [!TIP] +> If you installed Angular locally, you can call the local version with +> ```shell +> npx ng serve +> ``` + +Open `http://localhost:4200/` to view the sample app. + +> [!NOTE] +> Secure context requires HTTPS to provide camera access, but Angular CLI serves over HTTP by default. For mobile testing, you may need to configure HTTPS or use a reverse proxy. + +## Self-Host Resources + +You can self host the resources for the Hello World by following a few simple steps. Refer to the [plain JavaScript self-hosting guide]({{ site.guide }}index.html#quick-start) for details. + +### Set File Paths + +First we set MDS to look resource paths where we will place the resources later: + +```typescript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + scannerViewConfig: { + cameraEnhancerUIPath: "dist/libs/dynamsoft-document-scanner/dist/document-scanner.ui.html", + }, + engineResourcePaths: { + rootDirectory: "dist/libs/" + }, +}); +``` + +### Move Resources + +Now, add a script (`get-libs`) to automatically move the resources to their destination when building the project (`build`) in `samples/framework/angular/package.json`: + +```json +"scripts": { + "ng": "ng", + "start": "ng serve --ssl", + "build": "ng build && npm run get-libs", + "get-libs": "npm install --no-save dynamsoft-capture-vision-data dynamsoft-capture-vision-bundle && npx mkdirp /dist/libs && npx cpx 'node_modules/dynamsoft-*/**/*' dist/libs/ --dereference", + "watch": "ng build --watch --configuration development", + "test": "ng test" +}, +``` + +When building, **swap the build script** from `ng build` to `npm run build`. Continue using `ng serve` to serve the application. + +## Customization + +Please check the official [documentation]({{ site.guide }}index.html). + +## Support + +If you have any questions, feel free to contact [Dynamsoft support](https://www.dynamsoft.com/company/contact?product=mwc&utm_source=github_angular_readme). diff --git a/guide/index-v1.3.1.md b/guide/index-v1.3.1.md new file mode 100644 index 0000000..53113c8 --- /dev/null +++ b/guide/index-v1.3.1.md @@ -0,0 +1,894 @@ +--- +layout: default-layout +needAutoGenerateSidebar: true +needGenerateH3Content: true +noTitleIndex: false +breadcrumbText: Developer Guide +title: Mobile Document Scanner JS Edition - Scan Single-Page Documents +keywords: Documentation, Mobile Document Scanner, Web, JS Edition, Dynamsoft Document Scanner, +description: Mobile Document Scanner JS Edition User Guide +--- + +# Scan Single-Page Documents with Mobile Document Scanner + +> [!TIP] +> Read the [Introduction]({{ site.introduction }}index.html) for common use cases, an overview of the SDK architecture, and system requirements. + +Dynamsoft's **Mobile Document Scanner JavaScript Edition (MDS)** is a web SDK designed for scanning documents. MDS captures images of the documents and enhances their quality to professional standards, making it an ideal tool for mobile document scanning. + +> [!NOTE] +> See it in action with the [Mobile Document Scanner Demo](https://demo.dynamsoft.com/document-scanner/). + +This guide walks you through building a web application that scans single-page documents using **MDS** with pre-defined configurations. + +## License + +### Get a Trial License + +You can request a trial license for **Mobile Document Scanner** here: + +{% include trialLicense.html %} + +The trial license can be renewed twice for a total of two months of free access. + +### Get a Full License + +[Contact us](https://www.dynamsoft.com/company/contact/) to purchase a full license. + +## Quick Start + +To use the **Mobile Document Scanner**, first obtain its library files. You can acquire them from one of the following sources: + +1. [**GitHub**](https://github.com/Dynamsoft/document-scanner-javascript) – contains the source files for the **MDS** SDK, which can be compiled into library files. +2. [**npm**](https://www.npmjs.com/package/dynamsoft-document-scanner) – provides precompiled library files via npm for easier installation. +3. [**CDN**](https://www.jsdelivr.com/package/npm/dynamsoft-document-scanner) – delivers precompiled library files through a CDN for quick and seamless integration. + +You can choose one of the following methods to set up a Hello World page: + +1. **Build from source** – download the source files from GitHub and compile the library files yourself. +2. **Use precompiled scripts** – use the precompiled resource scripts from npm or the CDN for a quicker setup. +3. **Self-host resources** - self-host both MDS and its dependencies on your web server. + +
    + +
    +
    Build from Source
    + +### Build from Source + +This method retrieves all **MDS** source files from its [GitHub Repository](https://github.com/Dynamsoft/document-scanner-javascript), compiles them into a distributable package, and then runs a _ready-made_ Hello World sample page included in the repository: + +1. Download **MDS** from [GitHub](https://github.com/Dynamsoft/document-scanner-javascript) as a compressed folder. + +2. Extract the contents of the archive, and open the extracted directory in a code editor. + +3. Set your [license key](#get-a-trial-license) in the Hello World sample: + 1. Open the Hello World sample at [`/samples/hello-world.html`](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/samples/hello-world.html). + 2. Search for `"YOUR_LICENSE_KEY_HERE"`, then replace it with your actual license key. + +4. In the terminal, navigate to the project root directory and run the following to install project dependencies: + + ```shell + npm install + ``` + +5. After installing dependencies, build the project by running: + + ```shell + npm run build + ``` + +6. Start the local server by running the following to serve the project locally: + + ```shell + npm run serve + ``` + + Once the server is running, open the application in a browser using the address provided in the terminal output after running `npm run serve`. + + > [!TIP] + > See the server configuration details in [`/dev-server/index.js`](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/dev-server/index.js). + +
    + +
    +
    Use Precompiled Script
    + +### Use Precompiled Scripts + +We publish **MDS** library files on [npm](https://www.npmjs.com/package/dynamsoft-document-scanner) to make them simple to reference from a CDN. + +To use the precompiled script, simply include the following URL in a ` +``` + +Below is the complete Hello World sample page that uses this precompiled script from a CDN. + +> [!TIP] +> The code is identical to the [`/samples/hello-world.html`](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/samples/hello-world.html) file mentioned in the [Build from Source](#build-from-source) section, except for the script source. + +> [!WARNING] +> **Remember** to replace `"YOUR_LICENSE_KEY_HERE"` with your actual license key. + +```html + + + + + + Mobile Document Scanner - Hello World + + + +

    Mobile Document Scanner

    +
    + + + +``` + +To run the sample, create a new file called `hello-world.html`, then copy and paste the code above into the file. Next, serve the page directly by deploying it to a server. + +If you are using VS Code, a quick and easy way to serve the project is using the [Live Server (Five Server) VSCode extension](https://marketplace.visualstudio.com/items?itemName=yandeu.five-server). Simply install the extension, open the `hello-world.html` file in the editor, and click "Go Live" in the bottom right corner of the editor. This will serve the application at `http://127.0.0.1:5500/hello-world.html`. + +Alternatively, you can use other methods like `IIS` or `Apache` to serve the project, though we skip those here for brevity. + +
    + +
    +
    Self-Host Resources
    + +### Self-Host Resources + +By default, the MDS library (whether pre-compiled or self-compiled) fetches resource files (Dynamsoft `node` packages `dynamsoft-capture-vision-bundle` and `dynamsoft-capture-vision-data`, and an HTML UI template) from CDNs. Self-hosting library resources gives you full control over hosting your application. Rather than using CDNs to serve these resources, you can instead host these resources on your own servers to deliver to your users directly when they use your application. You can also use this option to host MDS fully offline by pointing to local resources. + +#### Download Resources + +First, download a copy of the library: + +1. Download **MDS** from [GitHub](https://github.com/Dynamsoft/document-scanner-javascript) as a compressed folder. + +2. Extract the contents of the archive, and open the extracted directory in a code editor. + +3. Set your [license key](#get-a-trial-license) in the Hello World sample: + 1. Open the Hello World sample at ([`/samples/hello-world.html`](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/samples/hello-world.html)). + + 2. Search for `"YOUR_LICENSE_KEY_HERE"`, then replace it with your actual license key. + +4. In the terminal, navigate to the project root directory and run the following to install project dependencies: + + ```shell + npm install + ``` + +#### Point to Resources + +The library uses [`engineResourcePaths`]({{ site.api }}index.html#engineresourcepaths) to locate required Dynamsoft `node` dependencies by pointing to the location of the resources on your web server. The library also uses `scannerViewConfig.cameraEnhancerUIPath` similarly to set the path for the HTML UI template of the `ScannerView`. The included sample server at `dev-server/index.js` can serve local files for this demonstration. Later steps will place both the `node` dependencies and the HTML template in the local `dist` directory. Therefore, set `engineResourcePaths` in the MDS constructor to point to the local `dist` directory (along with setting your license key, and all other configurations): + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + scannerViewConfig: { + cameraEnhancerUIPath: "dist/document-scanner.ui.html", // Use the local file + }, + engineResourcePaths: { + rootDirectory: "dist/libs/" + }, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) +- [`DocumentScannerViewConfig`]({{ site.api }}index.html#documentscannerviewconfig) +- [`engineResourcePaths`]({{ site.api }}index.html#engineresourcepaths) +- [`cameraEnhancerUIPath`]({{ site.api }}index.html#cameraenhanceruipaths) + +#### Modify the Build Script + +Update the `scripts` section in `package.json` to automatically copy resources to the output `dist` directory during the build process. This script gets the `dynamsoft-capture-vision-data` package, and moves both `dynamsoft-capture-vision-data` and `dynamsoft-capture-vision-bundle` to `dist/libs/`, which is where we set the resource directory to. + +```json +"scripts": { + "serve": "node dev-server/index.js", + "build": "rollup -c && npm run get-libs", + "get-libs": "npm install --no-save dynamsoft-capture-vision-data dynamsoft-capture-vision-bundle && npx mkdirp /dist/libs && npx cpx 'node_modules/dynamsoft-*/**/*' dist/libs/ --dereference," + "build:production": "rollup -c --environment BUILD:production" +}, +``` + +#### Serve the Resources + +The included sample server at `dev-server/index.js` needs an extra statement to serve the resources. Include this line: + +```javascript +app.use("/dist/libs", express.static(path.resolve(__dirname, "../dist/libs"))); +```` + +#### Build the Project + +Build the project by running: + +```shell +npm run build +``` + +#### Serve the Project Locally + +Start the local development server by running: + +```shell +npm run serve +``` + +Once the server is running, open the application in a browser using the address provided in the terminal output. + +#### Serve over HTTPS + +**Place the `dist` directory** onto your web server for to serve the web application. When deploying your web application for production, you must serve it over a **secure HTTPS connection**. We require this for the following reasons: + +1. **Browser Security Restrictions** – Most browsers only allow access to camera video streams in a secure context. + + > [!NOTE] + > Some browsers like Chrome may grant access to camera video streams for `http://127.0.0.1`, `http://localhost`, or even pages opened directly from the local file system (`file:///...`). This can be helpful during development and testing. + +2. **Dynamsoft License Requirements** – A secure context is required for **Dynamsoft licenses** to function properly. + +#### Set MIME Type + +Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: + +1. Upgrade your web application server to one that supports the `application/wasm` mimetype. +2. Manually define the mimetype on your server by setting the MIME type for `.wasm` as `application/wasm`. This allows the user's browser to correctly processes resource files. Different web servers have their own way of configuring the MIME type. Here are instructions for [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings), [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap), and [NGINX](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). + +#### Resource Caching + +The `wasm` resource files are relatively large and may take quite a few seconds to download. We recommend setting a longer cache time for these resource files to maximize the performance of your web application using the `Cache-Control` HTTP header. For example, use the `max-age` directive to cache resources for a specified time in seconds: + +``` +Cache-Control: max-age=31536000 +``` + +Reference: +[`Cache-Control`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) + +
    + +
    + +## Hello World Sample Explained + +Here we walk through the code in the Hello World sample to explain its function and usage. + +> [!TIP] +> You can also view the full code by visiting the [MDS JS Hello World Sample on Github](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/samples/hello-world.html). + +### Reference MDS + +```html + + + + + + Mobile Document Scanner - Hello World + + + + +``` + +In this step, we reference MDS with a relative path to the local file in the `` section of the HTML. + +```html + +``` + +Alternatively, you can reference the script hosted on a CDN, for example, on JSDelivr: + +```html + +``` + +**MDS** wraps all its dependency scripts, so a **MDS** project only needs to include **MDS** itself as a single script. No additional dependency scripts are required. + +> [!WARNING] +> Even if you reference the script itself locally, MDS still defaults to loading supporting resources like `.wasm` engine files from the CDN at runtime. If you require a **fully offline setup**, follow the [quick start instructions to self-host resources](#quick-start). + +### Instantiate MDS + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) + +This step creates the **MDS** UI, which by default occupies the entire visible area of the browser window when launched. If needed, you can restrict the UI to a specific container. For more details, refer to [Confine DocumentScanner UI to a Specific Container](#example-1-confine-documentscanner-ui-to-a-specific-container). + +> [!WARNING] +> Instantiating the `DocumentScanner` requires a valid license key. + +### Launch MDS + +```javascript +const result = await documentScanner.launch(); +``` + +API Reference: + +- [`launch()`]({{ site.api }}index.html#launch) + +This step launches the user into the document scanning workflow, beginning in the `DocumentScannerView`, where they can scan a document using one of three methods: + +- Option 1: Manually scan by pressing the **shutter button**. +- Option 2: Enable "**Smart Capture**" - the scanner will automatically capture an image once a document is detected. +- Option 3: Enable "**Auto Crop**" - the scanner will automatically capture an image, detect the document, and crop it out of the video frame. + +> [!TIP] +> For Options 1 & 2: The user is directed to `DocumentCorrectionView` to review detected document boundaries and make any necessary adjustments before applying corrections. Afterward, they proceed to `DocumentResultView`. +> +> For Option 3: The `DocumentCorrectionView` step is skipped. Image correction is applied automatically, and the user is taken directly to `DocumentResultView`. + +In `DocumentResultView`, if needed, the user can return to `DocumentCorrectionView` to make additional adjustments or press "Re-take" to restart the scanning process. + +### Display the Result + +The workflow returns a scanned image object of type `CorrectedImageResult`. To display the scanned `result` image, we use a `
    ` in the ``: + +```html + +

    Mobile Document Scanner

    +
    + +``` + +API Reference: + +- [`DocumentResult`]({{ site.api }}index.html#documentresult) + +The following code clears the result container and displays the scanned result as a canvas: + +```javascript +if (result?.correctedImageResult) { + resultContainer.innerHTML = ""; + const canvas = result.correctedImageResult.toCanvas(); + resultContainer.appendChild(canvas); +} else { + resultContainer.innerHTML = "

    No image scanned. Please try again.

    "; +} +``` + +## Custom Usage + +This section builds on the Hello World sample to demonstrate how to configure **MDS**, typically by adjusting the `DocumentScannerConfig` object. + +### `DocumentScannerConfig` Overview + +[`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) is the primary configuration object for customizing **MDS**. It includes the following properties: + +1. `license` - the license key. +2. `container` - the HTML container for the entire workflow. If not specified (like in the Hello World Sample), one is created automatically. +3. `showCorrectionView` - toggles `DocumentCorrectionView` in the scanning workflow. +4. `showResultView` - toggles `DocumentResultView` in the scanning workflow. +5. `scannerViewConfig` - configures the main scanner view with the following properties: + 1. `container` - the HTML container for the `DocumentScannerView`. + 2. `cameraEnhancerUIPath` - path to the UI definition file (.html) for the `DocumentScannerView`. + 3. `enableAutoCropMode` - sets the default value of Auto-Crop upon entering the `DocumentScannerView`. + 4. `enableSmartCaptureMode` - sets the default state of Smart Capture upon entering the `DocumentScannerView`. + 5. `scanRegion` - sets the scan region within the document scanning viewfinder. + 6. `minVerifiedFramesForSmartCapture` - sets the minimum number of video frames to verify detected document boundaries on Smart Capture mode. Higher frame counts lead to higher confidence at the cost of discarding results. + 7. `showSubfooter` - toggles the visibility of the mode selector menu. + 8. `showPoweredByDynamsoft` - sets the visibility of the Dynamsoft branding message. +6. `correctionViewConfig` - configures the `DocumentCorrectionView`. + 1. `container` - the HTML container for the `DocumentCorrectionView`. + 2. `toolbarButtonsConfig` - configures the appearance and labels of the buttons for the `DocumentCorrectionView` UI. + 3. `onFinish` - handler called when the user clicks the "Apply" button. +7. `resultViewConfig` - configures the result view with the following properties: + 1. `container` - the HTML container for the `DocumentResultView`. + 2. `toolbarButtonsConfig` - configures the appearance and labels of the buttons for the `DocumentResultView` UI. + 3. `onDone` - handler called when the user clicks the "Done" button. + 4. `onUpload` - handler called when the user clicks the "Upload" button. +8. `templateFilePath` - path to a Capture Vision template for scanning configuration; typically not needed as the default template is used. +9. `utilizedTemplateNames`- template names for detection and correction. Typically not needed as the default template is used. +10. `engineResourcePaths` - paths to extra resources such as `.wasm` engine files. + +Furthermore, we explore two main methods of customizing **MDS** with `DocumentScannerConfig`: + +1. [**Workflow Customization**](#workflow-customization): through container definitions. +2. [**View-Based Customization**](#view-based-customization): through configuration objects. + +The customization examples below build on the Hello World code from the [previous section](#use-precompiled-script). The only change required is adjusting the constructor argument. + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + // Add more arguments +}); +``` + +### Workflow Customization + +In the Hello World sample, we use the complete workflow with minimum configuration: + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key +}); +// Launch the scanner and wait for the result +const result = await documentScanner.launch(); +``` + +In this case, **MDS** automatically creates container elements for its **Views**. In this section we discuss a few ways to adjust the **MDS** workflow. + +#### Example 1: Confine DocumentScanner UI to a Specific Container + +As long as the `DocumentScanner` container is assigned, **MDS** confines its **Views** within that container. + +> [!NOTE] +> Containers assigned to its constituent **Views** will be ignored. + +```html +
    +``` + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + container: document.getElementById("myDocumentScannerContainer"), // Use this container for the full workflow + scannerViewConfig: { + container: document.getElementById("myDocumentScannerViewContainer"), // This container is ignored + }, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) + +#### Example 2: Only Show `DocumentScannerView` + +If you do not need either the `DocumentResultView` or `DocumentCorrectionView` in your workflow (for example, if you do not want your user to manually alter the detected document boundaries), you can hide the views with the following configuration properties like so: + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + showResultView: false, + showCorrectionView: false, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) + +#### Example 3: Specify Individual View Containers + +If the configuration object provide containers for the `DocumentScannerView`, `DocumentResultView`, and `DocumentCorrectionView`, but **does not provide** the `DocumentScanner` container, then **MDS** renders the full workflow using these three containers. + +```html +
    +
    +
    +``` + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + scannerViewConfig: { + container: document.getElementById("myDocumentScannerViewContainer"), + }, + correctionViewConfig: { + container: document.getElementById("myDocumentCorrectionViewContainer"), + }, + resultViewConfig: { + container: document.getElementById("myScanResultViewContainer"), + }, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) + +#### Example 4: Scan Static Image Directly + +To scan an image file directly without displaying the `DocumentScannerView` UI at all, you can pass a `File` object to `launch()`. As an example, select an image file from the local disk: + +```html + +``` + +Then get the input file as a `File` object, and pass that file object to `launch()` MDS with: + +```javascript +document.getElementById("initialFile").onchange = async function () { + const files = Array.from(this.files || []); + if (files.length) { + const result = await documentScanner.launch(files[0]); + console.log(result); + + // Clear the result container and display the scanned result as a canvas + if (result?.correctedImageResult) { + resultContainer.innerHTML = ""; // Clear placeholder content + const canvas = result.correctedImageResult.toCanvas(); + resultContainer.appendChild(canvas); + } else { + resultContainer.innerHTML = "

    No image scanned. Please try again.

    "; + } + } +}; +``` + +This hides the `DocumentScannerView` UI entirely and brings up the `DocumentCorrectionView` as the first view, after having detected document boundaries on the static image. The user can proceed through the rest of the workflow and further alter the document boundaries, re-take another image (to open up the `DocumentScannerView`), etc. + +> [!IMPORTANT] +> `launch()` can accept images or PDFs. If launching with a PDF, MDS will **only process the first page**. + +> [!TIP] +> You can completely disable all UI and use MDS to scan a file completely statically by hiding both the `DocumentCorrectionView` and the `DocumentResultView` in [example 2](#example-2-only-show-documentscannerview). + +#### Example 5: Configure Scan Modes + +The Document Scanner View comes with three scan modes: + +1. Border Detection +2. Auto-Crop +3. Smart Capture + +By default, Border Detection mode is enabled upon entering the Scanner View, while the other two are turned off by default. The user can then enable them by clicking their respective icons in the scanning mode sub-footer. From the `DocumentScannerViewConfig` interface, you can: + +1. Set the default state of Auto-Crop mode with `enableAutoCropMode` +2. Set the default state of Smart Capture mode with `enableSmartCaptureMode` +3. Set the visibility of the scanning mode sub-footer with `showSubfooter` + +> [!NOTE] +> Border Detection Mode is always enabled upon the Scanner View, and the scanning sub-footer is visible by default. + +For example, the following config enables all three scanning modes and hides the scanning mode sub-footer to prevent the viewer from changing or viewing the scanning modes: + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + scannerViewConfig: { + enableAutoCropMode: true, + enableSmartCaptureMode: true, + showSubfooter: false, +}}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) +- [`DocumentScannerViewConfig`]({{ site.api }}index.html#documentscannerviewconfig) + +### View-Based Customization + +In addition to modifying the workflow, you can customize individual Views with configuration options for UI styling, button settings, and event handling. + +#### `DocumentScannerView` Configuration + +##### Customizing the `DocumentScannerView` UI + +You can extensively customize the `DocumentScannerView` by editing its HTML template. Consider the following properties of the `DocumentScannerViewConfig` used for customizing the `DocumentScannerView`: + +```typescript +interface DocumentScannerViewConfig { + container?: HTMLElement; + templateFilePath?: string; + cameraEnhancerUIPath?: string; +} +``` + +Of these three properties, we focus on `cameraEnhancerUIPath`. Here we omit `container`, as we cover it in [Workflow Customization](#workflow-customization), and we omit `templateFilePath`, as it refers to the DCV template file that configures document boundary detection algorithms. + +> [!TIP] +> If the performance of **MDS** does not meet your needs, you may require an algorithm template **customized for your usage scenario** for better results. Please contact our experienced [Technical Support Team](https://www.dynamsoft.com/company/contact/) to discuss your requirements. We can tailor a suitable template for you, which you can then apply by updating `templateFilePath`. + +`cameraEnhancerUIPath` points to a file hosted on the jsDelivr CDN by default (see [Self-Host Resources: Point to Resources](#point-to-resources)): +[https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.3.1/dist/document-scanner.ui.html](https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.3.1/dist/document-scanner.ui.html). + +This file defines the UI for `DocumentScannerView`. Since files on the CDN **cannot be modified directly**, you must to use a **local version** to customize the UI. `cameraEnhancerUIPath` specifies the file path to this local version of the UI. + +##### Steps to Customize the UI for `DocumentScannerView` + +1. Follow the instructions in [Build from Source](#build-from-source) to obtain the source files for **MDS**. + +2. Edit the existing `/src/document-scanner.ui.html` to apply your customizations. + +3. Build the project to generate the updated file in `/dist/document-scanner.ui.html`: + + ```shell + npm run build + ``` + +4. Update the configuration to use the local file instead of the CDN version: + + ```javascript + const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace with your actual license key + scannerViewConfig: { + cameraEnhancerUIPath: "../dist/document-scanner.ui.html", // Use the local file + }, + }); + ``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) +- [`DocumentScannerViewConfig`]({{ site.api }}index.html#documentscannerviewconfig) + +##### Customizing the Scanning Region + +We can customize the scanning region in the viewfinder with the `scanRegion` property in the configuration object. You may want to do this if you want to only scan your document in a specific sub-region in the viewfinder. + +```typescript +interface ScanRegion { + ratio: { + width: number; + height: number; + }; + regionBottomMargin: number; // Bottom margin calculated in pixel + style: { + strokeWidth: number; + strokeColor: string; + }; +} +``` + +API Reference: + +[`ScanRegion`]({{ site.api }}index.html#scanregion) + +Here is how `ScanRegion` applies its settings to the viewfinder: + +1. Use the `ratio` property to set the height-to-width of the rectangular scanning region, then scale the rectangle up to fit within the viewfinder. +2. Translate the rectangular up by the number of pixels specified by `regionBottomMargin`. +3. Create a visual border for the scanning region boundary on the viewfinder with a given stroke width in pixels, and a stroke color. + +For example: + +```typescript +scanRegion { + ratio: { + width: 2; + height: 3; + }; + regionBottomMargin: 20; + style: { + strokeWidth: 3; + strokeColor: "green"; + }; +} +``` + +This creates a scan region with a height-to-width ratio of 3:2, translated upwards by 20 pixels, with a green, 3 pixel-wide border in the viewfinder. + +#### `DocumentCorrectionView` Configuration + +The following configuration interface customizes the `DocumentCorrectionView`: + +```typescript +interface DocumentCorrectionViewConfig { + container?: HTMLElement; + toolbarButtonsConfig?: DocumentCorrectionViewToolbarButtonsConfig; + onFinish?: (result: DocumentScanResult) => void; +} +``` + +This section omits the `container` option, as we cover it in the [Workflow Customization](#workflow-customization) section. Below we discuss the other two properties. + +##### Styling `DocumentCorrectionView` Buttons + +The `toolbarButtonsConfig` property (of type `DocumentCorrectionViewToolbarButtonsConfig`) customizes the **appearance and functionality** of the UI buttons. Here is its definition: + +```typescript +type ToolbarButtonConfig = Pick; +interface DocumentCorrectionViewToolbarButtonsConfig { + fullImage?: ToolbarButtonConfig; + detectBorders?: ToolbarButtonConfig; + apply?: ToolbarButtonConfig; +} +``` + +We can use it to **change the icon and label** of each of the three buttons individually or even **hide the buttons**. Below is an example that sets a custom label and image icon for the "Detect Borders" button and hides the "Full Image" button: + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + correctionViewConfig: { + toolbarButtonsConfig: { + fullImage: { + isHidden: true, + }, + detectBorders: { + icon: "path/to/new_icon.png", // Change to the actual path of the new icon + label: "Custom Label", + }, + }, + }, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) +- [`DocumentCorrectionViewConfig`]({{ site.api }}index.html#documentcorrectionviewconfig) + +##### Customizing Apply Button Callback + +The `onFinish` callback triggers upon having applied the user's corrections. For example, the code below displays the corrected image in a `resultContainer` after the user clicks "Apply": + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + correctionViewConfig: { + onFinish: (result) => { + const canvas = result.correctedImageResult.toCanvas(); + resultContainer.appendChild(canvas); + }, + }, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) +- [`DocumentCorrectionViewConfig`]({{ site.api }}index.html#documentcorrectionviewconfig) + +#### `DocumentResultView` Configuration + +Consider `toolbarButtonsConfig`, `onDone` and `onUpload` from the `DocumentResultViewConfig` configuration interface to customize the `DocumentResultView`: + +```typescript +interface DocumentResultViewConfig { + container?: HTMLElement; + toolbarButtonsConfig?: DocumentResultViewToolbarButtonsConfig; + onDone?: (result: DocumentResult) => Promise; + onUpload?: (result: DocumentResult) => Promise; +} +``` + +##### Styling `DocumentResultView` Buttons + +The `toolbarButtonsConfig` property, of type `DocumentResultViewToolbarButtonsConfig`, customizes the appearance and functionality of the UI buttons. Here is its definition: + +```typescript +type ToolbarButtonConfig = Pick; +interface DocumentResultViewToolbarButtonsConfig { + retake?: ToolbarButtonConfig; + correct?: ToolbarButtonConfig; + share?: ToolbarButtonConfig; + upload?: ToolbarButtonConfig; + done?: ToolbarButtonConfig; +} +``` + +This property ca **change the icon and label** of each of the three buttons individually in the `DocumentResultView` or even **hide the buttons*. Below is an example that sets a custom label and image icon for the "Retake" button, and hides the "Share" button: + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + resultViewConfig: { + toolbarButtonsConfig: { + retake: { + icon: "path/to/new_icon.png", // Change to the actual path of the new icon + label: "Custom Label", + }, + share: { + isHidden: true, + }, + }, + }, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) +- [`DocumentResultViewConfig`]({{ site.api }}index.html#documentresultviewconfig) + +##### Customizing the "Done" Button Callback + +The `onDone` callback triggers upon pressing the "Done" button. For example, the code below displays the result image in a `resultContainer` after the user clicks "Done": + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + resultViewConfig: { + onDone: async (result) => { + const canvas = result.correctedImageResult.toCanvas(); + resultContainer.appendChild(canvas); + }, + }, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) +- [`DocumentResultViewConfig`]({{ site.api }}index.html#documentresultviewconfig) + +##### Customizing the "Upload" Button + +The `onUpload` callback triggers upon pressing the "Upload" button. Note that the "Upload" button _only appears_ if a callback function is defined for `onUpload`; the button remains hidden otherwise. + +The following example demonstrates how to upload the result image to a server: + +> [!TIP] +> The following code applies if you follow the steps in [Build from Source](#build-from-source) and use the predefined express server setup. The scanned image uploads directly to the dev server as "uploadedFile.png". See the server configuration details in [`/dev-server/index.js`](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/dev-server/index.js) for more details. + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + resultViewConfig: { + onUpload: async (result) => { + const host = window.location.origin; + const blob = await result.correctedImageResult.toBlob(); + // Create form data + const formData = new FormData(); + formData.append("uploadFile", blob, "uploadedFile.png"); + // Upload file + const response = await fetch( + `${host}/upload`, // Change this to your actual upload URL + { + method: "POST", + body: formData, + }, + ); + }, + }, +}); +``` + +API Reference: + +- [`DocumentScanner()`]({{ site.api }}index.html#documentscanner) +- [`DocumentScannerConfig`]({{ site.api }}index.html#documentscannerconfig) +- [`DocumentResultViewConfig`]({{ site.api }}index.html#documentresultviewconfig) + +## Next Step + +**MDS** is a fully functional, ready-to-use **single page** scanning SDK with built-in UI layouts. There are two options which extend the features of MDS: + +1. To scan multi-page documents as PDFs, please contact [Dynamsoft Support](https://www.dynamsoft.com/company/contact/) for further information. + +2. For multi-page and multi-document processing, as well as advanced editing features, we developed **Mobile Web Capture (MWC)**. Read on to learn how to use this web-based wrapper SDK in the [**Mobile Web Capture User Guide**]({{ site.code-gallery }}mobile-web-capture/index.html). diff --git a/guide/index.md b/guide/index.md index 7de508d..2a13a69 100644 --- a/guide/index.md +++ b/guide/index.md @@ -9,17 +9,17 @@ keywords: Documentation, Mobile Document Scanner, Web, JS Edition, Dynamsoft Doc description: Mobile Document Scanner JS Edition User Guide --- -# Scan Single-Page Documents with Mobile Document Scanner +# Scan Documents with Mobile Document Scanner > [!TIP] > Read the [Introduction]({{ site.introduction }}index.html) for common use cases, an overview of the SDK architecture, and system requirements. -Dynamsoft's **Mobile Document Scanner JavaScript Edition (MDS)** is a web SDK designed for scanning single-page documents. MDS captures images of the documents and enhances their quality to professional standards, making it an ideal tool for mobile document scanning. +Dynamsoft's **Mobile Document Scanner JavaScript Edition (MDS)** is a web SDK designed for scanning documents. MDS captures images of the documents and enhances their quality to professional standards, making it an ideal tool for mobile document scanning. > [!NOTE] > See it in action with the [Mobile Document Scanner Demo](https://demo.dynamsoft.com/document-scanner/). -This guide walks you through building a web application that scans single-page documents using **MDS** with pre-defined configurations. +This guide walks you through building a web application that scans single-page documents using **MDS** with pre-defined configurations. See the [**multi-page scanning guide**](#multi-page-scanning) to scan multi-page documents. ## License @@ -101,7 +101,7 @@ We publish **MDS** library files on [npm](https://www.npmjs.com/package/dynamsof To use the precompiled script, simply include the following URL in a ` + ``` Below is the complete Hello World sample page that uses this precompiled script from a CDN. @@ -119,7 +119,7 @@ Below is the complete Hello World sample page that uses this precompiled script Mobile Document Scanner - Hello World - +

    Mobile Document Scanner

    @@ -163,11 +163,11 @@ Alternatively, you can use other methods like `IIS` or `Apache` to serve the pro ### Self-Host Resources -By default, the MDS library (whether pre-compiled or self-compiled) fetches resource files (Dynamsoft `node` packages `dynamsoft-capture-vision-bundle` and `dynamsoft-capture-vision-data`, and an HTML UI template) from CDNs. Self-hosting library resources gives you full control over hosting your application. Rather than using CDNs to serve these resources, you can instead host these resources on your own servers to deliver to your users directly when they use your application. You can also use this option to host MDS fully offline by pointing to local resources. +By default, the MDS library (whether pre-compiled or self-compiled) fetches resource files (Dynamsoft `node` dependencies and an HTML UI template) from CDNs. Self-hosting library resources gives you full control over hosting your application. Rather than using CDNs to serve these resources, you can instead host these resources on your own servers to deliver to your users directly when they use your application. You can also use this option to host MDS fully offline by pointing to local resources. #### Download Resources -First, download a copy of the library: +First, download a copy of the resources: 1. Download **MDS** from [GitHub](https://github.com/Dynamsoft/document-scanner-javascript) as a compressed folder. @@ -186,16 +186,21 @@ First, download a copy of the library: #### Point to Resources -The library uses [`engineResourcePaths`]({{ site.api }}index.html#engineresourcepaths) to locate required Dynamsoft `node` dependencies by pointing to the location of the resources on your web server. The library also uses `scannerViewConfig.cameraEnhancerUIPath` similarly to set the path for the HTML UI template of the `ScannerView`. The included sample server at `dev-server/index.js` can serve local files for this demonstration. Later steps will place both the `node` dependencies and the HTML template in the local `dist` directory. Therefore, set `engineResourcePaths` in the MDS constructor to point to the local `dist` directory (along with setting your license key, and all other configurations): +The library uses [`engineResourcePaths`]({{ site.api }}index.html#engineresourcepaths) to locate required Dynamsoft `node` dependencies by pointing to the location of the resources on your web server. The library also uses `scannerViewConfig.cameraEnhancerUIPath` similarly to set the path for the HTML UI template of the `ScannerView`. Later steps will place both the `node` dependencies and the HTML template in the local `dist` directory. Therefore, set `engineResourcePaths` in the MDS constructor to point to the local `dist` directory (along with setting your license key, and all other configurations): ```javascript const documentScanner = new Dynamsoft.DocumentScanner({ license: "YOUR_LICENSE_KEY_HERE", scannerViewConfig: { - cameraEnhancerUIPath: "dist/document-scanner.ui.html", // Use the local file + cameraEnhancerUIPath: "./dist/document-scanner.ui.xml", // Use the local file }, engineResourcePaths: { - rootDirectory: "dist/libs/" + std: "./dist/libs/dynamsoft-capture-vision-std/dist/", + dip: "./dist/libs/dynamsoft-image-processing/dist/", + core: "./dist/libs/dynamsoft-core/dist/", + license: "./dist/libs/dynamsoft-license/dist/", + cvr: "./dist/libs/dynamsoft-capture-vision-router/dist/", + ddn: "./dist/libs/dynamsoft-document-normalizer/dist/", }, }); ``` @@ -215,8 +220,8 @@ Update the `scripts` section in `package.json` to automatically copy resources t ```json "scripts": { "serve": "node dev-server/index.js", - "build": "rollup -c && npm run get-libs", - "get-libs": "npm install --no-save dynamsoft-capture-vision-data dynamsoft-capture-vision-bundle && npx mkdirp /dist/libs && npx cpx 'node_modules/dynamsoft-*/**/*' dist/libs/ --dereference, + "build": "rollup -c && npm run copy-libs", + "copy-libs": "npx mkdirp dist/libs && npx cpx \"node_modules/dynamsoft-*/**/*\" dist/libs/ --dereference", "build:production": "rollup -c --environment BUILD:production" }, ``` @@ -249,7 +254,7 @@ Once the server is running, open the application in a browser using the address #### Serve over HTTPS -**Place the `dist` directory** onto your web server for to serve the web application. When deploying your web application for production, you must serve it over a **secure HTTPS connection**. We require this for the following reasons: +**Place the `dist` directory** onto your web server to serve the web application. When deploying your web application for production, you must serve it over a **secure HTTPS connection**. We require this for the following reasons: 1. **Browser Security Restrictions** – Most browsers only allow access to camera video streams in a secure context. @@ -263,7 +268,7 @@ Once the server is running, open the application in a browser using the address Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. -2. Manually define the mimetype on your server by setting the MIME type for `.wasm` as `application/wasm`. This allows the user's browser to correctly processes resource files. Different web servers have their own way of configuring the MIME type. Here are instructions for [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings), [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap), and [NGINX](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). +2. Manually define the mimetype on your server by setting the MIME type for `.wasm` as `application/wasm`. This allows the user's browser to correctly process resource files. Different web servers have their own way of configuring the MIME type. Here are instructions for [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings), [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap), and [NGINX](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). #### Resource Caching @@ -298,7 +303,7 @@ Here we walk through the code in the Hello World sample to explain its function Mobile Document Scanner - Hello World @@ -313,7 +318,7 @@ In this step, we reference MDS with a relative path to the local file in the ` + ``` **MDS** wraps all its dependency scripts, so a **MDS** project only needs to include **MDS** itself as a single script. No additional dependency scripts are required. @@ -398,34 +403,40 @@ This section builds on the Hello World sample to demonstrate how to configure ** 1. `license` - the license key. 2. `container` - the HTML container for the entire workflow. If not specified (like in the Hello World Sample), one is created automatically. -3. `showCorrectionView` - toggles `DocumentCorrectionView` in the scanning workflow. -4. `showResultView` - toggles `DocumentResultView` in the scanning workflow. -5. `scannerViewConfig` - configures the main scanner view with the following properties: - 1. `container` - the HTML container for the `DocumentScannerView`. - 2. `cameraEnhancerUIPath` - path to the UI definition file (.html) for the `DocumentScannerView`. - 3. `enableAutoCropMode` - sets the default value of Auto-Crop upon entering the `DocumentScannerView`. - 4. `enableSmartCaptureMode` - sets the default state of Smart Capture upon entering the `DocumentScannerView`. - 5. `scanRegion` - sets the scan region within the document scanning viewfinder. - 6. `minVerifiedFramesForSmartCapture` - sets the minimum number of video frames to verify detected document boundaries on Smart Capture mode. Higher frame counts lead to higher confidence at the cost of discarding results. - 7. `showSubfooter` - toggles the visibility of the mode selector menu. - 8. `showPoweredByDynamsoft` - sets the visibility of the Dynamsoft branding message. -6. `correctionViewConfig` - configures the `DocumentCorrectionView`. - 1. `container` - the HTML container for the `DocumentCorrectionView`. - 2. `toolbarButtonsConfig` - configures the appearance and labels of the buttons for the `DocumentCorrectionView` UI. - 3. `onFinish` - handler called when the user clicks the "Apply" button. -7. `resultViewConfig` - configures the result view with the following properties: - 1. `container` - the HTML container for the `DocumentResultView`. - 2. `toolbarButtonsConfig` - configures the appearance and labels of the buttons for the `DocumentResultView` UI. - 3. `onDone` - handler called when the user clicks the "Done" button. - 4. `onUpload` - handler called when the user clicks the "Upload" button. -8. `templateFilePath` - path to a Capture Vision template for scanning configuration; typically not needed as the default template is used. -9. `utilizedTemplateNames`- template names for detection and correction. Typically not needed as the default template is used. -10. `engineResourcePaths` - paths to extra resources such as `.wasm` engine files. - -Furthermore, we explore two main methods of customizing **MDS** with `DocumentScannerConfig`: - -1. [**Workflow Customization**](#workflow-customization): through container definitions. -2. [**View-Based Customization**](#view-based-customization): through configuration objects. +3. `showCorrectionView` - toggle `DocumentCorrectionView` in the scanning workflow. +4. `showResultView` - toggle `DocumentResultView` in the scanning workflow. +5. `enableFrameVerification` - toggle selecting the clearest of multiple video frames upon scanning (on by default). +6. `enableContinuousScanning` - toggle continuous scanning mode to make multiple scans on a single `launch()` (`false` by default). +7. `onDocumentScanned` - handler to get single scan results in continuous scanning mode (if `enableContinuousScanning` is `true`). +8. `stopContinuousScanning` - programmatically stop the scanning loop when continuous scanning mode is enabled. +9. `scannerViewConfig` - configure the main scanner view with the following properties: + 1. `container` - the HTML container for the `DocumentScannerView`. + 2. `cameraEnhancerUIPath` - path to the UI definition file (.html) for the `DocumentScannerView`. + 3. `enableAutoCropMode` - set the default value of Auto-Crop upon entering the `DocumentScannerView`. + 4. `enableSmartCaptureMode` - set the default state of Smart Capture upon entering the `DocumentScannerView`. + 5. `enableBoundsDetectionMode` - set the default state of bounds detection mode upon entering the `DocumentScannerView`. + 6. `scanRegion` - set the scan region within the document scanning viewfinder. + 7. `minVerifiedFramesForSmartCapture` - set the minimum number of video frames to verify detected document boundaries on Smart Capture mode. Higher frame counts lead to higher confidence at the cost of discarding results. + 8. `showSubfooter` - toggle the visibility of the mode selector menu. + 9. `showPoweredByDynamsoft` - set the visibility of the Dynamsoft branding message. +10. `correctionViewConfig` - configure the `DocumentCorrectionView`. + 1. `container` - the HTML container for the `DocumentCorrectionView`. + 2. `toolbarButtonsConfig` - configure the appearance and labels of the buttons for the `DocumentCorrectionView` UI. + 3. `onFinish` - handler called when the user clicks the "Apply" button. +11. `resultViewConfig` - configure the result view with the following properties: + 1. `container` - the HTML container for the `DocumentResultView`. + 2. `toolbarButtonsConfig` - configure the appearance and labels of the buttons for the `DocumentResultView` UI. + 3. `onDone` - handler called when the user clicks the "Done" button. + 4. `onUpload` - handler called when the user clicks the "Upload" button. +12. `templateFilePath` - path to a Capture Vision template for scanning configuration; typically not needed as the default template is used. +13. `utilizedTemplateNames`- template names for detection and correction. Typically not needed as the default template is used. +14. `engineResourcePaths` - paths to extra resources such as `.wasm` engine files. + +Furthermore, we explore three main (non-mutually-exclusive) avenues of customization with `DocumentScannerConfig`: + +1. [**Multi-Page Scanning](#multi-page-scanning): through configuration objects and container definitions. +2. [**Workflow Customization**](#workflow-customization): through container definitions. +3. [**View-Based Customization**](#view-based-customization): through configuration objects. The customization examples below build on the Hello World code from the [previous section](#use-precompiled-script). The only change required is adjusting the constructor argument. @@ -436,6 +447,135 @@ const documentScanner = new Dynamsoft.DocumentScanner({ }); ``` +### Multi-Page Scanning + +Mobile Document Scanner can scan multi-page documents when configured to use the continuous scanning mode. Unlike the default behavior of returning a single scan on calling `launch()`, continuous scanning outputs a scan result on every successful scan, which you can further process by providing a handler. The workflow repeats to let the user scan through large documents efficiently. + +See [**Workflow Customization**](#workflow-customization) and [**View-Based Customization**](#view-based-customization) for a more thorough explanation of the customization syntax. + +#### Basic Multi-Page Scanning + +[**Full Sample Source Code**](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/samples/scenarios/multi-page-scanning.html) + +The most straightforward way to implement multi-page scanning is to enable continuous scanning mode and provide a callback handler to process each scanned document via [`onDocumentScanned`]({{ site.api }}index.html#ondocumentscanned). The scanner loops after each successful scan, allowing users to capture multiple pages in succession. The user can manually stop scanning by clicking the "Done" or close buttons from the Document Scanner View. Consider the relevant sections from the source code below: + +```html +
    +``` + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + enableContinuousScanning: true, + onDocumentScanned: (result) => { + // Process each scanned document + const canvas = result.correctedImageResult.toCanvas(); + document.getElementById("results").appendChild(canvas); + }, +}); + +await documentScanner.launch(); +``` + +API Reference: + +- [`DocumentScannerConfig.enableContinuousScanning`]({{ site.api }}index.html#enableContinuousScanning) +- [`DocumentScannerConfig.onDocumentScanned`]({{ site.api }}index.html#ondocumentscanned) + +##### Explanation + +There are two essential components to multi-page scanning - enabling continuous scanning mode, and providing your handler to process the scanned pages. + +1. We enable continuous scanning with the [`enableContinuousScanning`]({{ site.api }}index.html#enableContinuousScanning) property - this is responsible for changing the user workflow, automatically going back to the scanner view to take more scans after confirming each scan. +2. We can then provide a handler to process the document pages to [`onDocumentScanned`]({{ site.api }}index.html#ondocumentscanned). This handler gets called on confirming every scan. In this example, we simply display the result image to the page. + +> [!NOTE] +> Just as in single-scan mode, `launch()` returns a `DocumentResult` promise. In continuous scanning mode, `launch()` returns a **`DocumentResult` promise to the last page scanned**. + +##### Optional Settings + +To enhance the scanning process, you may also choose to use the following settings: + +1. Provide a handler to [`onThumbnailClicked`]({{ site.api }}index.html#onthumbnailclicked), for example, to show a full preview of the last scanned page. +2. Stop the scanning loop programmatically by calling [`stopContinuousScanning()`]({{ site.api }}index.html#stopcontinuousscanning) externally. This is particularly useful if scanning a pre-determined number of pages by counting the number of scans received by `onThumbnailClicked`. +3. For a faster scanning experience, enable both Smart Capture and Auto-Crop modes by default without requiring the user to re-enable them for each scan. See [Configure Scan Modes](#example-5-configure-scan-modes) for details. +4. Under certain use cases where the user does not need to manually edit or change the document boundaries, you can also skip the Document Correction and Document Result Views entirely. This allows the user to stay within the Document Scanner View to capture with the least number of manual interactions per scan. See [Only Show `DocumentScannerView`](#example-2-only-show-documentscannerview) for details. + +#### Multi-Page Scanning with DDV + +> [!TIP] +> You can find the full set of comprehensive documentation Dynamsoft Document Viewer [on our website](https://www.dynamsoft.com/document-viewer/docs/introduction/index.html). + +[**Full Sample Source Code**](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/samples/scenarios/scanning-to-pdf.html) + +For a more advanced multi-page scanning solution with document management, image editing, and comprehensive file support capabilities (including PDF), you can integrate **MDS** with **Dynamsoft Document Viewer (DDV)**. This combination provides: + +- Document editing and management +- Thumbnail previews +- Page reordering and deletion +- PDF export functionality +- A polished UI for both mobile and desktop + +Given the length of the sample, we only provide a snippet for creating the MDS instance here. See the full sample for more. Please see the [DDV documentation](https://www.dynamsoft.com/document-viewer/docs/introduction/index.html) for DDV-related APIs. + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + // Public trial license which is valid for 24 hours + // You can request a 30-day trial key from https://www.dynamsoft.com/customer/license/trialLicense/?product=mds + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + container: scannerContainer, + scannerViewConfig: { + enableAutoCropMode: true, + enableSmartCaptureMode: true, + }, + enableContinuousScanning: true, + onDocumentScanned: async (result) => { + try { + // Convert the scanned image to blob + const canvas = result.correctedImageResult.toCanvas(); + const blob = await new Promise((resolve) => { + canvas.toBlob((b) => resolve(b), "image/jpeg", 0.9); + }); + + // Add the scanned page to DDV document + if (blob) { + await doc.loadSource([ + { + convertMode: "cm/auto", + fileData: blob, + }, + ]); + } + } catch (error) { + console.error("Error adding scanned page to DDV:", error); + } + }, +}); +``` + +API Reference: + +- [`DocumentScannerViewConfig`]({{ site.api }}index.html#documentscannerviewconfig) +- [`enableAutoCropMode`]({{ site.api }}index.html#enableautocropmode) +- [`enableSmartCaptureMode`]({{ site.api }}index.html#enablesmartcapturemode) +- [`DocumentScannerConfig.enableContinuousScanning`]({{ site.api }}index.html#enableContinuousScanning) +- [`onDocumentScanned`]({{ site.api }}index.html#ondocumentscanned) +- [`loadsource()`](https://www.dynamsoft.com/document-viewer/docs/api/interface/idocument/index.html#loadsource) + +##### Explanation + +For brevity, we outline the key steps in this sample implementation: + +1. Initialize DDV +2. Customize the DDV edit viewer (notably by adding a scan button that launches MDS) +3. Instantiate the DDV edit viewer +4. Create a DDV document +5. Create a `DocumentScanner` instance + 1. Enable continuous scanning + 2. On confirming a scan, convert and send the image to the DDV document with [`loadsource()`](https://www.dynamsoft.com/document-viewer/docs/api/interface/idocument/index.html#loadsource) in the MDS event handler +6. Add an event to launch MDS from clicking the custom scan button added to ddv +7. Add an event to DDV that outputs a PDF of the scanned documents from DDV on close using [`saveToPdf()`](https://www.dynamsoft.com/document-viewer/docs/api/interface/idocument/#savetopdf) + ### Workflow Customization In the Hello World sample, we use the complete workflow with minimum configuration: @@ -619,17 +759,17 @@ Of these three properties, we focus on `cameraEnhancerUIPath`. Here we omit `con > If the performance of **MDS** does not meet your needs, you may require an algorithm template **customized for your usage scenario** for better results. Please contact our experienced [Technical Support Team](https://www.dynamsoft.com/company/contact/) to discuss your requirements. We can tailor a suitable template for you, which you can then apply by updating `templateFilePath`. `cameraEnhancerUIPath` points to a file hosted on the jsDelivr CDN by default (see [Self-Host Resources: Point to Resources](#point-to-resources)): -[https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.3.1/dist/document-scanner.ui.html](https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.3.1/dist/document-scanner.ui.html). +[https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.4.0/dist/document-scanner.ui.xml](https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.4.0/dist/document-scanner.ui.xml). -This file defines the UI for `DocumentScannerView`. Since files on the CDN **cannot be modified directly**, you must to use a **local version** to customize the UI. `cameraEnhancerUIPath` specifies the file path to this local version of the UI. +This file defines the UI for `DocumentScannerView`. Since files on the CDN **cannot be modified directly**, you must use a **local version** to customize the UI. `cameraEnhancerUIPath` specifies the file path to this local version of the UI. ##### Steps to Customize the UI for `DocumentScannerView` 1. Follow the instructions in [Build from Source](#build-from-source) to obtain the source files for **MDS**. -2. Edit the existing `/src/document-scanner.ui.html` to apply your customizations. +2. Edit the existing `/src/dcv-config/document-scanner.ui.xml` to apply your customizations. -3. Build the project to generate the updated file in `/dist/document-scanner.ui.html`: +3. Build the project to generate the updated file in `/dist/document-scanner.ui.xml`: ```shell npm run build @@ -682,7 +822,7 @@ Here is how `ScanRegion` applies its settings to the viewfinder: For example: -```typescript +```javascript scanRegion { ratio: { width: 2; @@ -719,9 +859,9 @@ The `toolbarButtonsConfig` property (of type `DocumentCorrectionViewToolbarButto ```typescript type ToolbarButtonConfig = Pick; interface DocumentCorrectionViewToolbarButtonsConfig { - fullImage?: ToolbarButtonConfig; - detectBorders?: ToolbarButtonConfig; - apply?: ToolbarButtonConfig; + fullImage?: ToolbarButtonConfig; + detectBorders?: ToolbarButtonConfig; + apply?: ToolbarButtonConfig; } ``` @@ -800,7 +940,7 @@ interface DocumentResultViewToolbarButtonsConfig { } ``` -This property ca **change the icon and label** of each of the three buttons individually in the `DocumentResultView` or even **hide the buttons*. Below is an example that sets a custom label and image icon for the "Retake" button, and hides the "Share" button: +This property can **change the icon and label** of each of the three buttons individually in the `DocumentResultView` or even **hide the buttons**. Below is an example that sets a custom label and image icon for the "Retake" button, and hides the "Share" button: ```javascript const documentScanner = new Dynamsoft.DocumentScanner({ @@ -872,7 +1012,7 @@ const documentScanner = new Dynamsoft.DocumentScanner({ { method: "POST", body: formData, - }, + } ); }, }, @@ -887,8 +1027,4 @@ API Reference: ## Next Step -**MDS** is a fully functional, ready-to-use **single page** scanning SDK with built-in UI layouts. There are two options which extend the features of MDS: - -1. To scan multi-page documents as PDFs, please contact [Dynamsoft Support](https://www.dynamsoft.com/company/contact/) for further information. - -2. For multi-page and multi-document processing, as well as advanced editing features, we developed **Mobile Web Capture (MWC)**. Read on to learn how to use this web-based wrapper SDK in the [**Mobile Web Capture User Guide**]({{ site.code-gallery }}mobile-web-capture/index.html). +**MDS** is a fully functional, ready-to-use scanning SDK with built-in UI layouts. For multi-page and **multi-document processing**, as well as advanced editing features, we developed **Mobile Web Capture (MWC)**. Read on to learn how to use this web-based wrapper SDK in the [**Mobile Web Capture User Guide**](https://www.dynamsoft.com/mobile-document-scanner/docs/web/code-gallery/mobile-web-capture/index.html). diff --git a/guide/mobile-web-capture-customization-v1.3.1.md b/guide/mobile-web-capture-customization-v1.3.1.md new file mode 100644 index 0000000..7426124 --- /dev/null +++ b/guide/mobile-web-capture-customization-v1.3.1.md @@ -0,0 +1,574 @@ +--- +layout: default-layout +needAutoGenerateSidebar: true +needGenerateH3Content: true +noTitleIndex: false +title: Mobile Web Capture - Scan Multi-Page Documents +keywords: Documentation, Mobile Web Capture, Dynamsoft Document Scanner, +description: Mobile Web Capture User Guide +--- + +# How to Customize Mobile Web Capture + +> [!TIP] +> Prerequisites: read the [MWC Getting Started Guide]({{ site.guides }}mobile-web-capture.html) before proceeding. + +This guide expands on the **Hello World** sample from the **MWC Getting Started Guide** and explores the available customization options. + + + +## MobileWebCaptureConfig Overview + +`MobileWebCaptureConfig` is the primary configuration object for customizing **MWC**. It includes the following properties: + +1. `license`: The license key. +2. `container`: The HTML container for the entire workflow. If not specified (like in the **Hello World** Sample), one is created automatically. +3. `exportConfig`: Configures functions for handling document export operations. + 1. `uploadToServer`: Specifies a function to upload a file to a server. + 2. `downloadFromServer`: Specifies a function to download a document from the server. + 3. `deleteFromServer`: Specifies a function to delete a document from the server. + 4. `onUploadSuccess`: Specifies a function that is triggered when the upload operation succeeds. +4. `showLibraryView`: Configures where or not this **MWC** instance starts with the `LibraryView`. +5. `onClose`: Specifies a function that is triggered when the user closes this **MWC** instance. +6. `documentScannerConfig`: Configures the behavior of the built-in `DocumentScanner` instance. See the details in [`DocumentScannerConfig`]({{ site.guides }}document-scanner.html#documentscannerconfig-overview). +7. `libraryViewConfig`: Configures the library view with the following properties: + 1. `emptyContentConfig`: Specifies the content displayed in the library view when it is empty (no document). + 2. `toolbarButtonsConfig`: Configures the buttons in the toolbar of the library view. +8. `documentViewConfig`: Configures the document view with the following properties: + 1. `emptyContentConfig`: Specifies the content displayed in the document view when it is empty (no page). + 2. `toolbarButtonsConfig`: Configures the buttons in the toolbar of the document view. +9. `pageViewConfig`: Configures the page view. + 1. `toolbarButtonsConfig`: Configures the buttons in the toolbar of the page view. + 2. `annotationToolbarLabelConfig`: Configures the labels of the annotation options. +10. `transferViewConfig`: Configures the transfer view. + 1. `toolbarButtonsConfig`: Configures the buttons in the toolbar of the transfer view. +11. `historyViewConfig`: Configures the history view. + 1. `emptyContentConfig`: Specifies the content displayed in the history view when it is empty (no uploads). + 2. `toolbarButtonsConfig`: Configures the button in the toolbar of the history view. +12. `ddvResourcePath`: Paths to extra resources such as `.wasm` engine files and CSS files. + +API Reference: [`MobileWebCaptureConfig`]({{ site.api }}mobile-web-capture.html#mobilewebcaptureconfig) + +## Overall UI and Workflow Customization + +**MWC** automatically creates containers that fill the entire viewport for its **Views** if none are specified in the configuration. These views come with a predefined workflow. The following demonstrates a few ways to customize the overall UI. + +### Specify the UI Container + +When a container is assigned, **MWC** UI will be confined in that container element: + +```html +
    +``` + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + container: document.getElementById("myMobileWebCapture") , // Use this container for the full workflow +}); +(async () => { + // Launch the Mobile Web Capture Instance + const fileName = `New_Document_${Date.now().toString().slice(-5)}`; + await mobileWebCapture.launch(fileName); +})(); +``` + +### Enable the LibraryView + +By default, **MWC** starts with `DocumentView`, disabling `LibraryView`, so only one document is created and managed. Enabling `LibraryView` allows multiple documents. + +> [!NOTE] +> Since **MWC** now starts with `LibraryView`, a document name is no longer required. If specified, `LibraryView` is still enabled, but **MWC** will start with `DocumentView`. + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + showLibraryView: true // Enable LibraryView +}); +(async () => { + // Launch the Mobile Web Capture Instance + await mobileWebCapture.launch(); // No need to specify a document name. +})(); +``` + +On the `LibraryView`, the user can + +1. **New** : Create a new document. +2. **Capture** : Create a new document by capturing the first image for it. +3. **Import** : Create a new document by importing one or multiple images or PDF files. + +The user can also enable the **"Upload"** feature. Check out [Enable File Upload](#enable-file-upload) and [Enable Upload History](#enable-upload-history). When the **Upload History** feature is enabled, the user can + +- **Uploads**: View uploaded documents from this session, download, or delete them. + +### Start by Opening a Document + +By default, **MWC** starts empty. However, you can specify a file to be opened as the initial document. + +```html + +``` + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key +}); +document.getElementById("initialFile").onchange = async function () { + const files = Array.from(this.files || []); + if (files.length) { + // Launch the Mobile Web Capture instance with an initial file + if (mobileWebCapture.hasLaunched) + await mobileWebCapture.dispose(); + await mobileWebCapture.launch(files[0]); + } +}; +``` + +API Reference: +- [`hasLaunched`]({{ site.api }}mobile-web-capture.html#haslaunched) +- [`dispose`]({{ site.api }}mobile-web-capture.html#dispose) + +### Scan Directly to Document + +When **capturing** a document, it goes through three views: + +1. **`DocumentScannerView`** +2. **`DocumentCorrectionView`** (optional) +3. **`DocumentResultView`** (optional) + +The latter two views can be skipped to speed up the process. + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + documentScannerConfig: { + showResultView: false, + showCorrectionView: false, + }, +}); +(async () => { + // Launch the Mobile Web Capture Instance + const fileName = `New_Document_${Date.now().toString().slice(-5)}`; + await mobileWebCapture.launch(fileName); +})(); +``` + +### Enable File Upload + +When `exportConfig.uploadToServer` is defined, an **Upload** button appears in both `DocumentView` and `PageView`. + +> [!NOTE] +> If `LibraryView` is enabled, the **Upload** button will also appear there. + +The following example demonstrates how to enable file upload and exit the Mobile Web Capture Instance after a successful upload. + +> [!TIP] +> If you followed the steps in [Build from Source](#option-1-build-from-source) and are still using the predefined Express server setup, the following upload code will work correctly. See the server configuration details in [`/dev-server/index.js`](https://github.com/Dynamsoft/mobile-web-capture/blob/main/dev-server/index.js). + +```javascript +const uploadToServer = async (fileName, blob) => { + const host = window.location.origin; + // Create form data + const formData = new FormData(); + formData.append("uploadFile", blob, fileName); + // Upload file + const response = await fetch( + `${host}/upload`, // Change this to your actual upload URL + { + method: "POST", + body: formData, + } + ); + if (response.status === 200) { + // **IMPORTANT**: Returning { status: "success" } is required to trigger onUploadSuccess. + return { + status: "success", + }; + } else { + return { + status: "failed", + }; + } +}; +const onUploadSuccess = async (fileName) => { + console.log(`${fileName} uploaded successfully!`); + return true; // Exit the Mobile Web Capture Instance +}; +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + exportConfig: { + uploadToServer, + onUploadSuccess, + }, +}); +(async () => { + // Launch the Mobile Web Capture Instance + const fileName = `New_Document_${Date.now().toString().slice(-5)}`; + await mobileWebCapture.launch(fileName); +})(); +``` + +> [!IMPORTANT] +> The **Upload** feature is enabled simultaneously in `DocumentView` and `PageView` (and in `LibraryView` if it is enabled). If this is not intended, you can hide the **Upload** button in these **Views**. +> Read more: +> 1. [Disable Upload in DocumentView](#example-2-disable-upload-in-documentview) +> 2. [Disable Upload in PageView](#example-1-disable-upload-in-pageview) +> 3. [Disable Upload in LibraryView](#example-2-disable-upload-in-libraryview) + +### Enable Upload History + +When **File Upload** feature is on and `LibraryView` is enabled, we can enable the **Upload History** feature in the `LibraryView` by defining all the following: +1. `exportConfig.uploadToServer` +2. `exportConfig.downloadFromServer` +3. `exportConfig.deleteFromServer` + +The following example demonstrates how to enable this feature. + +> [!NOTE] +> If you followed the steps in [Build from Source](#option-1-build-from-source) and are still using the predefined Express server setup, the following code will work correctly. See the server configuration details in [`/dev-server/index.js`](https://github.com/Dynamsoft/mobile-web-capture/blob/main/dev-server/index.js). + +```javascript +const host = window.location.origin; +const shortSessionID = Math.random().toString(36).substring(2, 12); +const uploadToServer = async (fileName, blob) => { + const formData = new FormData(); + formData.append("uploadFile", blob, fileName); + formData.append("fileName", fileName); + formData.append("sessionID", shortSessionID); + // Upload file + const response = await fetch( + `${host}/upload`, // Change this to your actual upload URL + { + method: "POST", + body: formData, + } + ); + const responseText = await response.text(); + if (!responseText || !responseText.includes("UploadedFileName")) { + throw new Error("Invalid server response"); + } + const serverFileName = responseText.match( + /UploadedFileName:(.+)_(\d+)_(.+)$/ + ); + if (!serverFileName) { + throw new Error("Failed to parse server response"); + } + const [, sessionID, uploadTime, realFileName] = serverFileName; + const downloadUrl = `${host}/download?fileName=${encodeURIComponent( + `${sessionID}_${uploadTime}_${realFileName}` + )}`; + // NOTE: Ensure the object returned contains status, fileName, and downloadUrl + return { + status: "success", + fileName: realFileName, + downloadUrl, + uploadTime, + }; +}; +const deleteFromServer = async (doc) => { + const response = await fetch( + `${host}/delete?fileName=${encodeURIComponent( + `${shortSessionID}_${doc.uploadTime}_${doc.fileName}` + )}`, + { + method: "POST", + } + ); +}; +const downloadFromServer = async (doc) => { + window.open(doc.downloadUrl); +}; +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + showLibraryView: true, // Enable LibraryView + exportConfig: { + uploadToServer, + downloadFromServer, + deleteFromServer, + } +}); +(async () => { + // Launch the Mobile Web Capture Instance + const fileName = `New_Document_${Date.now().toString().slice(-5)}`; + await mobileWebCapture.launch(fileName); +})(); +``` + +## View-Based Customization +### DocumentView Configuration + +Consider the following configuration interface used for customizing the `DocumentView`: + +```javascript +interface DocumentViewConfig { + emptyContentConfig?: EmptyContentConfig; + toolbarButtonsConfig?: DocumentToolbarButtonsConfig; +} +``` + +#### Example 1: Display A Message In An Empty Document + +By default, the `DocumentView` displays the following when empty: + +![Empty Document View]({{ site.assets }}imgs/empty-document-view.png) + +You can customize its appearance using the `emptyContentConfig` property. + +```html +
    Start Your Document!
    +``` + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + documentViewConfig: { + emptyContentConfig: document.getElementById("customizedDocViewContent"), + }, +}); +``` + +#### Example 2: Disable Upload in DocumentView + +When `exportConfig.uploadToServer` is defined, the **Upload** button appears in both `DocumentView` and `PageView`. The following example demonstrates how to disable this feature by hiding it in `DocumentView`, ensuring that the **Upload** button only appears in `PageView`. + +> [!TIP] +> Read more in [Enable File Upload](#enable-file-upload). + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + documentViewConfig: { + toolbarButtonsConfig: { // Note that there are two upload buttons in DocumentView + uploadDocument: { + isHidden: true + }, + uploadImage: { + isHidden: true + } + } + } +}); +``` + +#### Example 3: Update the Button Icon + +If you don't like a button's icon, you can customize it. The following example shows how to change the icon of the **"Share Document"** button: + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + documentViewConfig: { + toolbarButtonsConfig: { // Note that there are two upload buttons in DocumentView + shareDocument: { + icon: "path/to/new_icon.png", // Change to the actual path of the new icon + label: "Custom Label" + } + } + } +}); +``` + +### LibraryView Configuration + +Consider the following configuration interface used for customizing the `LibraryView`: + +```javascript +interface LibraryViewConfig { + emptyContentConfig?: EmptyContentConfig; + toolbarButtonsConfig?: LibraryToolbarButtonsConfig; +} +``` + +#### Example 1: Display A Message In An Empty Library + +By default, the `LibraryView` displays the following when empty: + +![Empty Library View]({{ site.assets }}imgs/empty-library-view.png) + +You can customize its appearance using the `emptyContentConfig` property. + +```html +
    Create Your First Document!
    +``` + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + showLibraryView: true, // Enable LibraryView + libraryViewConfig: { + emptyContentConfig: document.getElementById("customizedLibraryViewContent"), + }, +}); +``` + +#### Example 2: Disable Upload in LibraryView + +When `exportConfig.uploadToServer` is defined and `showLibraryView` is `true`, an **Upload** button will appears in `LibraryView`. The following example demonstrates how to hide the button. + +> [!NOTE] +> Read more in [Enable File Upload](#enable-file-upload) & [Enable Upload History](#enable-upload-history). + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + showLibraryView: true // Enable LibraryView + libraryViewConfig: { + toolbarButtonsConfig: { + upload: { + isHidden: true + } + } + } +}); +``` + +### PageView Configuration + +Consider the following configuration interface used for customizing the `PageView`: + +```javascript +interface PageViewConfig { + toolbarButtonsConfig?: PageViewToolbarButtonsConfig; + annotationToolbarLabelConfig?: DDVAnnotationToolbarLabelConfig; +} +``` + +#### Example 1: Disable Upload in PageView + +In this example, we'll demonstrate how to hide the **Upload** button in `PageView` even when `exportConfig.uploadToServer` is defined, ensuring that it only appears in `DocumentView`. + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + pageViewConfig: { + toolbarButtonsConfig: { + upload: { + isHidden: true + } + } + } +}); +``` + +#### Example 2: Change the Labels of the Annotation Toolbar Buttons + +You can customize the labels of the annotation toolbar buttons as follows: + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + pageViewConfig: { + annotationToolbarLabelConfig: { + TextBoxAnnotation: "Input Text", + }, + } +}); +``` + +### TransferView and HistoryView Configuration + +The configuration follows similar patterns, so we won’t cover them here for brevity. + +## Self-Hosting Resource Files + +By default, **MWC** relies on a **CDN** for resources such as `.wasm` engine files. If you require a **fully offline setup**, follow these steps: + +> [!IMPORTANT] +> These steps are based on [Build from Source](#option-1-build-from-source), meaning that all **MWC** source files must be available on your local machine. + +#### Update the Resource Paths + +The following code modifies how resource files are referenced: + +> [!TIP] +> In this case, we reference local resource files that are copied during the build process. See [Modify the Build Script](#modify-the-build-script) for details. However, you can also reference your own copies, such as files hosted on your own server. If you need assistance, feel free to [contact us](https://www.dynamsoft.com/company/contact/). + +```javascript +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key + ddvResourcePath: "./dist/libs/dynamsoft-document-viewer/dist/", + documentScannerConfig: { + scannerViewConfig: { + cameraEnhancerUIPath: "./dist/document-scanner.ui.html", // Use the local file + }, + engineResourcePaths: { + std: "./dist/libs/dynamsoft-capture-vision-std/dist/", + dip: "./dist/libs/dynamsoft-image-processing/dist/", + core: "./dist/libs/dynamsoft-core/dist/", + license: "./dist/libs/dynamsoft-license/dist/", + cvr: "./dist/libs/dynamsoft-capture-vision-router/dist/", + ddn: "./dist/libs/dynamsoft-document-normalizer/dist/", + }, + }, +}); +``` + +### Modify the Build Script + +Update the `scripts` section in `package.json` to automatically copy the libraries during the build process: + +```json +"scripts": { + "serve": "node dev-server/index.js", + "build": "rollup -c && npm run copy-libs", + "copy-libs": "npx mkdirp dist/libs && npx cpx \"node_modules/dynamsoft-*/**/*\" dist/libs/ --dereference", + "build:production": "rollup -c --environment BUILD:production" +}, +``` + +### Build the Project + +Once all dependencies are installed, build the project by running: + +```bash +npm run build +``` + +### Serve the Project Locally + +Start the local development server by running: +```bash +npm run serve +``` + +Once the server is running, open the application in a browser using the address provided in the terminal output. + +Now, all required files will be **served locally** without relying on a CDN. + +> [!IMPORTANT] +>* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: +> 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. +> 2. Manually define the mimetype on your server. You can refer to the guides for [apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) / [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) / [nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). +> +>* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. +> +> ``` +> Cache-Control: max-age=31536000 +> ``` +> +> Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). + +## Next Step + +Start building your own mobile document capture and management solution with **MWC**! If you encounter any technical issues or have suggestions, feel free to [contact us](https://www.dynamsoft.com/company/contact/). diff --git a/guide/mobile-web-capture-v1.3.1.md b/guide/mobile-web-capture-v1.3.1.md new file mode 100644 index 0000000..f85f526 --- /dev/null +++ b/guide/mobile-web-capture-v1.3.1.md @@ -0,0 +1,256 @@ +--- +layout: default-layout +needAutoGenerateSidebar: true +needGenerateH3Content: true +noTitleIndex: false +title: Mobile Web Capture - Scan Multi-Page Documents +keywords: Documentation, Mobile Web Capture, Dynamsoft Document Scanner, +description: Mobile Web Capture User Guide +--- + +# Scan Multi-Page Documents with Mobile Web Capture + +> [!TIP] +> Prerequisites: read the [Introduction]({{ site.introduction }}index.html) before proceeding. + +**Mobile Web Capture (MWC)** is an SDK designed for scanning multi-page documents. It integrates **Dynamsoft Document Scanner (DDS)** functionality while offering additional features such as multi-document management, annotation, and uploading, making it a comprehensive solution for managing complex document workflows. + +> [!TIP] +> See it in action with the [Mobile Web Capture Demo](https://demo.dynamsoft.com/mobile-web-capture/). + +This guide walks you through building a web application that scans multi-page documents using **MWC**, with **pre-defined configurations**. + +> [!TIP] +> If you are looking for a solution that scans single-page documents, please read [Dynamsoft Document Scanner User Guide]({{ site.guides }}document-scanner.html) instead. + + + +## License + +### Get a Trial License + +If you haven't got a trial license for **MWC**, you can request one here: + +{% include trialLicense.html %} + + The trial license can be renewed twice, offering a total of two months of free access. + +> [!NOTE] +> **DDS** and **MWC** share the same license keys. If you already have a **DDS** license, you can use it for **MWC**, and vice versa. + +### Get a Full License + +To purchase a full license, [contact us](https://www.dynamsoft.com/company/contact/). + +## Quick Start + +To use **MWC**, the first step is to obtain its library files. You can acquire them from one of the following sources: + +1. [**GitHub**](https://github.com/Dynamsoft/mobile-web-capture) – Contains the source files for the **MWC** SDK, which can be compiled into library files. +2. [**npm**](https://www.npmjs.com/package/dynamsoft-mobile-web-capture) – Provides precompiled library files via npm for easier installation. +3. [**CDN**](https://cdn.jsdelivr.net/npm/dynamsoft-mobile-web-capture) – Delivers precompiled library files through a CDN for quick and seamless integration. + +You can choose one of the following methods to set up a Hello World page: + +1. **Build from Source** – Download the source files from GitHub and compile the resource script yourself. +2. **Using Precompiled Script** – Use the precompiled resource scripts from npm or the CDN for a quicker setup. + +### Option 1: Build from Source + +This method retrieves all **MWC** source files from its [GitHub Repository](https://github.com/Dynamsoft/mobile-web-capture), compiles them into a distributable package, and then runs a *ready-made* Hello World sample page included in the repository. + +Follow these steps: + +1. Download **MWC** from [GitHub](https://github.com/Dynamsoft/mobile-web-capture) as a compressed folder. +2. Extract the contents of the archive. +3. Enter the license key you received in [Get a Trial License](#get-a-trial-license). + > [!TIP] + > In your code editor, open the Hello World sample located at [`/samples/hello-world.html`](https://github.com/Dynamsoft/mobile-web-capture/blob/main/samples/hello-world.html). Search for `"YOUR_LICENSE_KEY_HERE"` and replace it with your actual license key. +4. Install project dependencies + In the terminal, navigate to the project root directory and run: + ```bash + npm install + ``` +5. Build the project + After the dependencies are installed, build the project by running: + ```bash + npm run build + ``` +6. Serve the project locally + Start the local server by running: + ```bash + npm run serve + ``` +Once the server is running, open the application in a browser using the address provided in the terminal output after running `npm run serve`. + +> [!TIP] +> See the server configuration details in [`/dev-server/index.js`](https://github.com/Dynamsoft/mobile-web-capture/blob/main/dev-server/index.js). + +### Option 2: Use Precompiled Script + +Since the **MWC** library files are published on [npm](https://www.npmjs.com/package/dynamsoft-mobile-web-capture), it's easy to reference them from a CDN. + +To use the precompiled script, simply include the following URL in a ` +``` + +Below is the complete Hello World sample page that uses this precompiled script from a CDN. + +> [!NOTE] +> This code is identical to the [`/samples/hello-world.html`](https://github.com/Dynamsoft/mobile-web-capture/blob/main/samples/hello-world.html) file mentioned in the [Build from Source](#option-1-build-from-source) section, except for the script source. + +> [!WARNING] +> **Don't forget** to replace `"YOUR_LICENSE_KEY_HERE"` with your actual license key. + +```html + + + + + + Mobile Web Capture - Hello World + + + + + + +``` + +To run the sample, create a new file called `hello-world.html`, then copy and paste the code above into the file. Next, serve the page directly by deploying it to a server. + +If you are using VS Code, a quick and easy way to serve the project is using the [Live Server (Five Server) VSCode extension](https://marketplace.visualstudio.com/items?itemName=yandeu.five-server). Simply install the extension, open the `hello-world.html` file in the editor, and click "Go Live" in the bottom right corner of the editor. This will serve the application at `http://127.0.0.1:5500/hello-world.html`. + +Alternatively, you can use other methods like `IIS` or `Apache` to serve the project, though we won't cover those here for brevity. + +## Hello World Sample Explained + +Let’s walk through the code in the Hello World sample to understand how it works. + +> [!TIP] +> Instead of using the code above, an alternative way to view the full code is by visiting the [Mobile Web Capture Hello World Sample](https://github.com/Dynamsoft/mobile-web-capture/blob/main/samples/hello-world.html). + +### Reference MWC + +```html + + + + + + Mobile Web Capture - Hello World + + + +``` + +In this step, **MWC** is referenced using a relative local path in the `` section of the HTML. + +```html + +``` + +Alternatively, the script can be referenced from a CDN: + +```html + +``` + +**MWC** wraps all its dependency scripts, so a **MWC** project only needs to include **MWC** itself as a single script. No additional dependency scripts are required. + +> [!IMPORTANT] +> Even if you reference the script locally, supporting resources like `.wasm` engine files are still loaded from the CDN at runtime. If you require a **fully offline setup**, follow the instructions in [Self-Hosting Resource File]({{ site.guides }}mobile-web-capture-customization.html#self-hosting-resource-files). + +### Instantiate MWC + +```javascript +// Instantiate a Mobile Web Capture Object +const mobileWebCapture = new Dynamsoft.MobileWebCapture({ + license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key +}); +``` + +API Reference: [`MobileWebCapture()`](https://www.dynamsoft.com/mobile-web-capture/docs/api/mobile-web-capture.html#mobilewebcapture) + +This step creates the **MWC** UI, which, when launched, occupies the entire visible area of the browser window by default. If needed, you can specify a container to restrict the UI's size. For more details, refer to [Specify the UI Container]({{ site.guides }}mobile-web-capture-customization.html#example-1-specify-the-ui-container). + +> [!WARNING] +> A **license key** is required for the instantiation. + +### Launch MWC + +```javascript +const fileName = `New_Document_${Date.now().toString().slice(-5)}`; // Generates a unique filename to use as the initial document name +await mobileWebCapture.launch(fileName); +``` + +API Reference: [`launch()`](https://www.dynamsoft.com/mobile-web-capture/docs/api/mobile-web-capture.html#launch) + +This step launches the UI, starting in **`DocumentView`**, where the user can begin building a document in two ways: + +> [!NOTE] +> The `DocumentView` requires a document name, which is passed as a parameter in the `launch()` method. + +1. **Capture**: Capture image(s) of the document pages. +2. **Import**: Import one or multiple images or PDF files. + +Once a document has been created, the user can navigate between three views: + +#### The DocumentView +The user can: + +1. **Share**: Share the document as a multi-page PDF file. + - **Download** is enabled where **Share** is not supported (e.g., in Firefox). +2. **Manage**: Select one or multiple pages for further actions. +3. **Manage** → **Select All** : Select all pages. +4. **Manage** → **Delete** : Delete selected pages from the document. +5. **Manage** → **Share** : Share individual pages as images (**.PNG**). + - **Download** is enabled where **Share** is not supported (e.g., in Firefox). + +The user can also enable the **"Upload"** feature. Check out [Enable File Upload]({{ site.guides }}mobile-web-capture-customization.html#enable-file-upload) + +#### The PageView +When the user presses an image, the `PageView` is launched for that page, where the user can + +1. **Delete** : Remove the current page. +2. **Add Page** : Add more pages to the document. +1. **Share** : Share the current page as an image (**.PNG**). + - **Download** is enabled where **Share** is not supported (e.g., in Firefox). +2. **Edit** : Display additional editing features to further process the page. +3. **Edit** → **Crop** : Select a portion of the page and crop. +4. **Edit** → **Rotate** : Rotate the page **90 degrees counterclockwise**. +5. **Edit** → **Filter** : Adjust the page's pixels. +6. **Edit** → **Annotate** : Add annotations to the page. + +The user can also enable the **"Upload"** feature. Check out [Enable File Upload]({{ site.guides }}mobile-web-capture-customization.html#enable-file-upload) + +## Next Step + +Mobile Web Capture provides extensive customization options. Read on to explore the available customizations in the [MWC Customization Guide]({{ site.guides }}mobile-web-capture-customization.html). diff --git a/guide/react-v1.3.1.md b/guide/react-v1.3.1.md new file mode 100644 index 0000000..2c31a2a --- /dev/null +++ b/guide/react-v1.3.1.md @@ -0,0 +1,108 @@ +--- +layout: default-layout +needAutoGenerateSidebar: true +needGenerateH3Content: true +noTitleIndex: false +breadcrumbText: React Guide +title: Mobile Document Scanner JS Edition - React +keywords: Documentation, Mobile Document Scanner, Web, JS Edition, Dynamsoft Document Scanner, React +description: Mobile Document Scanner JS Edition React User Guide +--- + +# Mobile Document Scanner - React + +> [!IMPORTANT] +> This article builds on the prerequisite [MDS developer guide]({{ site.guide }}index.html) for plain JavaScript; please read it before proceeding. + +Mobile Document Scanner integrates easily with React applications. Just as in plain JavaScript, you can add document scanning in your **React application** in just a few lines of code, and achieve most customizations through the same accessible configuration object. + +## Features + +- Easy integration with pre-built UI +- Render MDS inside a React component +- Capture and process documents from video stream +- Automatic document detection and cropping +- Mobile-optimized scanning interface +- TypeScript support with type definitions + +## Requirements + +- **Node.js 20.19.0 or later** +- [Base requirements]({{ site.introduction }}index.html#system-requirements) + +## License + +### Get a Trial License + +Try **MDS** by requesting a trial license through our [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?product=mwc&utm_source=github_react_readme). You can renew the license twice for up to a total of two months of free access. + +### Get a Full License + +[Contact us](https://www.dynamsoft.com/company/contact?product=mwc&utm_source=github_react_readme) to purchase a full license. + +## Quick Start + +We publish **MDS** library files on [npm](https://www.npmjs.com/package/dynamsoft-document-scanner) to make them simple to reference from a CDN. We reference the library files in our _ready-made_ Hello World sample for React included in our GitHub source repository: + +1. Download **MDS** from [GitHub](https://github.com/Dynamsoft/document-scanner-javascript) as a compressed folder. + +2. Extract the contents of the archive, and open the extracted directory in a code editor. + +3. Set your [license key](#get-a-trial-license) in the **React framework sample**: + 1. Open the sample at [`/samples/frameworks/react-hooks/src/App.tsx`](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/document-scanner-javascript-dev/samples/frameworks/react-hooks/src/App.tsx). + 2. Search for `"YOUR_LICENSE_KEY_HERE"`, then replace it with your actual license key. + +### Install Dependencies + +```shell +npm install +``` + +### Start the App + +```shell +npm start +``` + +Then open https://localhost:3000/ to view the sample app. + +## Self-Host Resources + +You can self host the resources for the Hello World by following a few simple steps. Refer to the [plain JavaScript self-hosting guide]({{ site.guide }}index.html#quick-start) for details. + +### Set File Paths + +First we set MDS to look resource paths where we will place the resources later: + +```typescript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + scannerViewConfig: { + cameraEnhancerUIPath: "dist/libs/dynamsoft-document-scanner/dist/document-scanner.ui.html", + }, + engineResourcePaths: { + rootDirectory: "dist/libs/" + }, +}); +``` + +### Move Resources + +Now, add a script (`get-libs`) to automatically move the resources to their destination when building the project (`build`) in `samples/framework/react-hooks/package.json`: + +```json +"scripts": { + "dev": "vite", + "build": "tsc && vite build && npm run get-libs", + "get-libs": "npm install --no-save dynamsoft-capture-vision-data dynamsoft-capture-vision-bundle && npx mkdirp /dist/libs && npx cpx 'node_modules/dynamsoft-*/**/*' dist/libs/ --dereference", + "preview": "vite preview" +}, +``` + +## Customization + +Please check the official [documentation]({{ site.guide }}index.html). + +## Support + +If you have any questions, feel free to [contact Dynamsoft Support](https://www.dynamsoft.com/company/contact?product=mwc&utm_source=github_react_readme). diff --git a/guide/vue-v1.3.1.md b/guide/vue-v1.3.1.md new file mode 100644 index 0000000..b2f1d41 --- /dev/null +++ b/guide/vue-v1.3.1.md @@ -0,0 +1,108 @@ +--- +layout: default-layout +needAutoGenerateSidebar: true +needGenerateH3Content: true +noTitleIndex: false +breadcrumbText: Vue Guide +title: Mobile Document Scanner JS Edition - Vue +keywords: Documentation, Mobile Document Scanner, Web, JS Edition, Dynamsoft Document Scanner, Vue +description: Mobile Document Scanner JS Edition Vue User Guide +--- + +# Mobile Document Scanner - Vue + +> [!IMPORTANT] +> This article builds on the prerequisite [MDS developer guide]({{ site.guide }}index.html) for plain JavaScript; please read it before proceeding. + +Mobile Document Scanner integrates easily with Vue applications. Just as in plain JavaScript, you can add document scanning in your **Vue application** in just a few lines of code, and achieve most customizations through the same accessible configuration object. + +## Features + +- Easy integration with pre-built UI +- Render MDS inside a Vue component +- Capture and process documents from video stream +- Automatic document detection and cropping +- Mobile-optimized scanning interface +- TypeScript support with type definitions + +## Requirements + +- **Node.js 20.19.0 or later** +- [Base requirements]({{ site.introduction }}index.html#system-requirements) + +## License + +### Get a Trial License + +Try **MDS** by requesting a trial license through our [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?product=mwc&utm_source=github_vue_readme). You can renew the license twice for up to a total of two months of free access. + +### Get a Full License + +[Contact us](https://www.dynamsoft.com/company/contact?product=mwc&utm_source=github_vue_readme) to purchase a full license. + +## Quick Start + +We publish **MDS** library files on [npm](https://www.npmjs.com/package/dynamsoft-document-scanner) to make them simple to reference from a CDN. We reference the library files in our _ready-made_ Hello World sample for Vue included in our GitHub source repository: + +1. Download **MDS** from [GitHub](https://github.com/Dynamsoft/document-scanner-javascript) as a compressed folder. + +2. Extract the contents of the archive, and open the extracted directory in a code editor. + +3. Set your [license key](#get-a-trial-license) in the **Vue framework sample**: + 1. Open the sample at [`/samples/frameworks/vue/src/App.vue`](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/document-scanner-javascript-dev/samples/frameworks/vue/src/App.vue). + 2. Search for `"YOUR_LICENSE_KEY_HERE"`, then replace it with your actual license key. + +### Install Dependencies + +```shell +npm install +``` + +### Start the App + +```shell +npm run serve +``` + +Then open http://localhost:8080/ to view the sample app. + +## Self-Host Resources + +You can self host the resources for the Hello World by following a few simple steps. Refer to the [plain JavaScript self-hosting guide]({{ site.guide }}index.html#quick-start) for details. + +### Set File Paths + +First we set MDS to look resource paths where we will place the resources later: + +```typescript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", + scannerViewConfig: { + cameraEnhancerUIPath: "dist/libs/dynamsoft-document-scanner/dist/document-scanner.ui.html", + }, + engineResourcePaths: { + rootDirectory: "dist/libs/" + }, +}); +``` + +### Move Resources + +Now, add a script (`get-libs`) to automatically move the resources to their destination when building the project (`build`) in `samples/framework/vue/package.json`: + +```json +"scripts": { + "dev": "vite", + "build": "tsc && vite build && npm run get-libs", + "get-libs": "npm install --no-save dynamsoft-capture-vision-data dynamsoft-capture-vision-bundle && npx mkdirp /dist/libs && npx cpx 'node_modules/dynamsoft-*/**/*' dist/libs/ --dereference", + "preview": "vite preview" +}, +``` + +## Customization + +Please check the official [documentation]({{ site.guide }}index.html). + +## Support + +If you have any questions, feel free to [contact Dynamsoft Support](https://www.dynamsoft.com/company/contact?product=mwc&utm_source=github_vue_readme). diff --git a/introduction/index-v1.3.1.md b/introduction/index-v1.3.1.md new file mode 100644 index 0000000..d6ddef1 --- /dev/null +++ b/introduction/index-v1.3.1.md @@ -0,0 +1,93 @@ +--- +layout: default-layout +needAutoGenerateSidebar: true +needGenerateH3Content: true +noTitleIndex: false +title: Mobile Document Scanner JS Edition - Introduction +keywords: Documentation, Mobile Document Scanner, Web, JS Edition, Introduction +breadcrumbText: Introduction +description: Mobile Document Scanner JS Edition Documentation Introduction +--- + +# Introduction + +When digitizing physical documents - whether for easier storage, better accessibility, or streamlined processing - a hardware scanner is often the preferred choice. However, when hardware scanners are not feasible or convenient, mobile device cameras can serve as effective alternatives. To address this need, Dynamsoft created the **Mobile Document Scanner JavaScript Edition (MDS) SDK**. + +> [!TIP] +> If you are integrating **hardware scanners** into web applications, you may be interested in **Dynamsoft’s** [**Dynamic Web TWAIN**](https://www.dynamsoft.com/web-twain/docs/introduction/index.html) solution. + +## Common Usage Scenarios + +1. **Single Page Capture** – Capture a single, clear image of a physical document, such as an invoice or patient-intake form. This is the core functionality of MDS. You can try this feature in the [**MDS demo**](https://demo.dynamsoft.com/document-scanner/). If it meets your needs, feel free to go directly to the [**MDS user guide**]({{ site.guide }}index.html). +2. **Document Management** – Capture images of multiple document pages (e.g., a contract) and compile them into a single PDF. Please contact [Dynamsoft Support](https://www.dynamsoft.com/company/contact/) if you need this feature. +3. **Advanced Document Management** – Handle multi-page documents, **multiple documents**, PDF files, annotations, and more with the Mobile Web Capture advanced sample project. Check out the [**online demo**](https://demo.dynamsoft.com/mobile-web-capture/), or read the [**developer guide**]({{ site.code-gallery }}mobile-web-capture/index.html) to try it for yourself. + +## Design Principles + +We designed **MDS** with three core principles in mind: + +1. **Minimal Code** - High-level APIs provide full functionality with just **a couple of lines of code**, significantly reducing development and maintenance costs. +2. **Ready-to-Use UI** - Pre-integrated components and a pre-designed UI enable a **quick setup** while minimizing design efforts. +3. **Effortless Customization** - Tailored configuration objects allow for **easy workflow customization**, addressing common document scenarios without adding development complexity. + +The following example demonstrates how simple it is to power a complete document scanning workflow, including all UI elements: + +```javascript +const documentScanner = new Dynamsoft.DocumentScanner({ + license: "YOUR_LICENSE_KEY_HERE", +}); +await documentScanner.launch(); +``` +The UI elements are modularized into distinct Views, each offering developer-friendly configuration options. These options enable flexible business logic through straightforward configuration objects, helping to reduce development costs and streamline maintenance. + +The following section provides a high-level overview of the Views. + +## Views + +MDS workflows are composed of **Views**, each of which comes **ready-to-use** and can be easily customized using configuration objects. These include the following Views for document scanning and correction: + +1. **Document Scanner View** – Captures documents using a camera scanner. +2. **Document Correction View** – Applies further perspective cropping and adjustments. +3. **Document Result View** – Provides a preview of the scanned document. + +### Highlight: Document Scanner View + +![Document Scanner View](/assets/imgs/document-scanner-view-demo.png) + +The **Document Scanner View** captures scans of documents. It automatically detects document boundaries in the video feed and can optionally select the best frame for scanning, eliminating the need for users to manually snap the image. + +## System Requirements + +### Secure Context (HTTPS Deployment) + +When deploying your web application for production, ensure it is served over a **secure HTTPS connection**. This is required for the following reasons: + +1. **Browser Security Restrictions** – Most browsers only allow access to camera video streams in a secure context. + > [!NOTE] + > Some browsers like Chrome may grant access to camera video streams for `http://127.0.0.1`, `http://localhost`, or even pages opened directly from the local file system (`file:///...`). This can be helpful during development and testing. + +2. **Dynamsoft License Requirements** – A secure context is required for **Dynamsoft licenses** to function properly. + +### Required Browser Features + +The following** browser features** are required for the **DCE** and **DDN** components of **MDS**: + +1. [`WebAssembly`](https://caniuse.com/?search=WebAssembly) +2. [`Blob`](https://caniuse.com/?search=Blob) +3. [`URL`](https://caniuse.com/?search=URL)/[`createObjectURL`](https://caniuse.com/?search=createObjectURL) +4. [`Web Workers`](https://caniuse.com/?search=Worker) + +### Supported Browsers + +The table below lists the **minimum supported versions** of browsers based on these requirements: + +| Browser | Version | +| :-----: | :-----: | +| Chrome | v78+ | +| Firefox | v79+ | +| Safari | v15+ | +| Edge | v92+ | + +## Next Step + +Proceed to the [Mobile Document Scanner Developer Guide]({{ site.guide }}index.html) to build your own document scanning web application. diff --git a/introduction/index.md b/introduction/index.md index d6ddef1..83f050e 100644 --- a/introduction/index.md +++ b/introduction/index.md @@ -19,7 +19,7 @@ When digitizing physical documents - whether for easier storage, better accessib ## Common Usage Scenarios 1. **Single Page Capture** – Capture a single, clear image of a physical document, such as an invoice or patient-intake form. This is the core functionality of MDS. You can try this feature in the [**MDS demo**](https://demo.dynamsoft.com/document-scanner/). If it meets your needs, feel free to go directly to the [**MDS user guide**]({{ site.guide }}index.html). -2. **Document Management** – Capture images of multiple document pages (e.g., a contract) and compile them into a single PDF. Please contact [Dynamsoft Support](https://www.dynamsoft.com/company/contact/) if you need this feature. +2. **Multi-Page Capture** – Capture images of multiple document pages (e.g., a contract). You can further leverage our Dynamsoft Document Viewer (DDV) for built-in PDF support, editing, annotations, and more. See our [sample for reference](https://github.com/Dynamsoft/document-scanner-javascript/blob/main/samples/scenarios/scanning-and-viewing.html). 3. **Advanced Document Management** – Handle multi-page documents, **multiple documents**, PDF files, annotations, and more with the Mobile Web Capture advanced sample project. Check out the [**online demo**](https://demo.dynamsoft.com/mobile-web-capture/), or read the [**developer guide**]({{ site.code-gallery }}mobile-web-capture/index.html) to try it for yourself. ## Design Principles diff --git a/release-notes/index.md b/release-notes/index.md index 6d1d789..3bfb337 100644 --- a/release-notes/index.md +++ b/release-notes/index.md @@ -11,9 +11,49 @@ description: Mobile Web Capture Documentation Release Notes # Mobile Document Scanner JavaScript Edition Release Notes -## 1.3.1 (04/09/2025) +## 1.4.0 (24/11/2025) + +### Features + +#### Breaking changes + +- Rename `document-scanner.ui.html` to `document-scanner.ui.xml` to better reflect its purpose as a declarative UI configuration template. + - This affects self hosting users only - you must update the path in the `scannerViewConfig.cameraEnhancerUIPath` property accordingly and rebuild the library. + +#### Scanning Capabilities + +- Select the clearest of multiple video frames on scan with `enableFrameVerification` (default `true`). +- Add continuous scanning mode to make multiple scans on a single `launch()`, enabled by `enableContinuousScanning` (default `false`). + - Add `onDocumentScanned` handler to get single scan results in continuous scanning mode. + - Add a thumbnail scan preview in the scanner view for continuous scanning mode with an optional `onThumbnailClicked` click handler. + - Add `stopContinuousScanning` to programmatically stop the scanning loop. +- Add `enableBoundsDetectionMode` to set default bounds detection mode + +#### UI/UX Improvements + +- Remove the animated shutter spinner. + +#### Samples + +- Add sample demonstrating minimal code to integrate MDS with Dynamsoft Document Scanner (DDV) to scan to PDF with continuous scanning. +- Add minimal MDS-only continuous scanning sample. -### SDK +### Fixes + +- Fix "Torch not supported" message appearing unecessarily. +- Update framework sample dependencies to resolve security vulnerabilities. +- Remove memory leak caused by logging results to console. + +### Documentation + +- Add guides to using continuous scan mode and integrating with DDV. +- Add full [`tsdoc`](https://tsdoc.org/) annotation coverage for all MDS APIs to bring API references to IDEs and allow content extraction with compatible development tools. + +### Dependencies + +- [Dynamsoft Capture Vision JS 3.2.4000](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/release-notes/dcvb-3.html#324000-11112025) + +## 1.3.1 (04/09/2025) #### Features @@ -35,7 +75,6 @@ description: Mobile Web Capture Documentation Release Notes ### Documentation -- Update SDK versions from v1.2.0 to v1.3.1. - Add [`tsdoc`](https://tsdoc.org/) annotations to bring API references to IDEs and allow content extraction with compatible development tools. - Add developer guides for JavaScript Framework samples.