Create a Barcode Generator Web App in ASP.NET Core

In my previous two posts, provide code examples to develop QR code generator web apps in ASP.NET Core, both in the MVC structure and in ASP.NET Razor Pages

Here this post will demonstrate and share code example how to develop a web site in ASP.NET core using Razor page which helps you to develop barcode maker online applications.

Before starting, I want to give a sort of description about barcode which will help you to build a quality barcode creator online application.

What is Barcode

A barcode is a machine-readable representation of data that is visually encoded in a series of parallel bars and spaces. Barcodes are commonly used in retail, logistics, inventory management, and other systems that require quick and accurate data entry.

Barcode Type

There are several types of barcodes, each designed for specific uses. The most common barcode types include:

1. Linear Barcodes OR 1D Barcodes

These barcodes encode data in a series of varying-width parallel lines (bars) and spaces. They are typically used for tracking individual products in stores or warehouses.

Common 1D Barcodes:

  • UPC (Universal Product Code): Used primarily in North America for retail products.
  • EAN (European Article Number): Similar to UPC, but used internationally.
  • Code 128: A very dense barcode used in shipping and packaging.
  • Code 39: Used in automotive and industrial applications.

Example of a 1D Barcode (Code 128):

 | || | | || | | ||| |  

2. Matrix Barcodes OR 2D Barcodes

These barcodes encode data in both horizontal and vertical dimensions, allowing them to hold much more information than 1D barcodes. They are used for applications that require storage of large amounts of data, such as product tracking, ticketing, and mobile marketing.

Common 2D Barcodes:

  • QR Code (Quick Response Code): Popular in marketing, product labeling, and mobile applications.
  • Data Matrix: Used in industrial and healthcare applications.
  • PDF417: Used in transport and logistics, often for boarding passes and ID cards.

Example of a 2D Barcode (QR Code):

 [ ] [ ] [ ] [ ]   
 [ ] [ ] [ ] [ ]   
 [ ] [ ] [ ] [ ]  

3. How Barcodes Work

  • Reading a Barcode: A barcode scanner emits light onto the barcode. The light is reflected back, and the scanner detects the difference in light between the bars (dark) and spaces (light).
  • Decoding the Barcode: The scanner converts the pattern of bars and spaces into binary data, which is then mapped to a product ID, URL, or other relevant information.

4. How to Generate a Barcode

To generate a barcode (whether 1D or 2D), you can use various libraries or tools depending on your programming language or platform.

Barcode Generator Libraries:

  • ZXing.Net: A .NET library for barcode generation and scanning.
  • Barcode4J: A Java library for generating barcodes.
  • pyBarcode: A Python library to generate barcodes.

Getting Started

To create a barcode generator website in ASP.NET Core, you can follow these steps. This guide will help you set up a simple web application that generates barcodes from user input.

Prerequisites:

  • Install .NET SDK (version 6 or later).
  • Install a code editor like Visual Studio or Visual Studio Code.
  • Basic understanding of C# and ASP.NET Core.

Demonstration

In this demonstration, we will create a web site in ASP.NET Core that will offer Barcode code generator functionality. Here use will use the ASP.NET Razer page.

Step-1 : Create Web App Development Template

ASP.NET Core provides web application development template to develop web app, the below steps guides to create template:

  1. Make sure you have installed Microsoft Visual Studio, here I have used Microsoft Visual Studio version 2022.
  2. Open the Visual Studio and click on the Create a new project.
  3. The Create a new project window will appear.
    • Find the ASP.NET Core Web App (Razor Page) template.
    • Select the template and click on the Next button.
  4. Then Configure your new project window will appear.
    • Give the name BarCodeGenerator to your project.
    • Click on the Next button.
  5. Additional information windows will be displayed.
    • Select .Net 8.0 as framework.
    • Uncheck the Do not use top-level statements if checked.
    • Click on the Create button.
  6. You are done with ASP.NET Core Web site template.

Step-2 : Install Barcode Generator Library

You will need a barcodes generator library. One popular library is ZXing.Net, which supports generating different types of barcodes.

To download the ZXing.Net NuGet package using Visual Studio, follow these steps:

  1. Open your project in Visual Studio: Launch Visual Studio and open the project where you want to add the ZXing.Net package.
  2. Open the NuGet Package Manager:
    • Right-click on your project in the Solution Explorer.
    • Select Manage NuGet Packages from the context menu.
  3. Search for ZXing.Net:
    • In the NuGet Package Manager window, click on the Browse tab.
    • In the search box, type ZXing.Net and press Enter.
  4. Install the package:
    • Find ZXing.Net in the search results.
    • Click the Install button next to ZXing.Net.
    • Accept any license agreements that appear.
  5. Verify Installation:
    • After the package is installed, you will see it listed under the Installed tab in the NuGet Package Manager.
    • You can also verify that the package is installed by checking the References in the Solution Explorer.

Step -3: Add Web Page

The third step is to add a webpage into template where we will write the barcode maker code, here we will add an ASP.NET Razor page to the project that will work as a barcode builder, here are the steps:

  1. Go to Solution Explorer.
  2. Right-click on the Pages folder > Add > New Item.
  3. The Add New Item window will appear, in the dialog:
    • Select Razor Page-Empty.
    • Click on the Add button.
    • Give the name to the page Barcodegenerator.cshtml

4. Add Barcode Generator UI (BarcodeGenerator.cshtml)

This above created page will contain the user interface for inputting data and displaying the barcode. thus the below code add UI elevent for that

 @page  
 @model BarcodeGeneratorModel  
 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
   <meta charset="UTF-8">  
   <meta name="viewport" content="width=device-width, initial-scale=1.0">  
   <title>Barcode Generator</title>  
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.3.1/css/bootstrap.min.css">  
 </head>  
 <body>  
   <div class="container">  
     <h1 class="mt-5">Barcode Generator</h1>  
     <!-- Form to input barcode data -->  
     <form method="post" class="mt-3">  
       <div class="form-group">  
         <label for="barcodeData">Enter Data for Barcode:</label>  
         <input type="text" id="barcodeData" name="barcodeData" class="form-control" required />  
       </div>  
       <button type="submit" class="btn btn-primary mt-3">Generate Barcode</button>  
     </form>  
     <!-- Display barcode image -->  
     @if (Model.BarcodeImage != null)  
     {  
       <h3 class="mt-4">Your Barcode:</h3>  
       <img src="@Model.BarcodeImage" alt="Barcode" class="mt-2" />  
     }  
   </div>  
 </body>  
 </html>  

5. Implement Barcode Generator Logic (BarcodeGenerator.cshtml.cs)

Create the BarcodeGeneratorModel in the BarcodeGenerator.cshtml.cs file to handle form submission and barcode generation.The below code will add Razor Page model to handle the barcode generation logic.

 using Microsoft.AspNetCore.Mvc;  
 using Microsoft.AspNetCore.Mvc.RazorPages;  
 using ZXing;  
 using System.IO;  
 namespace YourProjectNamespace.Pages  
 {  
   public class BarcodeGeneratorModel : PageModel  
   {  
     [BindProperty]  
     public string BarcodeText { get; set; }  
     public string BarcodeImage { get; set; }  
     public void OnGet()  
     {  
       // No barcode is generated on the initial page load  
     }  
     public void OnPost()  
     {  
       if (!string.IsNullOrEmpty(BarcodeText))  
       {  
         var barcodeWriter = new BarcodeWriter  
         {  
           Format = BarcodeFormat.CODE_128, // Set your desired barcode format here  
           Options = new ZXing.Common.EncodingOptions  
           {  
             Width = 300, // Width of the barcode image  
             Height = 150 // Height of the barcode image  
           }  
         };  
         // Generate barcode from the input text  
         var barcodeBitmap = barcodeWriter.Write(BarcodeText);  
         // Convert the barcode image to base64 string for embedding in the page  
         using (var ms = new MemoryStream())  
         {  
           barcodeBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);  
           var byteArray = ms.ToArray();  
           BarcodeImage = "data:image/png;base64," + Convert.ToBase64String(byteArray);  
         }  
       }  
     }  
   }  
 }  

Explanation:
  • Barcode Generation (Index.cshtml.cs):

    • We use ZXing.Net's BarcodeWriter to create a barcode with the text "123456789". You can change this to any text or data you want to encode.
    • The barcode is generated as a Bitmap and then converted to a Base64 string, which is used to render it in the HTML.
  • Displaying the Barcode (Index.cshtml):

    • The barcode image is displayed by setting the src attribute of the <img> tag to a data URL (data:image/png;base64,@Model.BarcodeImageBase64).

Step 6: Configure Services in Startup (if needed)

Ensure that you have configured Razor Pages in your Startup.cs or Program.cs (depending on your version of ASP.NET Core). Usually, this is already done if you’ve generated your Razor Pages project properly, but you can check if Razor Pages is registered like this:

Startup.cs
 public void ConfigureServices(IServiceCollection services)  
 {  
   services.AddRazorPages();  
 }  

Program.cs

Add the below code after the CreateBuilder function call.

 // Add services to the container.  
 builder.Services.AddRazorPages();  

Step 7: Run the Application

After setting up everything, you can now run the application. When you navigate to the /BarcodeGenerator page, you should be able to input text, submit the form, and see the generated barcode displayed as an image.

Summary

This approach uses ZXing.Net to generate a barcode dynamically and then displays it in your Razor Pages view. You can customize the barcode format (e.g., CODE_128, QR_CODE, EAN13, etc.) and the barcode content (e.g., serial numbers, product IDs).

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال