Friday, July 29, 2011

How to generate barcodes in C#?


Generating barcode is surprisingly very easy (at least in C#). Barcodes are another representation of the data (characters, numbers,etc) in a different font. To generate barcodes in your application you need to just display data in barcode fonts. There are number of free barcode fonts available. One such font is available here http://www.squaregear.net/fonts/free3of9.shtml. You could use your custom font as well.

From here I assume you have downloaded (and extracted) the above font files in F:\Downloads\free3of9 folder. I will be using the extended font in this example (fre3of9x.ttf). Also I assume you are using a windows form (C#) with a label named label1.

1.    First you need to create a font object in C# by loading the downloaded font into a font collection:

System.Drawing.Text.PrivateFontCollection fontCollection = new    System.Drawing.Text.PrivateFontCollection();

            fontCollection.AddFontFile(@"F:\Downloads\free3of9\fre3of9x.ttf");                        
FontFamily family = new FontFamily("Free 3 of 9 Extended", fontCollection);

Please note that “Free 3 of 9 Extended” is the typeface name of the barcode font downloaded from the url that I have mentioned above. You need to find out the typeface name for the barcode font that you download for your use. Specifying any other name will throw “Font cannot be found.” exception.

2.    Next you need to generate the barcode by setting the font of the label as below:
      Font font3of9 = new Font(family, 30);
            label1.Text = "This is a bar code font";
      label1.Font = font3of9;

Following is the entire barcode generation code in C#:

      private void Form1_Load(object sender, EventArgs e)
      {
System.Drawing.Text.PrivateFontCollection fontCollection = new
System.Drawing.Text.PrivateFontCollection();
fontCollection.AddFontFile(@"F:\Downloads\free3of9\fre3of9x.ttf");
FontFamily family = new FontFamily("Free 3 of 9 Extended", fontCollection);
Font font3of9 = new Font(family, 30);
           label1.Text = "This is a bar code font";
label1.Font = font3of9;
       }

The output will be as below:




Hope this post will be useful for someone as a starting point to generate barcode in C#.

Happy coding!!

3 comments:

Anonymous said...

Thanks for sharing this post. I think that we can also create barcode in image in C#. For example, mentioned on this link:
http://www.keepdynamic.com/csharp-barcode-generator/code-39.shtml

Anonymous said...

How to print the barcode ??

Makaveil Jojo said...

create barcodes windows forms c#

Post a Comment