C# Barcode Reader Library
How to read, scan barcode image in ASP.NET Core web app using C#


Online C# tutorial for XImage.Barcode Reader in ASP.NET Core web application





In this C# tutorial, you will learn how to scan a uploaded file, and read barcodes from it using C# in ASP.NET Core Razor pages web app.

  • Setup a new ASP.NET Core web app and install packages and Barcode Scanner for .NET Core dlls
  • Create a Razor page to upload, read an image file or PDF, TIFF, Word, Excel, PowerPoint document
  • Specify the barcode type to read
  • Read, scan all barcodes from the uploaded file in ASP.NET Core web app

How to read barcodes in ASP.NET Core web app using C#

  1. Download XImage.Barcode Reader C# library
  2. Install C# library to read, scan barcodes
  3. Step by Step Tutorial
















Prerequisites


Download and install the following software on your computer







How to create QR Code barcode in ASP.NET Core web app using C#?


1. Create a new ASP.NET Core web app

Start Visual Studio 2022 and choose "Create a new project".

Choose "ASP.NET Core Web App" in the dialog, and then press "Next" button.




Create a new ASP.NET Core Web App project with name "RasterEdge.BarcodeReader.ASPNETCoreDemo".




Choose Framework as ".NET 6.0 (Long-term support)", and then press "Create" button.


Now, all Visual Studio generated files could be found in the Solution Explorer panel.




2. Install NuGet Packages and RasterEdge Barcode Scanner .NET DLLs

To install Barcode Scanner .NET dlls in your .NET Core projects, please go to page How to install DLLs on .NET Core app





3. Add C# code to create QR Code in ASP.NET Core web app



Edit file "Index.cshtml"

The cshtml page code will

  • Add one button, click to allow web user upload a local image file or PDF, Tiff, Word, Excel, PowerPoint document with barcodes inside
  • A drop down list with all supported barcode types. User needs choose one of them to scan the specific barcodes from file.
  • A scan button to start reading, scanning barcodes from uploaded image file or supported document




@page
@model IndexModel
@{
    ViewData["Title"] = "Scan Barcode";
}

<div class="text-center">
    <form enctype="multipart/form-data" method="post">
        <input asp-for="@Model.FormFile" type="file" style="width:300px; "
               onchange="document.getElementById('Submit').removeAttribute('disabled')" />
        &nbsp;&nbsp;
        Barcode Type:
        <select name="BarcodeType">
            @for (var i = 0; i < Model.BarcodeTypes.Length; i++)
            {
                @if (i == @Model.SelectedType)
                {
                    <option value="@i" selected>@Model.BarcodeTypes[i]</option>
                }
                else
                {
                    <option value="@i">@Model.BarcodeTypes[i]</option>
                }
            }
        </select>
        <br /><br />
        <input id="Submit" type="submit" value="Scan Image" disabled />
    </form>
    <br />
    <table name="ScanResult" class="table-bordered" style="width:60%;" align="center">
        <thead>
            <tr>
                <td colspan="4">Scan Result</td>
            </tr>
        </thead>
        <tbody>
            @if (Model.ResultCount >= 0)
            {
                <tr>
                    <td colspan="4" align="left">
                        Number of valid barcodes:&nbsp;&nbsp;@Model.ResultCount
                    </td>
                </tr>
            }
            @for (var i = 0; i < Model.ResultCount; i++)
            {
                var idx = i + 1;
                var msg = Model.Results[i].Data;
                var pageNum = (Model.Results[i].PageIndex < 0) ? "N/A" : "Page " + (Model.Results[i].PageIndex + 1).ToString();
                var direction = Model.Results[i].Direction;
                <tr>
                    <td style="width:5%;">@idx:</td>
                    <td align="left" style="width:60%;">'@msg'</td>
                    <td>@pageNum</td>
                    <td>@direction</td>
                </tr>
            }
        </tbody>
    </table>
</div>





Edit file "Index.cshtml.cs"

The ASP.NET Core C# source code will receive the user uploaded barcode image file or PDF, tiff document, and user specified barcode type, call RasterEdge barcode scanner for .NET sdk to scan the barcodes.

  • In method doScan(), the received file will be loaded into a BaseDocument object
  • Create a new ReaderSettings object to set the following barcode scan options
  •       Barcode type to scan
  •       Read single barcode or multiple barcodes

  • For image file, the code will scan the image and return all barcodes scanned.
  • For multi-page document (such as PDF, Tiff, Word, Excel, PowerPoint), the code will scan and read all barcodes from all pages
  • Return the all scanned barcodes with detailed information: number of barcodes, each barcode data message, page index, and barcode direction




using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RasterEdge.Imaging.Basic;
using RasterEdge.XImage.BarcodeScanner;
using RasterEdge.XDoc.TIFF;
using RasterEdge.XDoc.PDF;
using RasterEdge.XDoc.Word;
using RasterEdge.XDoc.Excel;
using RasterEdge.XDoc.PowerPoint;
using System.Drawing;

namespace RasterEdge.BarcodeReader.ASPNETCoreDemo.Pages
{
    public class BarcodeItem
    {
        public String Data = "";
        public int PageIndex = -1;
        public String Direction = "";
    }

    public class IndexModel : PageModel
    {
        public int SelectedType { get; set; } = 5;
        public String[] BarcodeTypes { get; set; } = new String[] {
            "AustraliaPost", "Codabar", "Code39", "Code39Extension", "Code93",
            "Code128", "DataMatrix", "EAN8", "EAN13", "Identcode",
            "IntelligentMail", "Interleaved2of5", "ISBN", "ISSN", "ITF14",
            "Leitcode", "PatchCode", "PDF417", "Planet", "Postnet",
            "QRCode", "RM4SCC", "UPCA", "UPCE"
        };
        public IFormFile? FormFile { get; set; }
        public int ResultCount { get; set; } = -1;
        public BarcodeItem[] Results { get; set; } = new BarcodeItem[0];

        public void OnGet()
        {
        }

        public Task<IActionResult> OnPost()
        {
            this.SelectedType = Int32.Parse(this.Request.Form["BarcodeType"]);

            if (this.FormFile != null)
            {
                var file = this.Request.Form.Files[0];
                using (MemoryStream ms = new MemoryStream())
                {
                    file.CopyTo(ms);

                    BarcodeItem[] result = doScan(ms);
                    if (result != null && result.Length > 0)
                    {
                        this.ResultCount = result.Length;
                        this.Results = result.ToArray();
                    }
                    else
                        this.ResultCount = 0;
                }
            }

            return Task.FromResult<IActionResult>(Page());
        }

        //  Scan barcode(s) from the stream.
        private BarcodeItem[] doScan(MemoryStream ms)
        {
            try
            {
                BaseDocument doc = tryLoadDocument(ms);

                ReaderSettings settings = new ReaderSettings();
                //  Set target barcode type
                settings.AddTypesToRead((BarcodeType)this.SelectedType);
                settings.NumberOfBarcodeToRead = NumberOfBarcodeToRead.MoreThanOne;

                List<BarcodeItem> result = new List<BarcodeItem>();
                //  Source stream is a document file.
                if (doc != null)
                {
                    float zoomRatio = 2F;
                    int pageCount = doc.GetPageCount();
                    for (int i = 0; i < pageCount; i++)
                    {
                        Bitmap bitmap = doc.GetPage(i).GetBitmap(zoomRatio);
                        Barcode[] tmp = RasterEdge.XImage.BarcodeScanner.BarcodeReader.ReadBarcodes(settings, bitmap);
                        result.AddRange(createResult(tmp, i));
                    }
                }
                //  Source stream is an image file.
                else
                {
                    Barcode[] tmp = RasterEdge.XImage.BarcodeScanner.BarcodeReader.ReadBarcodes(settings, new Bitmap(ms));
                    result.AddRange(createResult(tmp, -1));
                }

                return result.ToArray();
            }
            catch (Exception)
            {
                return null;
            }
        }

        //  Load document object from the stream; return null if not a valid PDF/TIFF/DOCX/XLSX/PPTX file.
        private BaseDocument tryLoadDocument(MemoryStream ms)
        {
            try
            {
                DocumentType docType = BaseDocument.DetermineDocumentType(ms);
                switch (docType)
                {
                    case DocumentType.PDF:
                        return (new PDFDocument(ms));
                    case DocumentType.TIFF:
                        return (new TIFFDocument(ms));
                    case DocumentType.DOCX:
                        return (new DOCXDocument(ms));
                    case DocumentType.XLSX:
                        return (new XLSXDocument(ms));
                    case DocumentType.PPTX:
                        return (new PPTXDocument(ms));
                    default:
                        return null;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        //  Convert scan result to BarcodeItem.
        //  pageIndex: -1 if the source file is an image file.
        private BarcodeItem[] createResult(Barcode[] result, int pageIndex)
        {
            if (result == null || result.Length == 0)
                return new BarcodeItem[0];
            BarcodeItem[] items = new BarcodeItem[result.Length];
            for (int i = 0; i < result.Length; i++)
            {
                items[i] = new BarcodeItem();
                items[i].Data = result[i].DataString;
                items[i].Direction = result[i].Direction.ToString();
                items[i].PageIndex = pageIndex;
            }
            return items;
        }
    }
}





4. Run web app

It is done. Now run the project.

It will launche the Kestrel web server and opens the default web browser.

Select and upload an image file (or PDF, TIFF document) with barcode, specify the barcode type, click button Scan Image to scan the barcodes