Introduction

The sample illustrates how to use Dynamic Web TWAIN JavaScript library to scan documents, control webcam, read barcode and rasterize PDF in web browsers. All of these functionalities can work on Windows and macOS.

Features of Dynamic Web TWAIN

Building the Sample

Download and extract the package. Open the project with Visual Studio 2005, 2008, 2010, 2013 and 2015.

Press F5 to launch the project:


Document Scanning, Webcam, Barcode & PDF in JavaScript

Scan Document

Here is the complete code for scanning document from TWAIN, WIA scanners.

JavaScript
Edit|Remove
<input type="button" value="Scan" onclick="AcquireImage();" /> 
 
<!-- dwtcontrolContainer is the default div id for Dynamic Web TWAIN control. 
    If you need to rename the id, you should also change the id in the dynamsoft.webtwain.config.js accordingly. --> 
<div id="dwtcontrolContainer"></div> 
 
<script type="text/javascript"> 
    Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used 
    var DWObject; 
 
    function Dynamsoft_OnReady() { 
        DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer' 
        if (DWObject) { 
            DWObject.ImageCaptureDriverType = 3; 
            var count = DWObject.SourceCount; 
            for (var i = 0; i < count; i++) 
                document.getElementById("source").options.add(new Option(DWObject.GetSourceNameItems(i), i)); // Get Data Source names from Data Source Manager and put them in a drop-down box 
        } 
    } 
 
    function AcquireImage() { 
        if (DWObject) { 
            var OnAcquireImageSuccess, OnAcquireImageFailure; 
            OnAcquireImageSuccess = OnAcquireImageFailure = function() { 
                DWObject.CloseSource(); 
            }; 
 
            DWObject.SelectSourceByIndex(document.getElementById("source").selectedIndex); //Use method SelectSourceByIndex to avoid the 'Select Source' dialog 
            DWObject.OpenSource(); 
            DWObject.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan. 
            DWObject.AcquireImage(OnAcquireImageSuccess, OnAcquireImageFailure); 
        } 
    } 
</script>

To upload an image, use the JavaScript code on the client-side:

 

JavaScript
Edit|Remove
function btnUpload_onclick() { 
    if (!checkIfImagesInBuffer()) { 
        return; 
    } 
    var i, strHTTPServer, strActionPage, strImageType; 
 
    var _txtFileName = document.getElementById("txt_fileName"); 
    if(_txtFileName) 
        _txtFileName.className = ""; 
   
    //DWObject.MaxInternetTransferThreads = 5; 
    strHTTPServer = location.hostname; 
    DWObject.IfSSL = DynamLib.detect.ssl; 
    var _strPort = location.port == "" ? 80 : location.port; 
    if (DynamLib.detect.ssl == true) 
        _strPort = location.port == "" ? 443 : location.port; 
    DWObject.HTTPPort = _strPort; 
     
     
    var CurrentPathName = unescape(location.pathname); // get current PathName in plain ASCII     
    var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1); 
    strActionPage = CurrentPath + "SaveToFile.aspx"//the ActionPage's file path , Online Demo:"SaveToDB.aspx" ;Sample: "SaveToFile.aspx"; 
    var redirectURLifOK = CurrentPath + "online_demo_list.aspx"; 
    for (i = 0; i < 4; i++) { 
        if (document.getElementsByName("ImageType").item(i).checked == true) { 
            strImageType = i + 1; 
            break; 
        } 
    } 
 
    var fileName = _txtFileName.value; 
    var replaceStr = "<"; 
    fileName = fileName.replace(new RegExp(replaceStr,'gm'),'&lt;'); 
    var uploadfilename = fileName + "." + document.getElementsByName("ImageType").item(i).value; 
 
    var OnSuccess = function(httpResponse) { 
        appendMessage('<b>Upload: </b>'); 
        checkErrorStringWithErrorCode(0"Successful."); 
        if (strActionPage.indexOf("SaveToFile") != -1{ 
            alert("Successful")//if save to file. 
        } else { 
            window.location.href = redirectURLifOK; 
        } 
    }; 
 
    var OnFailure = function(errorCode, errorString, httpResponse) { 
        checkErrorStringWithErrorCode(errorCode, errorString, httpResponse); 
    }; 
     
    if (strImageType == 2 && document.getElementById("MultiPageTIFF").checked) { 
        if ((DWObject.SelectedImagesCount == 1) || (DWObject.SelectedImagesCount == DWObject.HowManyImagesInBuffer)) { 
            DWObject.HTTPUploadAllThroughPostAsMultiPageTIFF( 
                strHTTPServer, 
                strActionPage, 
                uploadfilename, 
                OnSuccess, OnFailure 
            ); 
        } 
        else { 
            DWObject.HTTPUploadThroughPostAsMultiPageTIFF( 
                strHTTPServer, 
                strActionPage, 
                uploadfilename, 
                OnSuccess, OnFailure 
            ); 
        } 
    } 
    else if (strImageType == 4 && document.getElementById("MultiPagePDF").checked) { 
    if ((DWObject.SelectedImagesCount == 1) || (DWObject.SelectedImagesCount == DWObject.HowManyImagesInBuffer)) { 
            DWObject.HTTPUploadAllThroughPostAsPDF( 
                strHTTPServer, 
                strActionPage, 
                uploadfilename, 
                OnSuccess, OnFailure 
            ); 
        } 
        else { 
            DWObject.HTTPUploadThroughPostAsMultiPagePDF( 
                strHTTPServer, 
                strActionPage, 
                uploadfilename, 
                OnSuccess, OnFailure 
            ); 
        } 
    } 
    else { 
        DWObject.HTTPUploadThroughPostEx( 
            strHTTPServer, 
            DWObject.CurrentImageIndexInBuffer, 
            strActionPage, 
            uploadfilename, 
            strImageType, 
            OnSuccess, OnFailure 
        ); 
    } 
}

 

And the C# code on the server-side:

 

C#
Edit|Remove
// save to file 
String strImageName; 
        HttpFileCollection files = HttpContext.Current.Request.Files; 
        HttpPostedFile uploadfile = files["RemoteFile"]; 
        strImageName = uploadfile.FileName; 
 
        uploadfile.SaveAs(Server.MapPath(".") + "\\UploadedImages\\" + strImageName);
 
C#
Edit|Remove
// save to database 
string strImageName = ""try 
{ 
    int iFileLength; 
    HttpFileCollection files = HttpContext.Current.Request.Files; 
    HttpPostedFile uploadfile = files["RemoteFile"]; 
    if (uploadfile != null) 
    { 
        strImageName = uploadfile.FileName; 
        iFileLength = uploadfile.ContentLength; 
 
        Byte[] inputBuffer = new Byte[iFileLength]; 
        System.IO.Stream inputStream; 
 
        inputStream = uploadfile.InputStream; 
        inputStream.Read(inputBuffer, 0, iFileLength); 
 
        String strConnString; 
 
        strConnString = Common.DW_ConnString; 
 
        System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(strConnString); 
 
        String SqlCmdText = "INSERT INTO " + Common.DW_SaveTable + " (strImageName,imgImageData) VALUES (@ImageName,@Image)"; 
        System.Data.SqlClient.SqlCommand sqlCmdObj = new System.Data.SqlClient.SqlCommand(SqlCmdText, sqlConnection); 
 
        sqlCmdObj.Parameters.Add("@Image", System.Data.SqlDbType.Binary, iFileLength).Value = inputBuffer; 
        sqlCmdObj.Parameters.Add("@ImageName", System.Data.SqlDbType.VarChar, 255).Value = strImageName; 
 
        sqlConnection.Open(); 
        sqlCmdObj.ExecuteNonQuery(); 
        sqlConnection.Close(); 
 
    } 
} 
catch  
{ 
} 

 

Webcam Capture

 

JavaScript
Edit|Remove
function acquireImageByWebcam() 
{ 
    DWObject.Addon.Webcam.SelectSource(document.getElementById("webcamsource").options[document.getElementById("webcamsource").selectedIndex].text); 
    var valueMediaType = ""; 
    var MediaType = document.getElementById("MediaType"); 
    if(MediaType && MediaType.options.length > 0) 
    { 
        valueMediaType = MediaType.options[MediaType.selectedIndex].text; 
        if(valueMediaType != "") 
            if(!DWObject.Addon.Webcam.SetMediaType(valueMediaType)) 
            { 
                appendMessage('<b>Error setting MediaType value: </b>'); 
                appendMessage("<span style='color:#cE5E04'><b>" + DWObject.ErrorString + "</b></span><br />"); 
            } 
    } 
 
    var valueResolution = ""; 
    var ResolutionWebcam = document.getElementById("ResolutionWebcam"); 
    if(ResolutionWebcam && ResolutionWebcam.options.length > 0) 
    { 
        valueResolution = ResolutionWebcam.options[ResolutionWebcam.selectedIndex].text; 
        if(valueResolution != "") 
        DWObject.Addon.Webcam.SetResolution(valueResolution); 
        var aryResolution = DWObject.Addon.Webcam.GetResolution(); 
        if(valueResolution != aryResolution.GetCurrent()) 
        { 
            appendMessage('<b>Error setting Resolution value: </b>'); 
            appendMessage("<span style='color:#cE5E04'><b>" + DWObject.ErrorString + "</b></span><br />"); 
        } 
    } 
     
    var showUI = document.getElementById("ShowUIForWebcam").checked; 
 
    // optional 
    var OnCaptureStart = function () { 
    } 
    // optional 
    var OnCaptureSuccess = function () { 
    } 
    // optional 
    var OnCaptureError = function (error, errorstr) { 
        alert(errorstr); 
    } 
    // optional 
    var OnCaptureEnd = function () { 
        //Call DWObject.Addon.Webcam.CloseSource() to release webcam. 
        DWObject.Addon.Webcam.CloseSource(); 
        updatePageInfo(); 
    } 
 
    DWObject.Addon.Webcam.CaptureImage(showUI, OnCaptureStart, OnCaptureSuccess, OnCaptureError, OnCaptureEnd); 
     
}

 

Barcode Reader

 

JavaScript
Edit|Remove
function btnScanReadBarcode_onclick() { 
    if (!checkIfImagesInBuffer()) { 
        return; 
    } 
     
     var OnSuccess = function () { 
         //Get barcode result. 
        DWObject.Addon.Barcode.Read(DWObject.CurrentImageIndexInBuffer,  
        BarcodeInfo[document.getElementById("ddl_barcodeFormat").selectedIndex].val, GetBarcodeInfo, GetErrorInfo); 
    }; 
 
    var OnFailure = function(errorCode, errorString) { 
        appendMessage(errorString); 
    }; 
 
    var strhttp = "http:"; 
    if("https:" == document.location.protocol)  
        strhttp = "https:"; 
 
    if(Dynamsoft.Lib.env.bMac) 
        DWObject.Addon.Barcode.Download(strhttp + "//www.dynamsoft.com/Demo/DWT/Resources/addon/MacBarcode.zip", OnSuccess, OnFailure);   
    else 
    { 
        DWObject.Addon.Barcode.Download(strhttp + "//www.dynamsoft.com/Demo/DWT/Resources/addon/Barcode.zip", OnSuccess, OnFailure);  
    }   
}

 

PDF Rasterizer

 

JavaScript
Edit|Remove
function btnLoadPDF_onclick() { 
    var OnPDFSuccess = function () { 
        appendMessage("Loaded an image successfully.<br/>"); 
        updatePageInfo(); 
    }; 
 
    var OnPDFFailure = function (errorCode, errorString) { 
        checkErrorStringWithErrorCode(errorCode, errorString); 
    }; 
 
 
    var OnSuccess = function () { 
        DWObject.IfShowFileDialog = true; 
        DWObject.Addon.PDF.SetResolution(300); 
        DWObject.Addon.PDF.SetConvertMode(EnumDWT_ConverMode.CM_RENDERALL); 
        DWObject.LoadImageEx("", EnumDWT_ImageType.IT_PDF, OnPDFSuccess, OnPDFFailure); 
 
    }; 
 
    var OnFailure = function (errorCode, errorString) { 
        appendMessage(errorString); 
    }; 
 
    var strhttp = "http:"; 
    if ("https:" == document.location.protocol) 
        strhttp = "https:"; 
 
    if (Dynamsoft.Lib.env.bMac) { 
        DWObject.IfShowFileDialog = true; 
        DWObject.Addon.PDF.SetResolution(300); 
        DWObject.Addon.PDF.SetConvertMode(EnumDWT_ConverMode.CM_RENDERALL); 
        DWObject.LoadImageEx("", EnumDWT_ImageType.IT_PDF, OnPDFSuccess, OnPDFFailure); 
    } 
    else { 
        DWObject.Addon.PDF.Download(strhttp + "//www.dynamsoft.com/Demo/DWT/Resources/addon/Pdf.zip", OnSuccess, OnFailure); 
    } 
}
 

 

More Information

Video

https://youtu.be/mQEX0l3yz5U

Online Demo

https://www.dynamsoft.com/Demo/DWT/online_demo_scan.aspx