| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
Tip
Read the Introduction 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.
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 to scan multi-page documents.
Table of Contents
You can request a trial license for Mobile Document Scanner through our customer portal. The trial license can be renewed twice for a total of two months of free access.
Contact us to purchase a full license.
This section shows you how to run a simple single-page web application for scanning single-page documents. For multi-page workflows, see the multi-page scanning guide.
To use the Mobile Document Scanner, first obtain its library files. You can acquire them from one of the following sources:
You can choose one of the following methods to set up a Hello World page:
This method retrieves all MDS source files from its GitHub Repository, compiles them into a distributable package, and then runs a ready-made Hello World sample page included in the repository:
Download MDS from GitHub as a compressed folder.
Extract the contents of the archive, and open the extracted directory in a code editor.
Set your license key in the Hello World sample:
In the terminal, navigate to the project root directory and run the following to a. install project dependencies, b. build the library, and c. serve the sample:
npm install
npm run build
npm run devOnce the server is running, open the application in a browser using the addresses provided in the terminal output after running npm run dev.
We publish MDS library files on npm to make them simple to reference from a CDN.
To use the precompiled ESM bundle script, simply import it from CDN:
import { DocumentScanner } from "https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.5.0/dist/dds.bundle.js";Or use the UMD bundle script by including the URL in a <script> tag in the document head:
<script src="https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.5.0/dist/dds.bundle.js"></script>Below is the complete Hello World sample page that uses the precompiled ESM bundle script from a CDN.
Tip
The code is similar to the /samples/hello-world.html file mentioned in the Build from Source section, except for the script source.
Warning
Remember to replace "YOUR_LICENSE_KEY_HERE" with your actual license key.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dynamsoft Mobile Document Scanner - Hello World</title>
<!--Optional UMD usage, remove the ESM import if you use this-->
<!--<script src="https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.5.0/dist/dds.bundle.esm.js"></script>-->
<style>
#results canvas {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>Dynamsoft Mobile Document Scanner</h1>
<div id="results"></div>
<script type="module">
import { DocumentScanner } from "https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.5.0/dist/dds.bundle.esm.js";
const results = document.querySelector("#results");
const documentScanner = new DocumentScanner({
license: "YOUR_LICENSE_KEY_HERE",
scannerViewConfig: {
enableAutoCropMode: true,
enableSmartCaptureMode: true,
},
});
const result = await documentScanner.launch();
if (result?.correctedImageResult) {
results.innerHTML = "";
results.appendChild(result.correctedImageResult.toCanvas());
} else {
results.textContent = "No image scanned. Please try again.";
}
</script>
</body>
</html>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. 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.
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.
MDS provides the same bundle for different JS module systems.
To use the ESM bundle, use the import statement in a <script type=module> script, followed by the rest of the code:
import { DocumentScanner } from "/dist/dds.bundle.esm.js";
// CDN links also work here: "https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.5.0/dist/dds.bundle.js"This is equivalent to using a script tag with UMD:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mobile Document Scanner - Hello World</title>
<script src="/dist/dds.bundle.js"></script>
<!--Alternatively, reference the script from CDN
<script src="https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.5.0/dist/dds.bundle.js"></script>
-->
</head>
</html>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, see self-host resources.
const documentScanner = new Dynamsoft.DocumentScanner({
license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key
});API Reference:
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.
Warning
Instantiating the DocumentScanner requires a valid license key.
const result = await documentScanner.launch();API Reference:
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:
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.
The workflow returns a scanned image object of type CorrectedImageResult. To display the scanned result image, we use a <div> in the <body>:
<body>
<h1 style="font-size: large">Mobile Document Scanner</h1>
<div id="results"></div>
</body>API Reference:
The following code clears the result container and displays the scanned result as a canvas:
if (result?.correctedImageResult) {
resultContainer.innerHTML = "";
const canvas = result.correctedImageResult.toCanvas();
resultContainer.appendChild(canvas);
} else {
resultContainer.innerHTML = "<p>No image scanned. Please try again.</p>";
}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. Here are the resources to self-host:
The Hello World sample in the GitHub repository is set up to use self-hosted resources. Follow the steps in Build from Source to see this in action.
The library uses engineResourcePaths to locate required Dynamsoft node dependencies by pointing to the location of the resources on your web server. Similarly, scannerViewConfig.cameraEnhancerUIPath also sets the path for the HTML UI template of the ScannerView. Set the path properties to point to where your server is hosting your resources. For example, the Hello World and the project built-in development server (vite) places the resources in like so:
const documentScanner = new DocumentScanner({
license: "YOUR_LICENSE_KEY_HERE",
engineResourcePaths: {
dcvBundle: "/dynamsoft-capture-vision-bundle/dist",
dcvData: "/dynamsoft-capture-vision-data",
},
scannerViewConfig: {
cameraEnhancerUIPath: "../dist/document-scanner.ui.xml",
enableAutoCropMode: true,
enableSmartCaptureMode: true,
},
});API Reference:
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:
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.
Dynamsoft License Requirements – A secure context is required for Dynamsoft licenses to function properly.
Certain legacy web application servers may lack support for the application/wasm mimetype for .wasm files. To address this, you have two options:
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
This section builds on the Hello World sample to demonstrate how to configure MDS, typically by adjusting the DocumentScannerConfig object.
DocumentScannerConfig is the primary configuration object for customizing MDS. It includes the following properties:
Furthermore, we explore three main (non-mutually-exclusive) avenues of customization with DocumentScannerConfig:
The customization examples below build on the Hello World code from the previous section. The only change required is adjusting the constructor argument.
const documentScanner = new Dynamsoft.DocumentScanner({
license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key
// Add more arguments
});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 and View-Based Customization for a more thorough explanation of the customization syntax.
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. 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:
<div id="results"></div>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:
There are two essential components to multi-page scanning - enabling continuous scanning mode, and providing your handler to process the scanned pages.
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.
To enhance the scanning process, you may also choose to use the following settings:
Tip
You can find the full set of comprehensive documentation Dynamsoft Document Viewer on our website.
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:
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 for DDV-related APIs.
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:
For brevity, we outline the key steps in this sample implementation:
In the Hello World sample, we use the complete workflow with minimum configuration:
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.
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.
<div id="myDocumentScannerContainer" style="width: 80vw; height: 80vh;"></div>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:
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:
const documentScanner = new Dynamsoft.DocumentScanner({
license: "YOUR_LICENSE_KEY_HERE", // Replace this with your actual license key
showResultView: false,
showCorrectionView: false,
});API Reference:
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.
<div id="myDocumentScannerViewContainer" style="width: 80vw; height: 80vh"></div>
<div id="myDocumentCorrectionViewContainer" style="width: 80vw; height: 80vh"></div>
<div id="myScanResultViewContainer" style="width: 80vw; height: 80vh"></div>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:
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:
<input type="file" id="initialFile" accept="image/png,image/jpeg" />Then get the input file as a File object, and pass that file object to launch() MDS with:
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 = "<p>No image scanned. Please try again.</p>";
}
}
};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 disable all UI and run MDS headlessly by hiding both the DocumentCorrectionView and the DocumentResultView in example 2.
The Document Scanner View comes with three scan modes:
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:
Note
Border Detection Mode is always enabled in 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 user from changing or viewing the scanning modes:
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:
In addition to modifying the workflow, you can customize individual Views with configuration options for UI styling, button settings, and event handling.
You can configure theme colors and text strings across the library using themeColor and stringConfig. For example, the following changes the loading screen message, and sets the default primary color to red.
const documentScanner = new Dynamsoft.DocumentScanner({
license: "YOUR_LICENSE_KEY_HERE", // Replace with your actual license key
stringConfig: {
loadingMsg: "My new loading screen message",
},
themeColor: {
primary: "#F54927",
},
});See the reference for a full list of available configurations:
You can extensively customize the DocumentScannerView by editing its HTML template. Consider the following properties of the DocumentScannerViewConfig used for customizing the DocumentScannerView:
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, 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 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): https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.5.0/dist/document-scanner.ui.xml.
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.
Follow the instructions in Build from Source to obtain the source files for MDS.
Edit the existing /src/dcv-config/document-scanner.ui.xml to apply your customizations.
Build the project to generate the updated file in /dist/document-scanner.ui.xml:
npm run buildUpdate the configuration to use the local file instead of the CDN version:
const documentScanner = new Dynamsoft.DocumentScanner({
license: "YOUR_LICENSE_KEY_HERE", // Replace with your actual license key
scannerViewConfig: {
cameraEnhancerUIPath: "../dist/document-scanner.ui.xml", // Use the local file
},
});API Reference:
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.
interface ScanRegion {
ratio: {
width: number;
height: number;
};
regionBottomMargin: number; // Bottom margin calculated in pixel
style: {
strokeWidth: number;
strokeColor: string;
};
}API Reference:
Here is how ScanRegion applies its settings to the viewfinder:
For example:
const 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.
The following configuration interface customizes the DocumentCorrectionView:
interface DocumentCorrectionViewConfig {
container?: HTMLElement;
toolbarButtonsConfig?: DocumentCorrectionViewToolbarButtonsConfig;
onFinish?: (result: DocumentScanResult) => void;
}This section omits the container option, as we cover it in the Workflow Customization section. Below we discuss the other two properties.
The toolbarButtonsConfig property (of type DocumentCorrectionViewToolbarButtonsConfig) customizes the appearance and functionality of the UI buttons. Here is its definition:
type ToolbarButtonConfig = Partial<
Pick<ToolbarButton, "icon" | "label" | "className" | "isHidden">
>;
interface DocumentCorrectionViewToolbarButtonsConfig {
fullImage?: ToolbarButtonConfig;
detectBorders?: ToolbarButtonConfig;
apply?: ToolbarButtonConfig;
}We can use it to change the icon and label of each of the menu 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:
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:
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":
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:
Consider toolbarButtonsConfig, onDone and onUpload from the DocumentResultViewConfig configuration interface to customize the DocumentResultView:
interface DocumentResultViewConfig {
container?: HTMLElement;
toolbarButtonsConfig?: DocumentResultViewToolbarButtonsConfig;
onDone?: (result: DocumentResult) => Promise<void>;
onUpload?: (result: DocumentResult) => Promise<void>;
}The toolbarButtonsConfig property, of type DocumentResultViewToolbarButtonsConfig, customizes the appearance and functionality of the UI buttons. Here is its definition:
type ToolbarButtonConfig = Pick<ToolbarButton, "icon" | "label" | "isHidden">;
interface DocumentResultViewToolbarButtonsConfig {
retake?: ToolbarButtonConfig;
correct?: ToolbarButtonConfig;
share?: ToolbarButtonConfig;
upload?: ToolbarButtonConfig;
done?: ToolbarButtonConfig;
}This property can change the icon and label of each of the menu 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:
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:
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":
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:
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 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 for more details.
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:
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.
| Back | FazBrowse Home | New Git URL |