Monday, August 09, 2010

Rendering barcode in MVC project

To render barcode on web page, we could use TTS barcode font, some of them can be downloaded here for free.

I found some other method that doesn't requiring third-party fonts. One is call Zen Barcode Rendering Framework, it encapsulates the native rendering of barcode symbologies. Zen Barcode has a server side control BarcodeLabel, together with the barcode handler, it can display barcode on ASP.Net page.


To work with MVC project, I wrote a HTML helper method to render the image tag. Also to display a much friend jpg url, I also config a URL rewrite rule on IIS7. Below is the step by step guide:


1. First step is reference two DLLs:
Zen.Barcode.Core.dll
Zen.Barcode.Web.dll

2. Add HttpHandler to web.config so Zen Barcode will handling the .Barcode extension


type="Zen.Barcode.Web.BarcodeImageHandler, Zen.Barcode.Web,
Culture=Neutral, Version=2.0.3.0"/>


In IIS7, the handler also need to be added to system.webServer section.







Also add a namespace to web.config




3. Create HTML helper method for MVC view

With the helper function below, we can write the code in view like


<%= Html.BarcodeImage("634169458190082014")%>


Below is the helper function:


public static string BarcodeImage(this HtmlHelper htmlHelper, string text)
{
return BarcodeImage(htmlHelper, text, BarcodeSymbology.Code128);
}

public static string BarcodeImage(this HtmlHelper htmlHelper, string text, BarcodeSymbology symbology)
{
return BarcodeImage(htmlHelper, text, symbology, 2, 40, 1, 30);
}

public static string BarcodeImage(this HtmlHelper htmlHelper, string text, BarcodeSymbology symbology, int maxWidth, int maxHeight, int minWidth, int minHeight)
{
// Setup barcode image url
BarcodeImageUriBuilder builder = new BarcodeImageUriBuilder();
builder.Text = text;
builder.EncodingScheme = symbology;
builder.BarMinHeight = minHeight;
builder.BarMaxHeight = maxHeight;
builder.BarMinWidth = minWidth;
builder.BarMaxWidth = maxWidth;
string url = BuildEncodedParameter(builder.ToString());
return htmlHelper.Image(url, new { style = "border-width: 0px;" }).ToString();
}

private static string BuildEncodedParameter(string url)
{
if (string.IsNullOrEmpty(url))
url = "";
else
url = url.Replace(".Barcode","");

return "/barcode.jpg?" + url;

}


This helper method will render a img tag like below

 



The query string contains the base64 hash string of barcode information. It should be rewrited to an URL recognized by Zen HTTP handler.

4. URL Rewrite Rules in IIS7

 








This rule will rewrite the above URL to a format like below so Zen Handler can process

 
77u_QmFyY29kZVs0LDMwLDQwLDEsMl06NjM0MTY5NDU4MTkwMDgyMDE0OjE4MTQ4OTMyMQ2.Barcode



Done!