How to Create Your Own Barcodes in ASP.NET
What Will I Learn?
Creating Code 39 barcodes using ASP.NET.
Requirements
- ASP.NET Core
Difficulty
Intermediate
Tutorial Contents
- An Overview of the Code 39 Barcode Symbology
- Techniques for Generating Code 39 Barcodes
- Creating a Code 39 Barcode Using the Code39BarCode Class
How to Create Your Own Barcodes in ASP.NET
Barcodes offer an optical, machine-readable representation of data and are used to automate the identification and collection data. Nearly every item for sale at a grocery store or retailer has a barcode on it, which is used to identify the product being purchased at the checkout line. Airlines use barcodes to identify and track luggage. And many medium- to large-sized businesses use barcodes to track and manage office equipment, such as laptops.
One of my clients builds web-based order management software for print shops. I was recently tasked with enhancing the work order, invoice, and shipping label reports to include the order's job number in barcode form. By providing the job number in an optical, machine-readable format, those print shops using barcode readers at point of sale terminals could more quickly identify and process orders and returns.
A barcode is nothing more than an optical representation of a string. How that string gets converted into a barcode – and what characters can be part of that string – depends on the barcode's symbology. There are numerous standardized barcode symbologies used in industry. The Universal Product Code (UPC) symbology can encode the digist 0 through 9 and is most commonly used to identify products for sale. Other common barcode symbologies include Code 39 and Code 128.
This tutorial explores how to programmatically generate and display Code 39 barcodes using ASP.NET and the GDI+ classes in the System.Drawing
namespace.
An Overview of the Code 39 Barcode Symbology
The Code 39 symbology defines 43 characters: uppercase letters (A-Z), digits (0-9), and the characters -, ., $, /, +, %, space, and *. The * character is a special character used to denote the start and stop of the barcode and therefore cannot appear in the string to translate into a barcode. Code 39 is a simple, popular symbology that can is understood by virtually all barcode readers.Each character in the 43-character alphabet is represented as a unique series of thick and narrow black and white bars. Figure 1 shows the Code 39 representation of the characters A, B, and C.
The Code 39 encoding for the characters A, B, and C.
Constructing a valid Code 39 barcode entails taking the input string – say, ASP.NET IS FUN – surrounding it by the start and stop delimiters (asterisks) – *ASP.NET IS FUN* – and then concatenating the corresponding barcode encodings for each character in the string, adding a white, narrow space between each encoded character.
The Code 39 barcode for the input text, ASP.NET IS FUN
Techniques for Generating Code 39 Barcodes
There are a variety of commercial third-party barcode components for ASP.NET that can be had for a few hundred dollars. These components are designed to simplify creating barcodes, provide controls for WinForms, ASP.NET, WPF, and Silverlight, and support a variety of symbologies. If all you need to do is generate Code 39 barcodes then these packages are overkill, but if you need robust support for working with barcodes, consider using to a third-party component.
Another option is to install a Code 39 font on the web server. Because Code 39 barcodes are a concatenation of encoded characters you can generate a barcode by simply "writing" the barcode string using an appropriate font. There are some challenges in this space. First, you have to install a font on the web server, which means if your website runs on a shared web hosting environment you're out of luck. Second, you can't just write the barcode in HTML, as the user visiting your site is unlikely to have the barcode font installed on her computer. Instead, you'll need to "write" the barcode to an image and then serve that image to the user. Third, you might not be able to use a free Code 39 font. IDAutomation provides a free Code 39 barcode font for small businesses and non-profits, but larger organizations will need to purchase it.
Yet another option, and the one we explore in this article, is to programmatically generate the barcode on the fly using the GDI+ classes in the System.Drawing
namespace.
Creating a Code 39 Barcode Using the Code39BarCode Class
To assist with creating Code 39 barcodes from an ASP.NET application I created a class named Code39BarCode
. To create a barcode using this class you:
- Create an instance of the
Code39BarCode
class. - Set the germane properties. At minimum you'd need to set the
BarCodeText
property, which specifies the string that is to be translated into barcode form. - Call the class's
Generate
method, which generates an image in memory and returns the image's binary content.
In addition to the BarCodeText
property the Code39BarCode
class includes six additional public properties:
BarCodeWeight
– indicates the thickness of the barcode lines. Defaults toSmall
, which renders narrow lines 1 pixel wide and thick lines 3 pixels wide. Setting this property toMedium
renders narrow and thick lines 2 and 6 pixels wide, respectively.Large
renders narrow and thick lines 3 and 9 pixels wide, respectively.BarCodePadding
– indicates the padding (in pixels) between the border of the image and the barcode within the image. Defaults to 5.ShowBarCodeText
– a Boolean value that indicates whether to include the barcode text in the image itself. Defaults totrue
.BarCodeTextFont
– the font used to display the barcode text. Defaults to Arial font, 10.0pt.Height
– the height of the image in pixels. Defaults to 75. The height of the barcode itself is determined by this property, whether or not the barcode text is displayed, and theBarCodePadding
value.ImageFormat
– the image format of the rendered barcode. Defaults toImageFormat.Gif
.
The code snippet in Listing 1 shows the above three steps in action. Here a new barcode is created that represents the input string HELLO WORLD. The barcode's BarCodeWeight
property is set to Medium
and the Height to 100 pixels. The barcode is then generated. The resulting byte
array is saved to disk to a file named barcode.gif
. Figure 3 shows the generated barcode.
Listing 1: The barcode HELLO WORD is created and saved to disk.
// Create a Code39BarCode object
var barcode = new Code39BarCode()
{
BarCodeText = "HELLO WORLD",
BarCodeWeight = BarCodeWeight.Medium,
Height = 100
};
// Generate the barcode
byte[] fileContents = barcode.Generate();
// Save the barcode byte array to disk
string filePath = Server.MapPath("~/barcode.gif");
File.WriteAllBytes(filePath, fileContents);;
The Code 39 barcode generated by the Code39BarCode class.
To display a generated barcode in a web page you have two options:
- Save the generated barcode image to the web server's file system and then render an
<img>
element whosesrc
attribute references the saved barcode image. The barcode generated in Listing 1 could be referenced via an<img>
element like so:<img src="barcode.gif"
/>. - Create an HTTP Handler (or action, in ASP.NET MVC) that returns the binary content of the generated barcode image. Using this approach you would have an
<img>
element in the web page whosesrc
attribute references the HTTP Handler (or action), passing the details about the barcode to generate via the querystring. This approach is generally preferred since it does not clutter the web server's file system with one-time use barcode files.
To demonstrate using the latter style I included a suitable HTTP Handler and controller action in the WebForms and ASP.NET MVC demos. Let's focus on the WebForms demo's HTTP Handler, which is located in the website's root directory and is named ShowCode39BarCode.ashx
.
An HTTP Handler is the class that is invoked in response to a particular request made to an ASP.NET application. In a nutshell, when a suitable request arrives, ASP.NET instantiates the HTTP Handler and invokes its ProcessRequest
method. The ProcessRequest
method is passed an HttpContext
object that has references to the intrinsic server objects: Request
, Response
, Session
, and so on. The ProcessRequest
method is responsible for generating the output that is to be returned to the client. Unlike an ASP.NET WebForms page there is no design surface or Web controls. Instead, you must programmatically return the raw content.The ShowCode39BarCode.ashx
HTTP Handler is tasked with creating a Code 39 barcode and returning the binary contents of the generated barcode image. It accepts the following configuation settings via the querystring:
Code
– the barcode text (required).ShowText
– specifies whether to display the text in the barcode image. If omitted, the text is displayed; to hide the text, send in a value of 0.Thickness
– the barcode weight to use; can be 1, 2, or 3. If omitted, defaults to 1.Height
– the height of the barcode image. If omitted, theCode39BarCode
class's default value is used (75).
To display a barcode in a web page you'd add an <img>
element whose src
attribute points to the ShowCode39BarCode.ashx
HTTP Handler and passes in the appropriate information via the querystring. For example, the following <img>
element would generate the same HELLO WORLD barcode with a Medium
barcode weight and a height of 100 pixels that was created in Listing 1:
<img src="ShowCode39BarCode.ashx?Code=HELLO+WORLD&Thickness;=2&Height;=100" />
Listing 2 shows the ShowCode39BarCode.ashx
HTTP Handler's ProcessRequest
method. Note that is starts by setting the response ContentType
to image/gif
. This informs the browser that it is receiving a GIF. Next, the Code39BarCode
class is created and its properties are set based on the querystring parameters. Following that, the barcode is generated and the byte
array returned by the Generate
method is streamed directly down to the client using the Response.BinaryWrite method.
Listing 2: The ProcessRequest method creates the barcode and sends its binary content to the client.
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "image/gif";
var barcode = new Code39BarCode();
// Read in the user's inputs from the querystring
barcode.BarCodeText = context.Request.QueryString["code"].ToUpper();
barcode.ShowBarCodeText = context.Request.QueryString["ShowText"] != "0";
if (context.Request.QueryString["thickness"] == "3")
barcode.BarCodeWeight = BarCodeWeight.Large;
else if (context.Request.QueryString["thickness"] == "2")
barcode.BarCodeWeight = BarCodeWeight.Medium;
if (!string.IsNullOrEmpty(context.Request.QueryString["Height"]))
barcode.Height = Convert.ToInt32(context.Request.QueryString["Height"]);
context.Response.BinaryWrite(barcode.Generate());
}
Be sure to download the code associated with this article, as it includes the complete code for the Code39BarCode
class and WebForms and ASP.NET MVC applications that demonstrate how to use the class. To convince yourself that the barcode was correctly rendered and would be decodable by barcode readers, save the generated barcode to disk and then upload it to a free online barcode reader.
Happy Programming!
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Hey @evariste I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x
Cool post! I give you a Upvote!