Generate BarCode in ASP.NET Core MVC

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




To generate BarCode, need install NuGet Packages as below:

Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreMVCWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Demo}/{action=Index}/{id?}");
            });
        }
    }
}




Create new folder named Controllers. In this folder, create new controller named DemoController.cs as below:

using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
    [Route("demo")]
    public class DemoController : Controller
    {
        [Route("~/")]
        [Route("")]
        [Route("index")]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [Route("generate")]
        public IActionResult Generate(string productId)
        {
            ViewBag.productId = productId;
            return View("Index");
        }
    }
}

Create new folder named Views. In this folder, create new folder named Demo. Create new view named Index.cshtml as below:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Generate BarCode in ASP.NET Core MVC</title>
</head>
<body>

    <h3>Generate BarCode in ASP.NET Core MVC</h3>
    <form method="post" asp-controller="demo" asp-action="generate">
        <input type="text" placeholder="Product Id" name="productId" value="@ViewBag.productId" />
        <input type="submit" value="Generate" />
    </form>
    <br />
    @if (@ViewBag.productId != null)
    {
        <barcode content="@ViewBag.productId" width="200" height="100" />
    }

</body>
</html>




Create new folder named Tags. In this folder, create new class as below:

using System;
using Microsoft.AspNetCore.Razor.TagHelpers;
using ZXing.QrCode;
using System.Drawing;
using System.IO;

namespace LearnASPNETCoreMVCWithRealApps.Tags
{
    [HtmlTargetElement("barcode")]
    public class BarCodeTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var content = context.AllAttributes["content"].Value.ToString();
            var width = int.Parse(context.AllAttributes["width"].Value.ToString());
            var height = int.Parse(context.AllAttributes["height"].Value.ToString());
            var barcodeWriterPixelData = new ZXing.BarcodeWriterPixelData
            {
                Format = ZXing.BarcodeFormat.CODE_128,
                Options = new QrCodeEncodingOptions
                {
                    Height = height,
                    Width = width,
                    Margin = 0
                }
            };
            var pixelData = barcodeWriterPixelData.Write(content);
            using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
            {
                using (var memoryStream = new MemoryStream())
                {
                    var bitmapData = bitmap.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                    try
                    {
                        System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
                    }
                    finally
                    {
                        bitmap.UnlockBits(bitmapData);
                    }
                    bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                    output.TagName = "img";
                    output.Attributes.Clear();
                    output.Attributes.Add("width", width);
                    output.Attributes.Add("height", height);
                    output.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(memoryStream.ToArray())));
                }
            }
        }
    }
}




Right click current project and select Razor View Imports and click Add button to finish. In _ViewImports.cshtml file, add TagHelpers libraries as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, LearnASPNETCoreMVCWithRealApps




Access Index action in Demo controller with following url: http://localhost:48982/Demo/Index

Output

Input Product Id and click Generate button to generate BarCode

Output