DIY

How do I... Generate barcodes using C#?

<img src="http://t.cbsimg.net/i/z/200606/how_110x85.jpg" align="right" border="0" height="85" hspace="5" vspace="5" width="110" />There are many libraries that you can buy to generate barcodes from the .NET Framework. But why buy one when you could use a free font in conjunction with a few GDI+ functions? Zach Smith shows you how to use the "Free 3 of 9" font with the Bitmap and Graphics objects to generate barcodes using C#.

There are many different kinds of barcodes. The format we're dealing with here is called "3 of 9" (also referred to as Code 39). Most all third-party component libraries can generate these codes -- but there are also other options for generating 3 of 9 barcodes. The option we're going to use for this How do I is a free font created by Matthew Welch called "Free 3 of 9." This font is 100 percent free, you pay nothing, and you're even allowed to use it in commercial applications!

This blog post is also available in PDF form in a TechRepublic download.

Using Free 3 of 9

We are going to use the Free 3 of 9 font to in conjunction with the .NET Framework's GDI functionality to render the data presented by the font into a bitmap. Once we have that bitmap we can manipulate it in various ways until it is the size/shape we want. First you will need to download Free 3 of 9.

After you've downloaded the zip file extract the two font files contained within onto your desktop. From there drag and drop the files into your font directory. For XP, Vista, and 2003 server this directory is "C:\WINDOWS\Fonts\". As you move the font files into the font directory the fonts are automatically installed. To test that the font is installed open notepad and see if you can change the font to Free 3 of 9.

Creating the barcode image

As mentioned above, we'll be writing the barcode out onto a bitmap using GDI. The code in Listing A shows a function which takes a string as a parameter and returns a bitmap.

Listing A

Create a barcode

There are a couple points to make here:

  • We have a kind of chicken and the egg problem with our Graphics and Bitmap objects. We need the Graphics object to determine the size of our Bitmap, and we need the Bitmap to get the Graphics object! This seems unclean but the performance isn't really affected by it. The code shown generates well over 500 barcodes per second.
  • We're setting the background of the image to white in this example, but you can also set the background to transparent or any other color.
  • We use the SingleBitPerPixel TextRenderingHint. If you use a different hint (ie AntiAlias) you risk having the barcode come out blurry, and that could render the code unreadable. Using SingleBitPerPixel forces the font to be rendered with sharp edges.
  • We use a font size of 60. It is important that our barcode is large enough to be clearly read. The size is up to you though, and you may be able to get away with using a smaller font.
  • The Free 3 of 9 font uses the asterisk character as a special character that symbolizes the beginning and end of the barcode. You'll need to wrap the data you pass to the CreateBarcode function in asterisks, or modify the CreateBarcode method to do this automatically.

Converting the barcode to other image formats

There are times when you need a barcode to be presented as either a JPEG or GIF -- one instance is when customers will be printing the codes from your Web site. Doing this is easy when you use the CreateBarcode function as a base -- the code to convert the returned bitmap to a GIF is shown in Listing B.

Listing B

Convert to .GIF

To convert the bitmap to a JPEG simply replace ImageFormat.Gif with ImageFormat.Jpeg and change the file extension to ".jpg".

Streaming barcodes from ASP.NET

A really interesting side effect of being able to convert the bitmap to a GIF or JPEG is that we can use that functionality and stream the image from an ASP.NET page. This allows you to dynamically generate barcode images that can be embedded in a Web page. To do this simply create a normal ASP.NET Web Form (.aspx), and enter the code shown in Listing C into the Page_Load event.

Listing C

Stream to Web

With the code above we can access the barcode via a URL -- something like this:

http://yourwebsite/BarcodeGenerator.aspx?data=11111111
43 comments
mariah sharp
mariah sharp

I think this may help you ,C#barcode generator

tanlara
tanlara

i am using streaming bar code. returning image text itself. only " * "(Star) is converted.

eldavan
eldavan

Hola, puedo usar este código para una aplicación movil? que cambios haria? Gracias

recthor
recthor

there are many ways to do that. If you wanna save these complicated steps and find a easy way, you can google barcode generator and you will find many useful tools, or google how to create barcode in c# to get instructive articles. Good luck:) I think some imaging sdk programmes can enable to quickly generate barcodes. i have use imaging sdkr which can original layouts hyperlinks, Images and tables retained in word ,text, image, Epub, html.but i forgot download the wedsite ,go to google. By the way , pay attention to your system platform, select the suitable one . I use a barcode generator driver found on the internet . Install it and it becomes a selectable option.Then you can generate barcodes in many formats in any program at all, including Adobe Acrobat . Just open the sdk, select barcode, and choice a form you want, then you can generate barcode in c#, vb, sdp ,etc ,the task will be finished in several seconds. if you haven't found a good choice , you can have a try. best wishes. http://www.rasteredge.com/how-to/csharp-imaging/barcode-generating/

Susanna Moore
Susanna Moore

Hi, If you need to generate barcode images in Visual C# .NET project, you may use a C# barcode generator dll for .NET to achieve this. This mature tool supports common used linear & 2d barcode types, like Code 39 generation in C# and QR Code generation in C#. Form my experience, you can generate and encode barcode images into several source image files formats, like GIF, JPEG, BMP, PNG or all barcodes are highly compatible with latest barcode standards.

hunter
hunter

Here is how to use the font without installing it [pre] Public Shared Function Draw1DBarcode(ByVal fontFolder As String, ByVal data As String) As Bitmap data = String.Concat("*", data, "*") Dim barCode As New Bitmap(1, 1) Dim barcodeFonts As New System.Drawing.Text.PrivateFontCollection() barcodeFonts.AddFontFile(String.Concat(fontFolder, "\free3of9.ttf")) Dim ff As FontFamily = barcodeFonts.Families(0) Dim barcodeFont As New Font(ff, 30, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point) Dim graphicBarcode As Graphics = Graphics.FromImage(barCode) Dim dataSize As SizeF = graphicBarcode.MeasureString(data, barcodeFont) barCode = New Bitmap(barCode, dataSize.ToSize()) graphicBarcode = Graphics.FromImage(barCode) graphicBarcode.Clear(Color.White) graphicBarcode.TextRenderingHint = TextRenderingHint.SingleBitPerPixel graphicBarcode.DrawString(data, barcodeFont, New SolidBrush(Color.Black), 0, 0) graphicBarcode.Flush() barcodeFont.Dispose() graphicBarcode.Dispose() barcodeFonts.Dispose() Return barCode End Function [/pre]

ali3356
ali3356

Great work . I have tried the IDAutomationHC39M and its work fine. but be sure to installed the .ttf Thank you ,

VladLap
VladLap

to print barcode labels I use reporting services - local report with image control that get barcode from code: MemoryStream stream = new MemoryStream(); barCode.Save(stream, ImageFormat.Gif); byte[] blob = new byte[stream.Length]; blob = stream.ToArray(); return blob; It works fine with font (Code 39) of size 20 and greater but for 10 (even 18) barcode is not readable Using "myEncoderParameter = new EncoderParameter(myEncoder, 75L)" does not help. The same story with IDAutomationHC39H and Free 3 of 9 (does't work at all). What i'm doing wrong?

Barcoder
Barcoder

When I use this code and pass a number from the url i just get that number printed on the screen not the barcode. Also when i try with *12345* then i get the number with astrics.. what am i missing?

jinnah343
jinnah343

How do you input the data in the graphic image at the bottom of the barcode image

Jeanmli
Jeanmli

I can print barcode in my develop PC, but I can't print barcode from server

stalin_0053
stalin_0053

I am getting a full black bar code i am not able to see the bars because the whole barcode generated is black>>

heartbeats_111
heartbeats_111

can you please tell me how can read the data generated by this? that means how can i read this bar code can you please explain?

trebuntou
trebuntou

nice Idea!!! thanks for the knowledge

aikimark
aikimark

I did a search earlier in 2007 for a MICR font. Does anyone have a recommendation for a free or reasonably priced MICR font?

kryan
kryan

will you be doing a simular thing with the code 128 font i can't find a free one anywhere but the program i'm doing requires the more complex code 128 against the code 39 font. Thanks nice tutorial though.

curtis.cook
curtis.cook

The ability to download the code examples would be nice.

dan yang
dan yang

using KeepDynamic.Barcode.Generator; // Create linear barcode object in C# BarCode barcode = new BarCode(); // Set barcode symbology type to Code-128 in C# barcode.SymbologyType = SymbologyType.Code128; // Set barcode value in C# barcode.CodeText = "Code128"; // Set barcode drawing image format to PNG in C# barcode.Format = ImageFormat.Png; // Generate barcode & encode to the png image in C# barcode.drawBarcode("C://barcode-code128-csharp.png"); // Generate barcode & print to System.Drawing.Graphics object in C# barcode.drawBarcode("Graphics object"); // Create barcode & draw to System.IO.Stream object in C# barcode.drawBarcode("Stream object"); I read this article right now. hope it is helpful for you

Kaiser79
Kaiser79

Jeanmli Sorry , im a mexican man, my english is basic, but try to do this, i mean i had the same problem and whit this i fixed. you nedd to add System.IO; And make this changes Response.ContentType = "image/png"; Response.Clear(); Bitmap barCode = CreateBarcode("*" + Session["FileFolder"].ToString() + "*") ; MemoryStream ms = new MemoryStream(); barCode.Save(ms, ImageFormat.Png); ms.WriteTo(Response.OutputStream); check the modification, add ms I hope this help you.. Good luck Kaiser79 Again, sorry for my bad english.

Tony Hopkinson
Tony Hopkinson

With a barcode reader ??? Whichever one you are using will have a resource for how to use it in a program if that's what you mean. Basically though it's just an input device like a keyboard. If you plug one in to your windows pc, run up notepad and then scan something, the code will apear in teh text window, same for an editbox in an application.

AbbydonKrafts
AbbydonKrafts

If you want to render it in memory, you'll have to look into using the Windows API for creating a DC, drawing text on it, etc. It gets pretty complex. If you don't mind using a PictureBox, it's much easier. http://grandzebu.net/index.php Click the "English version of barcodes" link. Each barcode has a sample VB6 application.

Barcoder
Barcoder

When I use this code and pass a number from the url i just get that number printed on the screen not the barcode. Also when i try with *12345* then i get the number with astrics.. what am i missing?

yankeek
yankeek

We print massive amounts of checks using the "TT8731Z_.TTF" font for the micr numbers. Ken

kryan
kryan

Thankyou for the link to such a great font i've just got to alter my program that removed the demo text from the other font i was using.

milind.a.joshi
milind.a.joshi

Hi Eric, This was an excellent resource. Thank you.

aikimark
aikimark

Ken That font is not on my system. What is the source of that font.