- Notifications
You must be signed in to change notification settings - Fork2
Add document scanning to web apps with real-time capture, edge detection, and image enhancement. Lightweight and customizable.
License
Dynamsoft/document-scanner-javascript
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Dynamsoft'sMobile 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.
See it in action with theMobile Document Scanner Demo.
Table of Contents
- Scan Documents with Mobile Document Scanner
TryMDS by requesting a trial license through ourcustomer portal. The trial can be renewed twice, providing a total of two months of free access.
To purchase a full license,contact us.
The following section explains how to quickly run a simple, single-page web application to scansingle page documents. See themulti-page scanning guide to scan multi-page documents.
To use theMobile Document Scanner, first obtain its library files. You can acquire them from one of the following sources:
- GitHub – contains the source files for theMDS SDK, which can be compiled into library files.
- npm – provides precompiled library files via npm for easier installation.
- CDN – 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:
- Build from source – download the source files from GitHub and compile the library files yourself.
- Use precompiled scripts – use the precompiled resource scripts from npm or the CDN for a quicker setup.
- Self-host resources - self-host both MDS and its dependencies on your web server.
This method retrieves allMDS source files from itsGitHub Repository, compiles them into a distributable package, and then runs aready-made Hello World sample page included in the repository:
DownloadMDS fromGitHub as a compressed folder.
Extract the contents of the archive, and open the extracted directory in a code editor.
Set yourlicense key in the Hello World sample:
- Open the Hello World sample at
/samples/hello-world.html. - Search for
"YOUR_LICENSE_KEY_HERE", then replace it with your actual license key.
- Open the Hello World sample at
In the terminal, navigate to the project root directory and run the following to install project dependencies:
npm install
After installing dependencies, build the project by running:
npm run build
Start the local server by running the following to serve the project locally:
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.See the server configuration details in
/dev-server/index.js.
We publishMDS library files onnpm to make them simple to reference from a CDN.
To use the precompiled script, simply include the following URL in a<script> tag:
<scriptsrc="https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.4.0/dist/dds.bundle.js"></script>
Below is the complete Hello World sample page that uses this precompiled script from a CDN.
The code is identical to the
/samples/hello-world.htmlfile mentioned in theBuild from Source section, except for the script source.
Remember to replace
"YOUR_LICENSE_KEY_HERE"with your actual license key.
<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Mobile Document Scanner - Hello World</title><scriptsrc="https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.4.0/dist/dds.bundle.js"></script></head><body><h1style="font-size: large">Mobile Document Scanner</h1><divid="results"></div><script>constresultContainer=document.querySelector("#results");// Instantiate a Document Scanner ObjectconstdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license key});(async()=>{// Launch the scanner and wait for the resultconstresult=awaitdocumentScanner.launch();console.log(result);// Clear the result container and display the scanned result as a canvasif(result?.correctedImageResult){resultContainer.innerHTML="";// Clear placeholder contentconstcanvas=result.correctedImageResult.toCanvas();resultContainer.appendChild(canvas);}else{resultContainer.innerHTML="<p>No image scanned. Please try again.</p>";}})();</script></body></html>
To run the sample, create a new file calledhello-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 theLive Server (Five Server) VSCode extension. Simply install the extension, open thehello-world.html file in the editor, and click "Go Live" in the bottom right corner of the editor. This will serve the application athttp://127.0.0.1:5500/hello-world.html.
Alternatively, you can use other methods likeIIS orApache to serve the project, though we skip those here for brevity.
By default, the MDS library (whether pre-compiled or self-compiled) fetches resource files (Dynamsoftnode 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.
First, download a copy of the resources:
DownloadMDS fromGitHub as a compressed folder.
Extract the contents of the archive, and open the extracted directory in a code editor.
Set yourlicense key in the Hello World sample:
Open the Hello World sample at (
/samples/hello-world.html).Search for
"YOUR_LICENSE_KEY_HERE", then replace it with your actual license key.
In the terminal, navigate to the project root directory and run the following to install project dependencies:
npm install
The library usesengineResourcePaths to locate required Dynamsoftnode dependencies by pointing to the location of the resources on your web server. The library also usesscannerViewConfig.cameraEnhancerUIPath similarly to set the path for the HTML UI template of theScannerView. Later steps will place both thenode dependencies and the HTML template in the localdist directory. Therefore, setengineResourcePaths in the MDS constructor to point to the localdist directory (along with setting your license key, and all other configurations):
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",scannerViewConfig:{cameraEnhancerUIPath:"./dist/document-scanner.ui.xml",// 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/",},});
API Reference:
DocumentScanner()DocumentScannerConfigDocumentScannerViewConfigengineResourcePathscameraEnhancerUIPath
Update thescripts section inpackage.json to automatically copy resources to the outputdist directory during the build process.
"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 by running:
npm run build
Start the local development server by running:
npm run serve
Once the server is running, open the application in a browser using the address provided in the terminal output.
Place thedist directory onto your web server to serve the web application. When deploying your web application for production, you must serve it over asecure 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.
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 forDynamsoft licenses to function properly.
Certain legacy web application servers may lack support for theapplication/wasm mimetype for .wasm files. To address this, you have two options:
- Upgrade your web application server to one that supports the
application/wasmmimetype. - Manually define the mimetype on your server by setting the MIME type for
.wasmasapplication/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 forApache,IIS, andNGINX.
Thewasm 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 theCache-Control HTTP header. For example, use themax-age directive to cache resources for a specified time in seconds:
Cache-Control: max-age=31536000Reference:Cache-Control
Here we walk through the code in the Hello World sample to explain its function and usage.
You can also view the full code by visiting theMDS JS Hello World Sample on Github.
<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Mobile Document Scanner - Hello World</title><scriptsrc="../dist/dds.bundle.js"></script><!--Alternatively, reference the script from CDN <script src="https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.4.0/dist/dds.bundle.js"></script> --></head></html>
In this step, we reference MDS with a relative path to the local file in the<head> section of the HTML.
<scriptsrc="../dist/dds.bundle.js"></script>
Alternatively, you can reference the script hosted on a CDN, for example, on JSDelivr:
<scriptsrc="https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.4.0/dist/dds.bundle.js"></script>
MDS wraps all its dependency scripts, so aMDS project only needs to includeMDS itself as a single script. No additional dependency scripts are required.
Even if you reference the script itself locally, MDS still defaults to loading supporting resources like
.wasmengine files from the CDN at runtime. If you require afully offline setup, follow thequick start instructions to self-host resources.
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license key});
API Reference:DocumentScanner()
This step creates theMDS 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 toConfine DocumentScanner UI to a Specific Container.
Instantiating the
DocumentScannerrequires a valid license key.
constresult=awaitdocumentScanner.launch();
API Reference:
This step launches the user into the document scanning workflow, beginning in theDocumentScannerView, where they can scan a document using one of three methods:
- Option 1: Manually scan by pressing theshutter 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.
For Options 1 & 2: The user is directed to
DocumentCorrectionViewto review detected document boundaries and make any necessary adjustments before applying corrections. Afterward, they proceed toDocumentResultView.For Option 3: The
DocumentCorrectionViewstep is skipped. Image correction is applied automatically, and the user is taken directly toDocumentResultView.
InDocumentResultView, if needed, the user can return toDocumentCorrectionView to make additional adjustments or press "Re-take" to restart the scanning process.
The workflow returns a scanned image object of typeCorrectedImageResult. To display the scannedresult image, we use a<div> in the<body>:
<body><h1style="font-size: large">Mobile Document Scanner</h1><divid="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="";constcanvas=result.correctedImageResult.toCanvas();resultContainer.appendChild(canvas);}else{resultContainer.innerHTML="<p>No image scanned. Please try again.</p>";}
This section builds on the Hello World sample to demonstrate how to configureMDS, typically by adjusting theDocumentScannerConfig object.
DocumentScannerConfig is the primary configuration object for customizingMDS. It includes the following properties:
license- the license key.container- the HTML container for the entire workflow. If not specified (like in the Hello World Sample), one is created automatically.showCorrectionView- toggleDocumentCorrectionViewin the scanning workflow.showResultView- toggleDocumentResultViewin the scanning workflow.enableFrameVerification- toggle selecting the clearest of multiple video frames upon scanning (on by default).enableContinuousScanning- toggle continuous scanning mode to make multiple scans on a singlelaunch()(falseby default).onDocumentScanned- handler to get single scan results in continuous scanning mode (ifenableContinuousScanningistrue).stopContinuousScanning- programmatically stop the scanning loop when continuous scanning mode is enabled.scannerViewConfig- configure the main scanner view with the following properties:container- the HTML container for theDocumentScannerView.cameraEnhancerUIPath- path to the UI definition file (.html) for theDocumentScannerView.enableAutoCropMode- set the default value of Auto-Crop upon entering theDocumentScannerView.enableSmartCaptureMode- set the default state of Smart Capture upon entering theDocumentScannerView.enableBoundsDetectionMode- set the default state of bounds detection mode upon entering theDocumentScannerView.scanRegion- set the scan region within the document scanning viewfinder.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.showSubfooter- toggle the visibility of the mode selector menu.showPoweredByDynamsoft- set the visibility of the Dynamsoft branding message.
correctionViewConfig- configure theDocumentCorrectionView.container- the HTML container for theDocumentCorrectionView.toolbarButtonsConfig- configure the appearance and labels of the buttons for theDocumentCorrectionViewUI.onFinish- handler called when the user clicks the "Apply" button.resultViewConfig- configure the result view with the following properties:container- the HTML container for theDocumentResultView.toolbarButtonsConfig- configure the appearance and labels of the buttons for theDocumentResultViewUI.onDone- handler called when the user clicks the "Done" button.onUpload- handler called when the user clicks the "Upload" button.templateFilePath- path to a Capture Vision template for scanning configuration; typically not needed as the default template is used.utilizedTemplateNames- template names for detection and correction. Typically not needed as the default template is used.engineResourcePaths- paths to extra resources such as.wasmengine files.
Furthermore, we explore three main (non-mutually-exclusive) avenues of customization withDocumentScannerConfig:
- **Multi-Page Scanning: through configuration objects and container definitions.
- Workflow Customization: through container definitions.
- View-Based Customization: through configuration objects.
The customization examples below build on the Hello World code from theprevious section. The only change required is adjusting the constructor argument.
constdocumentScanner=newDynamsoft.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 callinglaunch(), 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.
SeeWorkflow Customization andView-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 viaonDocumentScanned. 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:
<divid="results"></div>
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",enableContinuousScanning:true,onDocumentScanned:(result)=>{// Process each scanned documentconstcanvas=result.correctedImageResult.toCanvas();document.getElementById("results").appendChild(canvas);},});awaitdocumentScanner.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.
- We enable continuous scanning with the
enableContinuousScanningproperty - this is responsible for changing the user workflow, automatically going back to the scanner view to take more scans after confirming each scan. - We can then provide a handler to process the document pages to
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 aDocumentResult promise. In continuous scanning mode,launch() returns aDocumentResult promise to the last page scanned.
To enhance the scanning process, you may also choose to use the following settings:
- Provide a handler to
onThumbnailClicked, for example, to show a full preview of the last scanned page. - Stop the scanning loop programmatically by calling
stopContinuousScanning()externally. This is particularly useful if scanning a pre-determined number of pages by counting the number of scans received byonThumbnailClicked. - 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. SeeConfigure Scan Modes for details.
- 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. SeeOnly Show
DocumentScannerViewfor details.
Tip
You can find the full set of comprehensive documentation Dynamsoft Document Vieweron our website.
For a more advanced multi-page scanning solution with document management, image editing, and comprehensive file support capabilities (including PDF), you can integrateMDS withDynamsoft 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 theDDV documentation for DDV-related APIs.
constdocumentScanner=newDynamsoft.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=mdslicense:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keycontainer:scannerContainer,scannerViewConfig:{enableAutoCropMode:true,enableSmartCaptureMode:true,},enableContinuousScanning:true,onDocumentScanned:async(result)=>{try{// Convert the scanned image to blobconstcanvas=result.correctedImageResult.toCanvas();constblob=awaitnewPromise((resolve)=>{canvas.toBlob((b)=>resolve(b),"image/jpeg",0.9);});// Add the scanned page to DDV documentif(blob){awaitdoc.loadSource([{convertMode:"cm/auto",fileData:blob,},]);}}catch(error){console.error("Error adding scanned page to DDV:",error);}},});
API Reference:
DocumentScannerViewConfigenableAutoCropModeenableSmartCaptureModeDocumentScannerConfig.enableContinuousScanningonDocumentScannedloadsource()
For brevity, we outline the key steps in this sample implementation:
- Initialize DDV
- Customize the DDV edit viewer (notably by adding a scan button that launches MDS)
- Instantiate the DDV edit viewer
- Create a DDV document
- Create a
DocumentScannerinstance - Enable continuous scanning
- On confirming a scan, convert and send the image to the DDV document with
loadsource()in the MDS event handler - Add an event to launch MDS from clicking the custom scan button added to ddv
- Add an event to DDV that outputs a PDF of the scanned documents from DDV on close using
saveToPdf()
In the Hello World sample, we use the complete workflow with minimum configuration:
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license key});// Launch the scanner and wait for the resultconstresult=awaitdocumentScanner.launch();
In this case,MDS automatically creates container elements for itsViews. In this section we discuss a few ways to adjust theMDS workflow.
As long as theDocumentScanner container is assigned,MDS confines itsViews within that container.
Containers assigned to its constituentViews will be ignored.
<divid="myDocumentScannerContainer"style="width: 80vw; height: 80vh;"></div>
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keycontainer:document.getElementById("myDocumentScannerContainer"),// Use this container for the full workflowscannerViewConfig:{container:document.getElementById("myDocumentScannerViewContainer"),// This container is ignored},});
API Reference:
If you do not need either theDocumentResultView orDocumentCorrectionView 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:
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keyshowResultView:false,showCorrectionView:false,});
API Reference:
If the configuration object provide containers for theDocumentScannerView,DocumentResultView, andDocumentCorrectionView, butdoes not provide theDocumentScanner container, thenMDS renders the full workflow using these three containers.
<divid="myDocumentScannerViewContainer"style="width: 80vw; height: 80vh"></div><divid="myDocumentCorrectionViewContainer"style="width: 80vw; height: 80vh"></div><divid="myScanResultViewContainer"style="width: 80vw; height: 80vh"></div>
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keyscannerViewConfig:{container:document.getElementById("myDocumentScannerViewContainer"),},correctionViewConfig:{container:document.getElementById("myDocumentCorrectionViewContainer"),},resultViewConfig:{container:document.getElementById("myScanResultViewContainer"),},});
API Reference:
To scan an image file directly without displaying theDocumentScannerView UI at all, you can pass aFile object tolaunch(). As an example, select an image file from the local disk:
<inputtype="file"id="initialFile"accept="image/png,image/jpeg"/>
Then get the input file as aFile object, and pass that file object tolaunch() MDS with:
document.getElementById("initialFile").onchange=asyncfunction(){constfiles=Array.from(this.files||[]);if(files.length){constresult=awaitdocumentScanner.launch(files[0]);console.log(result);// Clear the result container and display the scanned result as a canvasif(result?.correctedImageResult){resultContainer.innerHTML="";// Clear placeholder contentconstcanvas=result.correctedImageResult.toCanvas();resultContainer.appendChild(canvas);}else{resultContainer.innerHTML="<p>No image scanned. Please try again.</p>";}}};
This hides theDocumentScannerView UI entirely and brings up theDocumentCorrectionView 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 theDocumentScannerView), etc.
launch()can accept images or PDFs. If launching with a PDF, MDS willonly process the first page.
You can completely disable all UI and use MDS to scan a file completely statically by hiding both the
DocumentCorrectionViewand theDocumentResultViewinexample 2.
The Document Scanner View comes with three scan modes:
- Border Detection
- Auto-Crop
- 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 theDocumentScannerViewConfig interface, you can:
- Set the default state of Auto-Crop mode with
enableAutoCropMode - Set the default state of Smart Capture mode with
enableSmartCaptureMode - Set the visibility of the scanning mode sub-footer with
showSubfooter
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:
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keyscannerViewConfig:{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 extensively customize theDocumentScannerView by editing its HTML template. Consider the following properties of theDocumentScannerViewConfig used for customizing theDocumentScannerView:
interfaceDocumentScannerViewConfig{container?:HTMLElement;templateFilePath?:string;cameraEnhancerUIPath?:string;}
Of these three properties, we focus oncameraEnhancerUIPath. Here we omitcontainer, as we cover it inWorkflow Customization, and we omittemplateFilePath, as it refers to the DCV template file that configures document boundary detection algorithms.
If the performance ofMDS does not meet your needs, you may require an algorithm templatecustomized for your usage scenario for better results. Please contact our experiencedTechnical 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 (seeSelf-Host Resources: Point to Resources):https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.4.0/dist/document-scanner.ui.xml.
This file defines the UI forDocumentScannerView. Since files on the CDNcannot be modified directly, you must use alocal version to customize the UI.cameraEnhancerUIPath specifies the file path to this local version of the UI.
Follow the instructions inBuild from Source to obtain the source files forMDS.
Edit the existing
/src/dcv-config/document-scanner.ui.xmlto apply your customizations.Build the project to generate the updated file in
/dist/document-scanner.ui.xml:npm run build
Update the configuration to use the local file instead of the CDN version:
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace with your actual license keyscannerViewConfig:{cameraEnhancerUIPath:"../dist/document-scanner.ui.xml",// Use the local file},});
API Reference:
We can customize the scanning region in the viewfinder with thescanRegion 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.
interfaceScanRegion{ratio:{width:number;height:number;};regionBottomMargin:number;// Bottom margin calculated in pixelstyle:{strokeWidth:number;strokeColor:string;};}
API Reference:
Here is howScanRegion applies its settings to the viewfinder:
- Use the
ratioproperty to set the height-to-width of the rectangular scanning region, then scale the rectangle up to fit within the viewfinder. - Translate the rectangular up by the number of pixels specified by
regionBottomMargin. - 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:
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 theDocumentCorrectionView:
interfaceDocumentCorrectionViewConfig{container?:HTMLElement;toolbarButtonsConfig?:DocumentCorrectionViewToolbarButtonsConfig;onFinish?:(result:DocumentScanResult)=>void;}
This section omits thecontainer option, as we cover it in theWorkflow Customization section. Below we discuss the other two properties.
ThetoolbarButtonsConfig property (of typeDocumentCorrectionViewToolbarButtonsConfig) customizes theappearance and functionality of the UI buttons. Here is its definition:
typeToolbarButtonConfig=Pick<ToolbarButton,"icon"|"label"|"isHidden">;interfaceDocumentCorrectionViewToolbarButtonsConfig{fullImage?:ToolbarButtonConfig;detectBorders?:ToolbarButtonConfig;apply?:ToolbarButtonConfig;}
We can use it tochange the icon and label of each of the three buttons individually or evenhide 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:
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keycorrectionViewConfig:{toolbarButtonsConfig:{fullImage:{isHidden:true,},detectBorders:{icon:"path/to/new_icon.png",// Change to the actual path of the new iconlabel:"Custom Label",},},},});
API Reference:
TheonFinish callback triggers upon having applied the user's corrections. For example, the code below displays the corrected image in aresultContainer after the user clicks "Apply":
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keycorrectionViewConfig:{onFinish:(result)=>{constcanvas=result.correctedImageResult.toCanvas();resultContainer.appendChild(canvas);},},});
API Reference:
ConsidertoolbarButtonsConfig,onDone andonUpload from theDocumentResultViewConfig configuration interface to customize theDocumentResultView:
interfaceDocumentResultViewConfig{container?:HTMLElement;toolbarButtonsConfig?:DocumentResultViewToolbarButtonsConfig;onDone?:(result:DocumentResult)=>Promise<void>;onUpload?:(result:DocumentResult)=>Promise<void>;}
ThetoolbarButtonsConfig property, of typeDocumentResultViewToolbarButtonsConfig, customizes the appearance and functionality of the UI buttons. Here is its definition:
typeToolbarButtonConfig=Pick<ToolbarButton,"icon"|"label"|"isHidden">;interfaceDocumentResultViewToolbarButtonsConfig{retake?:ToolbarButtonConfig;correct?:ToolbarButtonConfig;share?:ToolbarButtonConfig;upload?:ToolbarButtonConfig;done?:ToolbarButtonConfig;}
This property canchange the icon and label of each of the three buttons individually in theDocumentResultView or evenhide the buttons. Below is an example that sets a custom label and image icon for the "Retake" button, and hides the "Share" button:
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keyresultViewConfig:{toolbarButtonsConfig:{retake:{icon:"path/to/new_icon.png",// Change to the actual path of the new iconlabel:"Custom Label",},share:{isHidden:true,},},},});
API Reference:
TheonDone callback triggers upon pressing the "Done" button. For example, the code below displays the result image in aresultContainer after the user clicks "Done":
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keyresultViewConfig:{onDone:async(result)=>{constcanvas=result.correctedImageResult.toCanvas();resultContainer.appendChild(canvas);},},});
API Reference:
TheonUpload callback triggers upon pressing the "Upload" button. Note that the "Upload" buttononly appears if a callback function is defined foronUpload; the button remains hidden otherwise.
The following example demonstrates how to upload the result image to a server:
The following code applies if you follow the steps inBuild 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.jsfor more details.
constdocumentScanner=newDynamsoft.DocumentScanner({license:"YOUR_LICENSE_KEY_HERE",// Replace this with your actual license keyresultViewConfig:{onUpload:async(result)=>{consthost=window.location.origin;constblob=awaitresult.correctedImageResult.toBlob();// Create form dataconstformData=newFormData();formData.append("uploadFile",blob,"uploadedFile.png");// Upload fileconstresponse=awaitfetch(`${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 andmulti-document processing, as well as advanced editing features, we developedMobile Web Capture (MWC). Read on to learn how to use this web-based wrapper SDK in theMobile Web Capture User Guide.
About
Add document scanning to web apps with real-time capture, edge detection, and image enhancement. Lightweight and customizable.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors5
Uh oh!
There was an error while loading.Please reload this page.