How to Read Barcodes Online from a Web Application

Integrate barcode scanner to your web application in JavaScript

Barcodes are everywhere today. They are particularly popular with retail stores, for warehouse inventory applications, and more. Essentially, barcodes are important for applications where easily sharing information via computers or mobile devices is important.

As the hunger for more online information sharing and saving grows so too does the need to process barcode information from a web application. But how can you integrate barcode reading technology with web technologies?

If you have tried integrating a barcode with a web application before, you will know how time-consuming the task can be. However, with the help of Dynamsoft’s Dynamic Web TWAIN imaging SDK, you can make it happen in just a few minutes.

In this tutorial, I will show you step by step how to build a simple barcode reading web application. Here is a demo page of what we will be building. You can try the below demo online:

read barcode online demo

Try demo online

For this tutorial, you need a basic understanding of HTML and JavaScript. There is no CSS involved in this demo page. We’ll concentrate on the barcode functionality in this tutorial. You can add whatever styles you like afterward. Even if you are a novice to web programming, you will find this tutorial easy to follow. So just take it easy and have some fun.

Next, let’s go through the sample code by breaking it down to four steps:

  1. Start a Web Application
  2. Add Dynamic Web TWAIN to the HTML Page
  3. Use Dynamic Web TWAIN to Scan or Load Images
  4. Use Dynamic Web TWAIN Barcode Reader Add-on to Read Barcodes

In step 1, 2, and 3, we are integrating Dynamic Web TWAIN with your web application. This is a prerequisite for barcode processing as, in this case, Barcode Reader is an add-on of Dynamic Web TWAIN. For Dynamic Web TWAIN integration, we have covered this topic in a post: Build a Web Page to Scan Documents to PDF in Just 5 Minutes. The steps for this tutorial are almost the same. Here I will go through the first three steps very quickly. If you are already familiar with them, it’s okay to skip directly to step 4.

Step 1: Start a Web Application

You can get Dynamic Web TWAIN Barcode Reader Resources files after installing Dynamic Web TWAIN free 30-day trial.

Create an empty HTML page named readbarcode.html. Put it on the same folder as the Resources folder:
barcode reading demo filesystem

Step 2: Add Dynamic Web TWAIN to the HTML Page

Include dynamsoft.webtwain.initiate.js , dynamsoft.webtwain.config.js , and dynamsoft.webtwain.addon.barcode.js in the HTML head.

dynamsoft.webtwain.initiate.js and dynamsoft.webtwain.config.js are responsible for Dynamic Web TWAIN’s initialization, while dynamsoft.webtwain.addon.barcode.js provides all barcode related API interfaces:

<script type="text/javascript" src="Resources/dynamsoft.webtwain.initiate.js"> </script>
<script type="text/javascript" src="Resources/dynamsoft.webtwain.config.js"> </script>
<script type="text/javascript" src="Resources/addon/dynamsoft.webtwain.addon.barcode.js"> </script>

Add a div container for Dynamic Web TWAIN, and register the OnWebTwainReady event to get access to Dynamic Web TWAIN via DWObject:




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

}

Step 3: Use Dynamic Web TWAIN to Scan or Load Images

Add Scan and Load buttons to the page:

<input type="button" value="Scan" onclick="AcquireImage();" />
<input type="button" value="Load" onclick="LoadImage();" />

And add the implementation of function AcquireImage() and LoadImage(). Notice how LoadImage() handles success and failure with callback functions OnSuccess() and OnFailure() :

       function AcquireImage() {
           if (DWObject) {
               DWObject.SelectSource();
               DWObject.OpenSource();
                DWObject.IfDisableSourceAfterAcquire = true;  // Scanner source will be disabled/closed automatically after the scan.
               DWObject.AcquireImage();
           }
       }

       //Callback functions for async APIs
       function OnSuccess() {
           console.log('successful');
       }

       function OnFailure(errorCode, errorString) {
           alert(errorString);
       }

       function LoadImage() {
           if (DWObject) {
               DWObject.IfShowFileDialog = true; // Open the system's file dialog to load image
               DWObject.LoadImageEx("", EnumDWT_ImageType.IT_ALL, OnSuccess, OnFailure); // Load images in all supported formats (.bmp, .jpg, .tif, .png, .pdf). OnSuccess or OnFailure will be called after the operation
           }
       }

Step 4: Use Dynamic Web TWAIN Barcode Reader Add-on to Read Barcodes in JavaScript

Now you have two options to get the image loaded into Dynamic Web TWAIN:

  • Scan images from a scanner using AcquireImage();
  • Or load images from hard disk using LoadImage().

It’s time to add the Dynamic Web TWAIN Barcode Reader add-on to your web page.

Add a selection list for supported barcode formats:

<select size="1" id="barcodeformat" style="position: relative; width: 220px;"></select>

And populate it in function Dynamsoft_OnReady():

function Dynamsoft_OnReady() {

    DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');

    if (DWObject) {//Currently only code 39 and code 128 are supported

        document.getElementById("barcodeformat").options.add(new Option("Code 39", 1));

        document.getElementById("barcodeformat").options.add(new Option("Code 128", 0));

    }

}

Dynamic Web TWAIN Barcode Reader Add-on supports 1D barcodes and QR code, Datamatrix and PDF417. Supported 1D barcodes includes Code 39, Code 93, Code 128, Codabar, Interleaved 2 of 5, EAN-8, EAN-13, UPC-A, UPC-E, Industrial 2 of 5.

Now it comes to the most important part of this tutorial – barcode reading logic. Please notice that how callback functions are used to deal with the success and failure scenarios for barcode reading:

    function GetBarcodeInfo(sImageIndex, result) {
        //Retrieve barcode details
        var count = result.GetCount();
        if (count == 0) {
            alert("The barcode for the selected format is not found.");
            return;
        } else {
            for (i = 0; i < count; i++) {
                var text = result.GetContent(i);
                var x = result.GetX1(i);
                var y = result.GetY1(i);
                var format = result.GetFormat(i);
                var barcodeText = ("barcode[" + (i + 1) + "]: " + text + "\n");
                barcodeText += ("format:" + format + "\n");
                barcodeText += ("x: " + x + " y:" + y + "\n");
                alert(barcodeText);
            }
        }
    }
    //This is the function called when barcode reading fails
    function GetErrorInfo (errorcode, errorstring) {
        alert(errorstring);
    }
    function ReadBarcode() {
        var DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
        if (DWObject) {
            if (DWObject.HowManyImagesInBuffer == 0) {
                alert("Please scan or load an image first.");
                return;
            }

        <span style="display: inline-block; padding: 2px 4px; margin-bottom: 3px; background: #fffdb7;">DWObject.Addon.Barcode.Download(<span style="color: rgba(0, 0, 0, 0.870588);">"</span>http://localhost/dwt/addon/Barcode.zip<span style="color: rgba(0, 0, 0, 0.870588);">"</span>);</span>
        <span style="display: inline-block; padding: 2px 4px; background: #fffdb7;">//download barcode reader DLL to local. Please update the URL accordingly</span>
            //Get barcode result.
            switch (document.getElementById("barcodeformat").selectedIndex) {
                case 0:
                    result = DWObject.Addon.Barcode.Read(
                        DWObject.CurrentImageIndexInBuffer, EnumDWT_BarcodeFormat.CODE_39, GetBarcodeInfo, GetErrorInfo);
                    break;
                case 1:
                    result = DWObject.Addon.Barcode.Read(
                        DWObject.CurrentImageIndexInBuffer, EnumDWT_BarcodeFormat.CODE_128, GetBarcodeInfo, GetErrorInfo);
                    break;
                default:
                    break;
            }
        }
    }

Now, save the file.

Okay, we are all set. You can open readbarcode.html in a browser and start barcode reading.

NOTE:

  • If you are getting “Invalid license”, please contact support@dynamsoft.com for a license extension.
  • If you are getting error “barcode dll is missing”, please make sure the download URL in DWObject.Addon.Barcode.Download() is correct. 

Conclusion

Use of Dynamic Web TWAIN Barcode Reader Add-on makes integration of barcode reading into a web page pretty easy. All mainstream browsers (Internet Explorer 32 and 64-bit, Chrome, Firefox) on Windows are supported by Barcode Reader Add-on.

I hope you enjoyed following along. Please contact us if you have any questions regarding barcode processing.

P.S. if you need to read barcodes from a desktop application, please check out Read Barcode from Images in C# or How to Read Barcode in WPF with VB.NET .

Resources

Get sample code>>

Get a 30-day free trial of Dynamic Web TWAIN>>