Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Access Remote Scanners from Mobile Web Browsers via Network

20 Aug 2020 1  
With Dynamic Web TWAIN v16.1.1 and a few lines of code, web developers can rapidly build cross-browser web apps to control remote scanners, which are to PCs, servers, or embedded devices.
In this article we create a simple index.html file for scanning documents in web browsers, add the scanner elements, add a web TWAIN container, add the Dynamsoft service object, acquire images from scanners.

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

How do you scan documents with a mobile device? A general and intuitive way is to use mobile camera apps. Mobile cameras indeed bring convenience for quick image captures. Nevertheless, a real hardware scanner is better than a software scanner implemented with a mobile camera for getting high-quality document images. Dynamsoft brings a remote scanner solution to enterprise-class document management applications. With Dynamic Web TWAIN v16.1.1 and a few lines of code, web developers can rapidly build cross-browser web apps to control remote scanners, which are to PCs, servers, or embedded devices.

Dynamic Web TWAIN: The Real Cross-platform Scanner SDK for Web

Dynamic Web TWAIN is a set of JavaScript APIs designed for hardware scanner programming. It supports all mainstream operating systems and web browsers. With the SDK, web developers can create web document scanning and management apps by writing a few lines of code. To experience how Dynamic Web TWAIN works, try the online demo. Dynamic Web TWAIN supports local and remote modes. Users can switch the mode by binding different IP addresses to Dynamsoft service.

Local Mode

In local mode, Dynamsoft service grants JavaScript APIs access to scanners.

Image 1

You can quickly install the SDK via NPM:

npm install dwt @types/dwt

Create a simple index.html file for scanning documents in web browsers:

<!DOCTYPE html>
<html>
<head>
  <title>Hello World</title>
  <script src="dist/dynamsoft.webtwain.min.js"></script> 
</head>
<body>
  <input type="button" value="Scan" onclick="AcquireImage();" />
  <div id="dwtcontrolContainer"></div>
  <script type="text/javascript">
Dynamsoft.WebTwainEnv.ResourcesPath = "dist";
// Get the license key from https://www.dynamsoft.com/CustomerPortal/Portal/Triallicense.aspx
    Dynamsoft.WebTwainEnv.ProductKey = 'LICENSE-KEY'; 
    window.onload = function () {
      Dynamsoft.WebTwainEnv.Load();
    };
    var DWObject;
    function Dynamsoft_OnReady() {
      // dwtcontrolContainer is the id of the DIV to create the WebTwain instance in.
      DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
    }
    function AcquireImage() {
      if (DWObject) {
        DWObject.SelectSource(function () {
          DWObject.OpenSource();
          DWObject.AcquireImage(
            {
              PixelType: Dynamsoft.EnumDWT_PixelType.TWPT_RGB,
              Resolution: 200,
              IfDisableSourceAfterAcquire: true
            },
            function () {
              console.log("Successful!");
            },
            function (settings, errCode, errString) {
              alert(errString)
            }
          );
        }, function () {
          alert('SelectSource failed!');
        });
      }
    }
  </script> 
</body>
</html>

Remote Scan Mode: Consolidating Standalone Scanners into a Cluster

As long as you have Dynamsoft service installed on Windows, Linux, macOS, and Raspberry Pi, you can simply turn on the remote mode by configuring the IP address.

Image 2

In the figure above, you can see Dynamsoft service is the bridge between a scanner and web clients.

How to Scan Documents from Hardware Scanners to Your Mobile Web Browser?

Dynamic Web TWAIN installer contains a Resources folder for web development.

Create a project folder and copy the Resources folder from Dynamic Web TWAIN installation directory to your project directory.

Create an index.html file.

Add the Scanner <select> Elements

Add two HTML <select> elements: one for scanner server selection and the other for scanner source selection. You can hard-code the IP addresses if you know which machines are connected to scanners. Please refer to Config the IP Address on the Proxy Machine for how to set and get the IP addresses of the proxy machines.

<select size="1" id="remote" style="position: relative; width: 220px;">
        <option>192.168.8.84</option>
        <option>192.168.8.85</option>
</select>
<select size="1" id="source" style="position: relative; width: 220px;"></select>

Add a Web TWAIN Container

Add an HTML <div> element as a Web TWAIN container and initialize the Dynamic Web TWAIN object with a valid trial license key:

<div id="dwtcontrolContainer"></div>

<script type="text/javascript">
        Dynamsoft.WebTwainEnv.UseLocalService = false; 
        Dynamsoft.WebTwainEnv.AutoLoad = true;
        // Get a free trial license key from https://www.dynamsoft.com/CustomerPortal/Portal/Triallicense.aspx
        Dynamsoft.WebTwainEnv.ProductKey = 'LICENSE-KEY';
        var DWObject = null;
        var DWServiceObject = null;

        Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); 

        function Dynamsoft_OnReady() {
            DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
            if(DWObject) {
                DWObject.MouseShape = true;
                createScanObject(ip.value);
            }
        }

Add the Dynamsoft Service Object

Compared to the code for local scanner access, in addition to the Dynamic Web TWAIN object, you need to create another object for accessing the remote scanner based on an IP address used for websocket connection.

function createScanObject(ip) {
            var dwtConfig={WebTwainId:ip, Host: ip, UseLocalService:'true'}; 
            Dynamsoft.WebTwainEnv.CreateDWTObjectEx(dwtConfig, function (dwt) {
                DWServiceObject = dwt; 
                DWServiceObject.RegisterEvent('OnPostTransferAsync', function(outputInfo){
                        DWServiceObject.ConvertToBlob(
                            [DWServiceObject.ImageIDToIndex(outputInfo.imageId)], 
                            Dynamsoft.EnumDWT_ImageType.IT_PNG, 
                            function (result, indices, type) {
                                DWObject.LoadImageFromBinary(
                                    result,         
                                    function () {
                                        console.log('LoadImageFromBinary success');
                                        DWServiceObject.RemoveImage(DWServiceObject.ImageIDToIndex(outputInfo.imageId));
                                    },
                                    function (errorCode, errorString) {
                                        console.log(errorString);   
                                    }
                                );
                            },
                            function (errorCode, errorString) {
                                console.log(errorString);
                            }
                        );
                    }
            );
            
            DWServiceObject.GetSourceNamesAsync().then(function(result) {
                    // remove previous options
                    for (var i=0; i< selectSource.length; i++) {
                            selectSource.remove(i);
                    }

                    for (var i = 0; i < result.length; i++)
                        selectSource.options.add(new Option(result[i], i));
                },
                function(fail) {
                    console.log(fail);
                });
            }, 
            function (error){console.log(error)});
        }

Acquire Images from Scanners

Once the remote connection is established, you can acquire image data from the remote scanner and load it into the image container created on the web-client side. Here is the code for triggering the remote document scan event:

function acquireImage() {
            if (DWServiceObject) {
                var onSuccess, onFailure;
                onSuccess = onFailure = function () {
                    DWServiceObject.CloseSource();
                };
                
                var deviceConfiguration = {
                    SelectSourceByIndex: 0,
                    IfShowUI: false,
                    PixelType:Dynamsoft.EnumDWT_PixelType.TWPT_RGB,
                    Resolution: 300,
                    IfFeederEnabled: false,
                    IfDuplexEnabled: false,
                    IfDisableSourceAfterAcquire: true,
                };
                
                DWServiceObject.SelectSourceByIndex(document.getElementById('source').selectedIndex); 
                DWServiceObject.AcquireImage(deviceConfiguration, onSuccess, onFailure);
            }
        }

You need to know that when using SANE backend to query scanner devices on Linux, it takes a little longer. So be patient while waiting for the source list to return if you want to use a remote scanner connected to a Linux system.

Test It Out

Now you can try to scan documents from any scanner placed in your office via your mobile web browser.

Image 3

Image 4

Config the IP Address on the Proxy Machine

To run Dynamsoft service on your machine, you can download the full Dynamic Web TWAIN SDK package containing a free 30-day trial license. Alternatively, you can install the platform-dependent scanning service from the online demo page and apply for a valid license key from the online portal.

Image 5

For security, by default, the Dynamsoft service does not allow remote access. If you want to use the remote connection, you need to configure the setting manually:

  1. Edit DSConfiguration.ini. Add your server IP address to the configuration file.
Server=<MACHINE IP ADDRESS>

Where is the configuration file located on the proxy machine?

C:\Windows\SysWOW64\Dynamsoft\DynamsoftServicex64_16\DSConfiguration.ini

Image 6

Linux, macOS and Raspberry Pi OS

/opt/dynamsoft/DynamsoftService/DSConfiguration.ini

  1. Restart Dynamsoft service to activate the remote connection.

Source Code

https://github.com/yushulx/web-twain-remote-scan

SDK Download

https://www.dynamsoft.com/Downloads/WebTWAIN_Download.aspx

More Example Code

https://github.com/Dynamsoft/Dynamic-Web-TWAIN

API Documentation

https://www.dynamsoft.com/docs/dwt/

Release Notes

https://www.dynamsoft.com/Products/WebTWAIN_News.aspx

Technical Support

If you have any questions about Dynamic Web TWAIN SDK, please feel free to contact support@dynamsoft.com.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here