Click here to Skip to main content
Click here to Skip to main content

Barcodes in ASP.NET applications

By , 21 Oct 2008
 

Introduction

In one of my projects, I needed to implement barcodes into an ASP.NET page. Unfortunately, the only way that I found was using a third party component. So, I decided to find a way to do it without using external components.

Using the code

First, you have to download a free barcode font. For this example, I used "IDAutomationHC39M" from IdAutomation. In this example, I used Barcode 39.

In WinForms applications, it is really easy to use Barcode fonts; just place a Label, and apply the free barcode font, and assign a value, and everything is ready.

In Webforms, things are different, because the application runs on the server. The barcode font must reside on the server. If we use a Label, the barcode font is located on the server, not on the client, so you will just see the value, not the barcode.

Well, let's start:

Just copy the barcode font into the windows\fonts folder of the server. The whole idea is to create a text with the font (a barcode), then create an image of it, and send it back to the client.

Here is a simple page with it:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace Barcodes
{

/// <summary />
/// Summary description for BarCode.
/// </summary />

public class BarCode : System.Web.UI.Page
{
    private void Page_Load(object sender, System.EventArgs e)
    {
         // Get the Requested code to be created.
         string Code = Request["code"].ToString();

         // Multiply the lenght of the code by 40 (just to have enough width)
         int w = Code.Length * 40;
    
        // Create a bitmap object of the width that we calculated and height of 100
         Bitmap oBitmap = new Bitmap(w,100);
    
        // then create a Graphic object for the bitmap we just created.
         Graphics oGraphics = Graphics.FromImage(oBitmap);
        
        // Now create a Font object for the Barcode Font
        // (in this case the IDAutomationHC39M) of 18 point size
        Font oFont = new Font("IDAutomationHC39M", 18);
        
        // Let's create the Point and Brushes for the barcode
        PointF oPoint = new PointF(2f, 2f);
         SolidBrush oBrushWrite = new SolidBrush(Color.Black);
         SolidBrush oBrush = new SolidBrush(Color.White);
            
        // Now lets create the actual barcode image
        // with a rectangle filled with white color
        oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
            
        // We have to put prefix and sufix of an asterisk (*),
        // in order to be a valid barcode
        oGraphics.DrawString("*" + Code + "*", oFont, oBrushWrite, oPoint);
        
        // Then we send the Graphics with the actual barcode
        Response.ContentType = "image/jpeg" ;
         oBitmap.Save (Response.OutputStream, ImageFormat.Jpeg);
    }
}
}

Let's test our page. Just call http://localhost/BarCodes/BarCode.aspx?Code=1234.

Pic1.png

As you can see, there is a barcode with the value of 1234.

Now, let’s create a page that has an asp:Image on it:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" 
   AutoEventWireup="false" Inherits="BarCodes.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm1</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" 
        content="http://schemas.microsoft.com/intellisense/ie5">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <asp:Image id="myBarCode"  runat="server"></asp:Image>
  </form>
 </body>
</HTML>

Add this to the code behind:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace BarCodes
{
    /// <summary />
    /// Summary description for WebForm1.
    /// </summary />
    public class WebForm1 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Image myBarCode;
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            myBarCode.ImageUrl = "BarCode.aspx?code=31231";
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        
        /// <summary />
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary />
        private void InitializeComponent()
        {    
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion
    }
}

Now, let’s see the result:

Pic2.png

Well friends, that is all! An easy and cheap way to have barcodes in your ASP.NET applications.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Erick Cuellar
Software Developer (Senior) INTERlink Software
Guatemala Guatemala
Member
I have been developing software for a while, using ASP.NET (since version 1.0) and C#.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionBarcode image is not displayingmembergeetha rangaiah15 May '13 - 22:33 
Questioncoupon on web sitesmemberTarcode Michael24 Dec '12 - 15:45 
AnswerRe: coupon on web sites [modified]memberMember 97323305 Jan '13 - 17:20 
GeneralMy vote of 3memberSahyadri315 Nov '12 - 0:20 
QuestionScanning the barcodememberpriti shrivastava29 Oct '12 - 22:44 
QuestionHow Can i use it from text boxmemberooffooooo7 Sep '12 - 22:36 
QuestionBarcodemembervsvarunsharma13 Aug '12 - 19:15 
GeneralMy vote of 5memberSavindraSingh10 Aug '12 - 4:12 
GeneralMy vote of 2memberPankil_cool16 Jul '12 - 5:28 
BugBarcode not working on server but localhostmemberMember 795278311 Jun '12 - 22:49 
GeneralMy vote of 5membermanoj kumar choubey23 Feb '12 - 21:06 
Questionbarcode control for asp.netmemberZacbr3 Feb '12 - 14:06 
Questionhow can I do to see the bar code in webform [modified]memberMember 850929422 Dec '11 - 21:32 
AnswerRe: how can I do to see the bar code in webformmembersteve7g10 Jan '12 - 16:34 
QuestionBarcode for Crystal ReportmemberMember 82184676 Sep '11 - 22:34 
AnswerRe: Barcode for Crystal ReportmemberIvy Shirley24 Nov '11 - 19:27 
QuestionBarCodes Generated Fine But Not being READmemberThe nk4 Aug '11 - 1:43 
AnswerRe: BarCodes Generated Fine But Not being READmemberIvy Shirley24 Nov '11 - 19:31 
GeneralMy vote of 2membereferreyra14 Jun '11 - 1:47 
GeneralRe: My vote of 2memberIvy Shirley24 Nov '11 - 19:48 
Questionbarcode generated fine, now how do i read it back thru the app?membergvozdik201119 Apr '11 - 4:33 
GeneralMy vote of 3memberRasha_200818 Apr '11 - 22:57 
GeneralThe barcode doesn't scanmemberAn Suri26 Jan '11 - 13:29 
GeneralRe: The barcode doesn't scanmemberIvy Shirley24 Nov '11 - 19:42 
GeneralThis is not freememberAmin J. Ismaili1 Nov '10 - 4:46 
Questionwhy my picture is not shown ?memberarya0128 Oct '10 - 19:37 
AnswerRe: why my picture is not shown ?memberIvy Shirley24 Nov '11 - 19:44 
GeneralMy vote of 5memberMember 164379217 Sep '10 - 4:40 
QuestionHas anyone been able to get around the huge whitespace to the right of the generated barcode image?membermbcrump23 Jul '10 - 4:23 
AnswerRe: Has anyone been able to get around the huge whitespace to the right of the generated barcode image?memberIvy Shirley24 Nov '11 - 19:38 
GeneralBarCode Image Worksmemberroopeshcb21 Jul '10 - 13:15 
GeneralRe: BarCode Image WorksmemberIvy Shirley24 Nov '11 - 19:34 
GeneralMy vote of 5memberSunasara Imdadhusen8 Jul '10 - 0:17 
GeneralResolved : Could not create font object of "IDAutomationHC39M"memberpravin dingore23 May '10 - 7:00 
GeneralRe: Resolved : Could not create font object of "IDAutomationHC39M"membersilvia.stanila5 Feb '11 - 8:54 
Questionhow can use barcode code in my web application [modified]memberkajal patoliya22 Mar '10 - 1:15 
AnswerRe: how can use barcode code in my web applicationmembersporting_proj27 Mar '11 - 19:04 
GeneralRe: how can use barcode code in my web applicationmemberIvy Shirley24 Nov '11 - 19:18 
AnswerRe: how can use barcode code in my web application [modified]memberIvy Shirley24 Nov '11 - 18:55 
AnswerRe: how can use barcode code in my web application [modified]memberIvy Shirley24 Nov '11 - 19:03 
Generalbarcode is not showing the imagemembergulam husain ansari14 Sep '09 - 21:17 
AnswerRe: barcode is not showing the imagememberErick Cuellar25 Oct '09 - 13:27 
QuestionSolid black barmemberholderag10 Jun '09 - 2:23 
General"Real" Free Barcode FontmemberMad-Halfling21 Apr '09 - 6:13 
QuestionI'm getting only the label (*1234*) not the bar code lines. What is the issue?. Please help mememberarunkumarsp13 Apr '09 - 0:34 
AnswerRe: I'm getting only the label (*1234*) not the bar code lines. What is the issue?. Please help mememberroopeshcb21 Jul '10 - 13:12 
GeneralRe: I'm getting only the label (*1234*) not the bar code lines. What is the issue?. Please help mememberadeelghaffar78620 Apr '11 - 0:41 
GeneralRe: I'm getting only the label (*1234*) not the bar code lines. What is the issue?. Please help memembercruzagr3 networks23 Nov '11 - 17:03 
GeneralBarcode workmemberSreepappu30 Nov '08 - 20:53 
GeneralGood WorkmemberManickarj28 Oct '08 - 19:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 21 Oct 2008
Article Copyright 2008 by Erick Cuellar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid