Wednesday, 10 January 2018

Dynamically generate and display Barcode Image in ASP.Net MVC

ASP.Net MVC: Dynamically generate and display Barcode Image

Description:

In this example we explain that how to dynamically generate the Barcode Image in Asp.Net MVC.or how to create Dynamically Barcode in MVC using Razor View. Or how to dynamically generate Barcode and display it in Razor View in MVC.

Here we use the .Net Graphics API to generate or display Barcode in MVC Razor view.so how to create Barcode in MVC Razor.
Controller:

public class EmployeeController : Controller
    {

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

        [HttpPost]
        public ActionResult Index(string barcode)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                //The Image is drawn based on length of Barcode text.
                using (Bitmap bitMap = new Bitmap(barcode.Length * 40, 80))
                {
                    //The Graphics library object is generated for the Image.
                    using (Graphics graphics = Graphics.FromImage(bitMap))
                    {
                        //The installed Barcode font.
                        Font oFont = new Font("IDAutomationHC39M", 16);
                        PointF point = new PointF(2f, 2f);

                        //White Brush is used to fill the Image with white color.
                        SolidBrush whiteBrush = new SolidBrush(Color.White);
                        graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);

                        //Black Brush is used to draw the Barcode over the Image.
                        SolidBrush blackBrush = new SolidBrush(Color.Black);
                        graphics.DrawString("*" + barcode + "*", oFont, blackBrush, point);
                    }

                    //The Bitmap is saved to Memory Stream.
                    bitMap.Save(ms, ImageFormat.Png);

                    //The Image is finally converted to Base64 string.
                    ViewBag.BarcodeImage = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
                }
            }

            return View();
        }
    }

View:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>ASP.Net MVC: Dynamically generate and display Barcode Image</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
    {
        <input type="text" name="barcode"/>
        <input type="submit" value="Generate Barcode"/>
    }
    <hr/>
    @if (ViewBag.BarcodeImage != null)
    {
        <img src="@ViewBag.BarcodeImage" alt=""/>
    }
</body>
</html>






0 comments:

Post a Comment