Crete BarCode and QRCode based on product


Create Product with Barcode & QRCode


Step 1: From the above url download the source file where u will get the FREE3OF9.TTF font inside Font folder. You just need to add this font into your application. Either you can paste the whole folder(Font) or a particular specified file by making a font folder inside your application.

Step 2: Create a table Product



Step 3: Create a model class BarCodeModel.cs which contains the following  
            Parameters

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace KendoControls.Models
{
    public class BarCodeModel
    {
        public int Product_Id { get; set; }
        public string Pro_Name { get; set; }
        public string Pro_Desc { get; set; }
        public byte[] BarCodeImage { get; set; }
        public byte[] QRCodeImage { get; set; }
        public string BarCode { get; set; }
        public string ImageUrl { get; set; }
        public string QrCodeImageUrl { get; set; }
    }
}

Step 4. Next Add a controller name BarCodeUpdated and add a view named Index

  public ActionResult Index()
        {
            return View();
        }

Step 5. Next right click on index and add view and write the below code in
                   View


model KendoControls.Models.BarCodeModel
@{
    ViewBag.Title = "Index";
    Layout = null;
}


@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset style="font-size:12px">
        <legend>Add Product</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Pro_Name, new { style="width:200px" })
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Pro_Name, new { style = "width:200px" })
            @Html.ValidationMessageFor(model => model.Pro_Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Pro_Desc, new { style = "width:200px" })
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Pro_Desc, new { style = "width:200px" })
            @Html.ValidationMessageFor(model => model.Pro_Desc)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

Step 6: For generating bar code, we are adding two classes, the first is "barcodecs" and the other is "BarCode39". Barcodecs class has two methods, the first is "generateBarcode" which is used for generating unique bar code number and the other method is "getBarcodeImage" which is used for creating bar code image using "Code 39 Font".

barcode39.cs" code is available in the given source code file. barcodecs.cs code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;

namespace BarCode.Models
{
    public class barcodecs
    {
        public string generateBarcode()
        {
            try
            {
                string[] charPool = "1-2-3-4-5-6-7-8-9-0".Split('-');
                StringBuilder rs = new StringBuilder();
                int length = 6;
                Random rnd = new Random();
                while (length-- > 0)
                {
                    int index = (int)(rnd.NextDouble() * charPool.Length);
                    if (charPool[index] != "-")
                    {
                        rs.Append(charPool[index]);
                        charPool[index] = "-";
                    }
                    else
                        length++;
                }
                return rs.ToString();
            }
            catch (Exception ex)
            {
                //ErrorLog.WriteErrorLog("Barcode", ex.ToString(), ex.Message);
            }
            return "";
        }       

        public Byte[] getBarcodeImage(string barcode, string file)
        {
            try
            {
                BarCode39 _barcode = new BarCode39();
                int barSize = 16;
                string fontFile = HttpContext.Current.Server.MapPath("~/fonts/FREE3OF9.TTF");
                return (_barcode.Code39(barcode, barSize, true, file, fontFile));
            }
            catch (Exception ex)
            {
                //ErrorLog.WriteErrorLog("Barcode", ex.ToString(), ex.Message);
            }
            return null;
        }
    }
}

Step 7: Now, create HttpPost Action method for getting posted data.

  public ActionResult Index(BarCodeModel model)
        {
            barcodecs objbar = new barcodecs();   
            using (MemoryStream ms = new MemoryStream())
            {
                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(model.Pro_Name, QRCodeGenerator.ECCLevel.Q);
                using (Bitmap bitMap = qrCode.GetGraphic(20))
                {
                    bitMap.Save(ms, ImageFormat.Png);
                    byte[] byteImage = ms.ToArray();
                    ViewBag.QRCodeImage = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
                    Product objprod = new Product()
                    {
                        Pro_Name = model.Pro_Name,
                        Pro_Desc = model.Pro_Desc,
                        BarCode = objbar.generateBarcode(),
                        QRCodeImage=byteImage
                    };
                    objprod.BarCodeImage = objbar.getBarcodeImage(objprod.BarCode, model.Pro_Name);
                    context.Products.Add(objprod);
                    context.SaveChanges();
                }
            }           
         
            return RedirectToAction("BarCode", "BarCodeUpdated");
        }

Step 8: Now, create another action method for displaying barcode. In this action method, we get data from database. The code is as given below: 

  //for displaying barcode
  public ActionResult BarCode()
        {   
           IList<BarCodeModel> model = new List<BarCodeModel>();
           var res = context.Products.ToList();
            for (int i = 0; i < res.Count; i++)
            {               
                var p = res[i].BarCodeImage;
                model.Add(new BarCodeModel()
                {
                    Pro_Name = res[i].Pro_Name.ToString(),
                    Pro_Desc = res[i].Pro_Desc.ToString(),
                    BarCode =  res[i].BarCode.ToString(),
                    ImageUrl = res[i].BarCodeImage != null ? "data:image/jpg;base64," +
                                Convert.ToBase64String((byte[])res[i].BarCodeImage) : "" ,
                    QrCodeImageUrl = res[i].QRCodeImage != null ? "data:image/jpg;base64," +
                                 Convert.ToBase64String((byte[])res[i].QRCodeImage) : ""
                }); 
            }
            return View(model);
        }


Step 9: Now, right click on BarCode() action method and add a new view for displaying barcode. Write the following code on BarCode.cshtml for displaying data.

@model IEnumerable<KendoControls.Models.BarCodeModel>
@{
    ViewBag.Title = "BarCode";
    Layout = "~/Views/Shared/_LayoutApplicantPortal.cshtml";
}


@{
    ViewBag.Title = "BarCode";
}


<p>
    <h4>@Html.ActionLink("Create New Product With Bar Code", "Index")</h4>
</p>
<table style="font-size:14px">
    <tr>
        <th style="padding-right: 53px;">           
            Name
        </th>
        <th style="padding-right: 53px;">
            Description
        </th>
        <th style="padding-right: 53px;">
            BarCode
        </th>
        <th style="padding-right: 53px;">
            ImageURl
        </th>
        <th style="padding-right: 53px;">
            QrCode ImageURl
        </th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>             
                @item.Pro_Name
            </td>
            <td>         
                @item.Pro_Desc
            </td>
            <td>
                @item.BarCode              
            </td>
            <td>
                <img src="@item.ImageUrl" />
            </td>
      <td>
                <img src="@item.QrCodeImageUrl" height="100" width="100"/>
            </td>
        </tr>
    }
</table>

Now, build and run your application.



After save the list will be shown



Comments

Popular posts from this blog

Kendo Control(Dynamics)

Override Authorize Filters in MVC

Form Validation