Barcode in mvc

Barcode in asp.net MVC (display as image in html)
Barcode can be generated very easily using zxing. Zxing is open source library which supports decoding and generating of barcodes (like QR Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within images.
barcode
Install Zxing.net from Nuget
The following barcodes are supported by the decoder:
UPC-A, UPC-E, EAN-8, EAN-13, Code 39, Code 93, Code 128, ITF, Codabar, MSI, RSS-14 (all variants), QR Code, Data Matrix, Aztec and PDF-417.
The encoder supports the following formats:
UPC-A, EAN-8, EAN-13, Code 39, Code 128, ITF, Codabar, Plessey, MSI, QR Code, PDF-417, Aztec, Data Matrix

Steps for generating barcode.
  • Create a new MVC Project
  • Right click on project in solution explorer and click. Manage nuget Packages
  • click on browse tab. Search for zxing.net
  • Click on install button on right side
Add the following Action Methods to your controller.
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using MVC_CRUD_ADO.DAL;
using MVC_CRUD_ADO.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZXing;
namespace MVC_CRUD_ADO.Controllers
{
public class UsersController : Controller
{

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

public ActionResult RenderBarcode(string userid)
{
Image img = null;
using (var ms = new MemoryStream())
{
var writer = new ZXing.BarcodeWriter() { Format = BarcodeFormat.CODE_128 };
writer.Options.Height = 80;
writer.Options.Width = 280;
writer.Options.PureBarcode = true;
img = writer.Write(userid);
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return File(ms.ToArray(), "image/jpeg");
}
}
}


View (DisplayBarcode.cshtml) should be like the following
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@{
ViewBag.Title = "DisplayBarcode";
}
<hr />
<div class="form-horizontal">
<div class="row">
<div class="col-md-8">
<img src="@Url.Action("RenderBarcode", "Users",new {userid="accus-7898"})" /><hr/>

</div>
</div>
<div class="row">
<div class="col-md-8">
<img src="@Url.Action("RenderBarcode", "Users",new {userid="1234567890"})" width="450" height="80" />
</div>
</div>
</div>

Post a Comment

0 Comments