Generate and Display Barcode image in ASP .NET MVC

In this article, I will explain that how can we dynamically generate and display the Barcode image using ASP .Net MVC. So let’s start it.

So first step that you will need to follow is

Download the Barcode fonts

Before start, you will need to download the Barcode fonts. Here I’m using the IDAutomationHC39M Free Version fonts. You can download it from here.  After downloading the fonts, extract the zip file and open the file then click on the install button. Once installation is completed, restart your PC.

Controller

Below is my controller code. In the controller, the BarCode method is for the view, which will allow you to generate the Barcode code. The GenerateBarcode method is using for generating the Barcode and return the Barcode image string.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GenerateBarcode.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult BarCode()
        {
            return View();
        }
        public string GenerateBarcode(string barcode)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (Bitmap bitMap = new Bitmap(barcode.Length * 40, 80))
                {
                    using (Graphics graphics = Graphics.FromImage(bitMap))
                    {
                        Font font = new Font("IDAutomationHC39M Free Version", 16);
                        PointF point = new PointF(2f, 2f);
                        SolidBrush whiteBrush = new SolidBrush(Color.White);
                        graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
                        SolidBrush blackBrush = new SolidBrush(Color.DarkBlue);
                        graphics.DrawString("*" + barcode + "*", font, blackBrush, point);
                    }
                    bitMap.Save(memoryStream, ImageFormat.Jpeg);
                    return "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray());
                }
            }
        }
    }
}

View

@{
    ViewBag.Title = "BarCode";
}
<style>
    .d-none{
        display:none;
    }
</style>
<h2>Generate Barcode</h2>
<br /><br /><br />
<div class="row">
    <div class="col-lg-4">
        <div class="form-group">
            <label>Enter something to generate the barcode of it.</label>
            <input type="text" class="form-control" id="barcodeInput" required/>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-lg-1">
        <button class="btn btn-primary" id="GenerateBarcode">Generate</button>
    </div>
</div>
<br /><br /><br />
<div class="row">
    <div class="col-lg-4">
        <img src="" alt="BarcodeImage" id="BarcodeImage" class="d-none" />
    </div>
</div>

Script

Script has an ajax call that calls the GenerateBarcode function from the controller and displays the barcode on view.

<script>
        $(document).ready(function () {
            $('#GenerateBarcode').click(function () {
                if ($('#barcodeInput').val() != '') {
                    $.ajax({
                        url: '/Home/GenerateBarcode',
                        data: { 'barcode': $('#barcodeInput').val() },
                        success: function (result) {
                            if (result != '' && result != undefined && result != null) {
                                debugger
                                $('#BarcodeImage').removeClass('d-none');
                                $('#BarcodeImage').attr('src', result);
                            }
                            else {
                                $('#BarcodeImage').addClass('d-none');
                            }
                        },
                        error: function () {
                            alert('Something went wrong.');
                        }
                    });
                }
                else {
                    alert('Please enter something to genrate barcode.');
                }
            });
        });
    </script>

Output

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories