Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add document scanning to web apps with real-time capture, edge detection, and image enhancement. Lightweight and customizable.

License

NotificationsYou must be signed in to change notification settings

Dynamsoft/document-scanner-javascript

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

License

Get a Trial License

TryMDS by requesting a trial license through ourcustomer portal. The trial can be renewed twice, providing a total of two months of free access.

Get a Full License

To purchase a full license,contact us.

Quick Start

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:

  1. GitHub – contains the source files for theMDS SDK, which can be compiled into library files.
  2. npm – provides precompiled library files via npm for easier installation.
  3. 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:

  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

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:

  1. DownloadMDS fromGitHub as a compressed folder.

  2. Extract the contents of the archive, and open the extracted directory in a code editor.

  3. Set yourlicense key in the Hello World sample:

    1. Open the Hello World sample at/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:

    npm install
  5. After installing dependencies, build the project by running:

    npm run build
  6. 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 runningnpm run serve.

    See the server configuration details in/dev-server/index.js.

Use Precompiled Script

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.html file 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.

Self-Host Resources

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.

Download Resources

First, download a copy of the resources:

  1. DownloadMDS fromGitHub as a compressed folder.

  2. Extract the contents of the archive, and open the extracted directory in a code editor.

  3. Set yourlicense key in the Hello World sample:

    1. Open the Hello World sample at (/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:

    npm install

Point to Resources

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:

Modify the Build Script

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

Build the project by running:

npm run build

Serve the Project Locally

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.

Serve over HTTPS

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:

  1. 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 forhttp://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 forDynamsoft licenses to function properly.

Set MIME Type

Certain legacy web application servers may lack support for theapplication/wasm mimetype for .wasm files. To address this, you have two options:

  1. Upgrade your web application server to one that supports theapplication/wasm mimetype.
  2. Manually define the mimetype on your server by setting the MIME type for.wasm asapplication/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.

Resource Caching

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=31536000

Reference:Cache-Control

Hello World Sample Explained

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.

Reference MDS

<!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.wasm engine files from the CDN at runtime. If you require afully offline setup, follow thequick start instructions to self-host resources.

Instantiate MDS

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 theDocumentScanner requires a valid license key.

Launch MDS

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 toDocumentCorrectionView to review detected document boundaries and make any necessary adjustments before applying corrections. Afterward, they proceed toDocumentResultView.

For Option 3: TheDocumentCorrectionView step 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.

Display the Result

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>";}

Custom Usage

This section builds on the Hello World sample to demonstrate how to configureMDS, typically by adjusting theDocumentScannerConfig object.

DocumentScannerConfig Overview

DocumentScannerConfig is the primary configuration object for customizingMDS. 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 - toggleDocumentCorrectionView in the scanning workflow.
  4. showResultView - toggleDocumentResultView 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 singlelaunch() (false by default).
  7. onDocumentScanned - handler to get single scan results in continuous scanning mode (ifenableContinuousScanning istrue).
  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 theDocumentScannerView.
    2. cameraEnhancerUIPath - path to the UI definition file (.html) for theDocumentScannerView.
    3. enableAutoCropMode - set the default value of Auto-Crop upon entering theDocumentScannerView.
    4. enableSmartCaptureMode - set the default state of Smart Capture upon entering theDocumentScannerView.
    5. enableBoundsDetectionMode - set the default state of bounds detection mode upon entering theDocumentScannerView.
    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 theDocumentCorrectionView.
  11. container - the HTML container for theDocumentCorrectionView.
  12. toolbarButtonsConfig - configure the appearance and labels of the buttons for theDocumentCorrectionView UI.
  13. onFinish - handler called when the user clicks the "Apply" button.
  14. resultViewConfig - configure the result view with the following properties:
  15. container - the HTML container for theDocumentResultView.
  16. toolbarButtonsConfig - configure the appearance and labels of the buttons for theDocumentResultView UI.
  17. onDone - handler called when the user clicks the "Done" button.
  18. onUpload - handler called when the user clicks the "Upload" button.
  19. templateFilePath - path to a Capture Vision template for scanning configuration; typically not needed as the default template is used.
  20. utilizedTemplateNames- template names for detection and correction. Typically not needed as the default template is used.
  21. engineResourcePaths - paths to extra resources such as.wasm engine files.

Furthermore, we explore three main (non-mutually-exclusive) avenues of customization withDocumentScannerConfig:

  1. **Multi-Page Scanning: through configuration objects and container definitions.
  2. Workflow Customization: through container definitions.
  3. 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});

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 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.

Basic Multi-Page Scanning

Full Sample Source Code

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:

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 theenableContinuousScanning 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 toonDocumentScanned. 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.

Optional Settings

To enhance the scanning process, you may also choose to use the following settings:

  1. Provide a handler toonThumbnailClicked, for example, to show a full preview of the last scanned page.
  2. Stop the scanning loop programmatically by callingstopContinuousScanning() externally. This is particularly useful if scanning a pre-determined number of pages by counting the number of scans received byonThumbnailClicked.
  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. SeeConfigure 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. SeeOnly ShowDocumentScannerView for details.

Multi-Page Scanning with DDV

Tip

You can find the full set of comprehensive documentation Dynamsoft Document Vieweron our website.

Full Sample Source Code

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:

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 aDocumentScanner instance
  6. Enable continuous scanning
  7. On confirming a scan, convert and send the image to the DDV document withloadsource() in the MDS event handler
  8. Add an event to launch MDS from clicking the custom scan button added to ddv
  9. Add an event to DDV that outputs a PDF of the scanned documents from DDV on close usingsaveToPdf()

Workflow Customization

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.

Example 1: Confine DocumentScanner UI to a Specific Container

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:

Example 2: Only ShowDocumentScannerView

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:

Example 3: Specify Individual View Containers

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:

Example 4: Scan Static Image Directly

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 theDocumentCorrectionView and theDocumentResultView inexample 2.

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 theDocumentScannerViewConfig interface, you can:

  1. Set the default state of Auto-Crop mode withenableAutoCropMode
  2. Set the default state of Smart Capture mode withenableSmartCaptureMode
  3. Set the visibility of the scanning mode sub-footer withshowSubfooter

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:

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 theDocumentScannerView UI

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 updatingtemplateFilePath.

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.

Steps to Customize the UI forDocumentScannerView
  1. Follow the instructions inBuild from Source to obtain the source files forMDS.

  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.xml:

    npm run build
  4. 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:

Customizing the Scanning Region

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:

ScanRegion

Here is howScanRegion applies its settings to the viewfinder:

  1. Use theratio 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 byregionBottomMargin.
  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:

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 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.

StylingDocumentCorrectionView Buttons

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:

Customizing Apply Button Callback

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:

DocumentResultView Configuration

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>;}
StylingDocumentResultView Buttons

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:

Customizing the "Done" Button Callback

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:

Customizing the "Upload" Button

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.js for 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:

Next Step

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

Stars

Watchers

Forks

Packages

No packages published

Contributors5


[8]ページ先頭

©2009-2025 Movatter.jp