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

C# Barcode Generator WebService

By , 31 Mar 2003
 

Sample Image - barcodegen.jpg

Introduction

Some days ago, I was asked to find a solution to create a barcode to be printed on documents produced by a web application. After trying to find some components that produced barcodes, I soon realized that their price was very high when dealing with an unlimited number of clients licences. I needed an alphanumeric barcode representation and the preferred barcode representation was Code39.

In order to expose this service to the maximum of clients while delivering a standardized solution, I thought of writing a web service that would generate the barcode dynamically and return it streamlined as an image.

This article describes the solution that I’ve implemented.

The Barcode Generation

Instead of writing a code39 barcode generator that mimics the algorithm for that barcode representation, my idea was to use one of the freely available barcode fonts to produce the barcode (http://www.squaregear.net/fonts/free3of9.shtml).

So my approach was simple:

  1. Load the Barcode Font
  2. Create an image object
  3. Draw a string into that image using a code39 barcode font
  4. Return that image serialized.

Using the Code39 Font...

The way to use a font in windows is simple, all you have to do is install it (by copying it to the c:\WINDOWS\Fonts - under XP) and just use it.

Unfortunately, the ASP.NET graphic context does not allow you to use any font  (free3of9.ttf for example) because .NET GDI only uses/enumerates OpenType fonts. So what you have to do is create a temporary font object.

This method is very straighforward, as you can see in the code sample below:

// Create a private font collection
objectPrivateFontCollection pfc=new PrivateFontCollection();

// Load in the temporary barcode font
pfc.AddFontFile("c:\\barcodefont\\free3of9.ttf");

// Select the font family to use
FontFamily family=new FontFamily("Free 3 of 9",pfc);

// Create the font object with size 30
Font c39Font=new Font(family,30);

With this easy way, you get a font object mapped to the barcode font so that you can create the barcode.

Creating the Barcode Image Container

The image creation is very simple. .NET classes allow you to generate images on the fly. So, in order to create a image large enough to accommodate the barcode, first you need to determine the size that will be occupied by the code string drawing, using the barcode font.

You can do it using the MeasureString method:

// Create a temporary bitmap...
Bitmap tmpBitmap = new Bitmap(1,1,PixelFormat.Format32bppArgb);
objGraphics = Graphics.FromImage(tmpBitmap);
// measure the barcode size...
SizeF barCodeSize=objGraphics.MeasureString(barCodeString,c39Font);

The returned type barCodeSize has the width, and the height that will be occupied by the code string drawing.

Draw the Barcode

So now we need to draw the barcode. We will use the code39 barcode font object instantiated earlier.

Assuming the the barcode variable holds the barcode string, the required code is:

// Draw the barcode
objGraphics.DrawString(barCode, Code39Font, new solidBrush(Color.Black),0,0);

Please note that usualy the code39 barcodes are represented concatenating  the char (*) at the beginning and end of the barcode string…meaning that code 123456 has to be written as *123456*. But I will leave that to your experience.

Serialize/Deserialize the Image

In order to return the image from the web service method, you now have to serialize the image, meaning that your web method has to return an array of bytes.

This way, you have to create a stream from the bitmap image, and return it as an array of bytes. Once again, the .NET framework makes it easy for us do perform that task:

// Create stream....
MemoryStream ms = new MemoryStream();

// save the image to the stream
objBitmap.Save(ms ,ImageFormat.Png);

//return an array of bytes....
return ms.GetBuffer();

On the other end (the client side) when you are consuming the web service, you need to be able to deserialize the array of bytes back to the image:

Byte[] imgBarcode;

// Call the webservice to create the barcode...

// Create a stream....
MemoryStream memStream = new MemoryStream(imgBarcode);

// Recreate the image from the stream<BR>Bitmap bmp=new Bitmap(memStream);

A final note about the sample code attached…

After creating the barcode web app that will be your webservice, you need to configure the web.config file in order to specify where your barcode font is located. Search for the following section and make your changes accordingly.

<appSettings>
   <add key="BarCodeFontFile" value="c:\temp\font\FREE3OF9.TTF" />
   <add key="BarCodeFontFamily" value="Free 3 of 9" />        
</appSettings>

And that’s all folks. Hope you’ve enjoyed it.

Best regards,
Rui Miguel Barbosa

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Rui Miguel Barbosa
Web Developer
Portugal Portugal
Member
No Biography provided

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 in .netmemberBarcoding House20 Jan '13 - 17:17 
QuestionqrcodememberMember 917112825 Nov '12 - 21:35 
AnswerRe: qrcodememberTarcode Michael23 Dec '12 - 15:48 
AnswerUseful informationmembersybil_25 Sep '12 - 17:30 
QuestionUnable to scan barcode which was generated by using 28 digit stringmemberKiranRViradiya25 Apr '12 - 23:52 
AnswerRe: Unable to scan barcode which was generated by using 28 digit stringmembersybil_25 Sep '12 - 17:32 
AnswerRe: Unable to scan barcode which was generated by using 28 digit stringmemberAspper White26 Nov '12 - 17:06 
AnswerRe: Unable to scan barcode which was generated by using 28 digit stringmemberSusanna Moore4 Jan '13 - 16:19 
Questiongenerate qr codememberjames99115 Mar '12 - 23:17 
GeneralGreat articlememberJason from Florida25 Jan '12 - 1:12 
Questionbarcode creator for C#memberKeepDynamic9 Jan '12 - 3:57 
Questionabout the QR barcode generator [modified]memberblueicy19 Dec '11 - 19:47 
AnswerRe: about the QR barcode generatormembersteve7g10 Jan '12 - 16:26 
AnswerRe: about the QR barcode generatormemberblueskysinger20 Feb '12 - 16:06 
GeneralMy vote of 5memberTeddy Segoro1 Dec '11 - 19:53 
Questionhow use this generator in asp.net web applicathionmembersaidfathi5 Nov '11 - 2:43 
AnswerRe: how use this generator in asp.net web applicathionmemberblueicy10 Jan '12 - 17:10 
AnswerRe: how use this generator in asp.net web applicathionmemberblueskysinger20 Feb '12 - 16:15 
Questionhow can i read and write barcode through vb.net 2005memberJalesh Singh25 Aug '11 - 20:23 
AnswerRe: how can i read and write barcode through vb.net 2005memberIvy Shirley24 Nov '11 - 19:55 
AnswerRe: how can i read and write barcode through vb.net 2005memberZacbr8 Jan '12 - 3:28 
Questionhow to read this generated bar codememberdprapireddy30 Jun '11 - 1:55 
AnswerRe: how to read this generated bar codememberblueicy28 Dec '11 - 17:11 
GeneralWorking for mememberamit k saini3 Jun '11 - 1:37 
GeneralMy vote of 5memberjohannesnestler3 Nov '10 - 5:10 
GeneralBarcode 2 of 5membernilo@computerisation.co.uk1 Sep '10 - 4:19 
QuestionString(Alphabatical) value unable to convert to the barcode formatmemberRajiredy17 May '10 - 22:54 
GeneralDude you rock :)memberRaphael Shekwolo8 Apr '10 - 1:39 
GeneralWant ot read barcode image form Tiff FilememberMember 412614918 Sep '09 - 19:30 
GeneralScanner couldn't scan the printed barcodes.., (scanner says it supports code39)membersaurabhnijhawan198716 Jun '09 - 20:25 
Generalgetting an error while runningmemberkutti krishnan kodoth12 Jun '09 - 19:06 
GeneralScanner Couldn't readmembermurtaza dhari9 Feb '09 - 23:52 
GeneralRe: Scanner Couldn't readmembermurtaza dhari10 Feb '09 - 0:42 
GeneralExtended (ASCII) character supportmemberMark Rodrigues25 Oct '08 - 13:10 
QuestionRead Bar CodememberSaurabh Sondhi7 Oct '08 - 9:04 
GeneralLicensemembervictor.sauermann26 Sep '08 - 22:09 
AnswerRe: LicensememberMark Rodrigues25 Oct '08 - 12:47 
GeneralWill it work for Other Barcode (code 128 A, 128 B, PDF417 etc)memberNETA200325 Apr '07 - 12:05 
GeneralNice workmemberAlexandr_K27 Sep '06 - 8:52 
News.GetBuffer() is badmemberSteve Hansen19 Mar '06 - 9:43 
GeneralRe: .GetBuffer() is badmemberdonperry21 May '08 - 3:35 
GeneralAntialiasing..memberhaphaphaphap1 Nov '05 - 4:24 
GeneralRe: Antialiasing..memberDuddy16 Dec '05 - 5:19 
GeneralRe: Antialiasing..memberdapoussin22 May '06 - 3:21 
GeneralRe: Antialiasing..memberLeonelCorso9 Oct '07 - 8:19 
GeneralIDAutomation Barcode Generator Webservicesussidautomation15 Oct '05 - 5:24 
GeneralIt generates different kind of imagesussAnonymous18 Aug '05 - 20:17 
GeneralBarcode is incorrectmembertyc1008 Oct '04 - 9:48 
Generalabout client sidemembercodehobbist20058 Jun '04 - 20:15 
QuestionProduced Image cannot be scanned??memberkthuya23 May '04 - 22:44 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 1 Apr 2003
Article Copyright 2003 by Rui Miguel Barbosa
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid