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

 
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 
So many barcode generator info, nowadays, barcode plays a very important role, we can see and use it in every time. before long,I've tested one free online generator, it is interesting that when I go shopping, I use such mobile software to scan the commodity. have a try.barcode generator in.net
QuestionqrcodememberMember 917112825 Nov '12 - 21:35 
I have one requirement generate QR COde like this
<html>
<head runat="server">
</head>
<body>
<asp:RadioButton ID="RadioButton1" runat="server" ForeColor="#006600" GroupName="coupon" Text="QR Code" />
                                <br />
                                <asp:RadioButton ID="RadioButton2" runat="server" ForeColor="#006600" GroupName="coupon" Text="Bar Code" />
                                <br />
                                <asp:RadioButton ID="RadioButton3" runat="server" ForeColor="#006600" GroupName="coupon" Text="Coupon Code" />
 
<asp:DropDownList ID="DropDownList1" runat="server" Height="24px" style="color: #0000FF; background-color: #66CCFF" Width="147px">
                                    <asp:ListItem>Select type of value</asp:ListItem>
                                    <asp:ListItem>$</asp:ListItem>
                                    <asp:ListItem>%</asp:ListItem>
                                </asp:DropDownList>
 
 <asp:TextBox ID="TextBox1" runat="server" Height="24px" style="color: #0000FF" >               </asp:TextBox>
 
                                <asp:Button ID="Button1" runat="server" BackColor="#FF99CC" BorderStyle="Double" ForeColor="#003300" Height="31px" Text="Generate" OnClick="Button1_Click" />
 
<asp:Image ID="Image2" runat="server" Height="96px" Width="126px" />
 
</body>
</html>
 
3 Radio butons,1 DropDown list,1textBox,1 Image
 
I want to select perticular (ex:Bar,QR codeetc),Select Type of One dropdown list value,Enter Value in textBox AND I want to click on the Genarate button Generate QR code(OR)Bar code image display in the button below Image control
After scan that Image display total values what i am selecting in the above,
Plz help me

AnswerRe: qrcodememberTarcode Michael23 Dec '12 - 15:48 
Great barcode tutorial for C#.NET. Smile | :)

AnswerUseful informationmembersybil_25 Sep '12 - 17:30 
Quit useful now in 2012 even it is posted several years ago. Thanks. Blush | :O
barcode for Windows Forms, ASP.NET, Word, Excel, Crystal Reports, RDLC, ssrs@Aspper

QuestionUnable to scan barcode which was generated by using 28 digit stringmemberKiranRViradiya25 Apr '12 - 23:52 
Hi,
I have generated barcode with code size 28 digit.
My final code = '*' + 28 digit + '*'.
Barcode is generated but after printing that barcode when I tried to scan that barcode, barcode scanner unable to scan that.
 
I have used different bar size such as 30, 45, 60 but no luck.
 
Please help...
 
Thanks
Kiran Viradiya

AnswerRe: Unable to scan barcode which was generated by using 28 digit stringmembersybil_25 Sep '12 - 17:32 
Hey, remove that '*' characters at the left and right end of code 128, it is only for code 39 barcode symbology.
barcode for Windows Forms, ASP.NET, Word, Excel, Crystal Reports, RDLC, ssrs@Aspper

AnswerRe: Unable to scan barcode which was generated by using 28 digit stringmemberAspper White26 Nov '12 - 17:06 
The form '*' + 28 digit + '*' really like the barcode code 39. The code 39 barcodes has the start and stop character at the beginning and end part of the Code 39. So you may change the barcode type to Code 39 and have a try. Or you could try to remove the '*' then scan again.

AnswerRe: Unable to scan barcode which was generated by using 28 digit stringmemberSusanna Moore4 Jan '13 - 16:19 
Hi,
 
Based on my exprience, this might be quiet zone issue. In ISO/IEC specification, a specific barcode quiet zone must be greater than a value. For example, for almost linear barcodes, like Code 128, the quiet zone should be at least 10 times of the bar width (narrowest value). Besides, barcode reader tool should be also designed according to the latest barcode specifications.
 
Hope this info can help.
Questiongenerate qr codememberjames99115 Mar '12 - 23:17 
this is a qr code generation DLL for .net project. qr code printing functions can be added by integrating it into .NET framework apps
GeneralGreat articlememberJason from Florida25 Jan '12 - 1:12 
Great article! I was able to use this to create a barcode for our packing slips.
The barcode prints out nicely. We just need to buy a scanner so we can start scanning! Thank you for your help.
Questionbarcode creator for C#memberKeepDynamic9 Jan '12 - 3:57 
this is a barcode generator written in C#.NET and supports .net 2.0 and greater.
Questionabout the QR barcode generator [modified]memberblueicy19 Dec '11 - 19:47 
Yeah, the barcode generator is very useful to our daily life and I have just bought one QR Barcode for my phone, and it works well. So, if you are interested in it ,you may have a try.
Free Online Code Reader

modified 28 Dec '11 - 23:07.

AnswerRe: about the QR barcode generatormembersteve7g10 Jan '12 - 16:26 
It is really very easy to generate
"<a href="http://www.keepautomation.com/products/net_barcode/">barcode</a>", you may try yourself. Size and color could be changed, funny
Laugh | :laugh:
http://www.keepautomation.com

AnswerRe: about the QR barcode generatormemberblueskysinger20 Feb '12 - 16:06 
Hey,since you're talking about      C# Barcode Generator here, I might as well give some suggestions. Here's      C# Barcode Generator I've been using, very convenient, and supports 20+ major barcode types~de Reader<a href="http://www.keepautomation.com/guide/csharp_barcode_generator.html">http://www.keepautomation.com/guide/csharp_barcode_generator.html</a>[<a href="http://www.keepautomation.com/guide/csharp_barcode_generator.html" target="_blank" title="New Window">^</a>]
GeneralMy vote of 5memberTeddy Segoro1 Dec '11 - 19:53 
excellente
Questionhow use this generator in asp.net web applicathionmembersaidfathi5 Nov '11 - 2:43 
i need to use this generator in web application
i have problem in this code
 
MemoryStream memStream = new MemoryStream(imgBarcode);
 
BarcodeImg.ImageUrl = new Bitmap(memStream);
AnswerRe: how use this generator in asp.net web applicathionmemberblueicy10 Jan '12 - 17:10 
Sorry ,can't open that site.I suggest you to do some programming to make a barcode scanner by yoursel. Or else,you may download a free barcode scanner first to have a try.There are so many companies sell barcode scanners nowadays. Maybe, you can buy one online. I have brought one from KEEPAUTOMATION Free Online Code Reader and it works well. This company can also provide you with some free online barcode generator, you may have a try someday.
AnswerRe: how use this generator in asp.net web applicathionmemberblueskysinger20 Feb '12 - 16:15 
Hey,since you're talking about Vb .NET barcode scanner here, I might as well give some suggestions. Here's Vb .NET barcode scanner I've been using, very convenient, and supports 20+ major barcode types~de Reader<a href="http://www.keepautomation.com/guide/vbnet_barcode_generator.html">http://www.keepautomation.com/guide/vbnet_barcode_generator.html</a>
Questionhow can i read and write barcode through vb.net 2005memberJalesh Singh25 Aug '11 - 20:23 

how can i read and write barcode through vb.net 2005

AnswerRe: how can i read and write barcode through vb.net 2005memberIvy Shirley24 Nov '11 - 19:55 
Hey dear~Here's some sample code for you~
 
[^]
 
C#.NET Barcode Generator Quick Start
1. How to install .NET Barcode Generator Control to your Visual C# project?
Add OnBarcode.Barcode.WinForms.dll or OnBarcode.Barcode.ASPNET.dll to C# project reference
 
2. How to create linear barcodes in C# class?
 
Linear barcode = new Linear(); // Create linear barcode object
barcode.Type = BarcodeType.CODE39; // Set barcode symbology type to Code-39
barcode.Data = "0123456789"; // Set barcode data to encode
barcode.X = 1; // Set barcode bar width (X dimension) in pixel
barcode.Y = 60; // Set barcode bar height (Y dimension) in pixel
barcode.drawBarcode("csharp-code39.png"); // Draw & print generated barcode to png image file
AnswerRe: how can i read and write barcode through vb.net 2005memberZacbr8 Jan '12 - 3:28 
here is a vb.net barcode which tells the way of reading and writing 1D and 2D barcodes through vb.net 2005.
Questionhow to read this generated bar codememberdprapireddy30 Jun '11 - 1:55 
Hi I am able to generate this barcode successfully, however how can I read this barcode, could you please post that article also.
 
Thanks,
Durga
AnswerRe: how to read this generated bar codememberblueicy28 Dec '11 - 17:11 
I don't have experience on reading barcodes, maybe you should buy one component and do some programming to make a barcode scanner by yourself.There are so many companies sell barcode scanners nowadays.Maybe,you can buy one online. I have brought one from and it works well. KEEPAUTOMATION Free Online Code ReaderThis company can also provide you with some free online barcode generators, you may have a try someday.
GeneralWorking for mememberamit k saini3 Jun '11 - 1:37 
Thanks
GeneralMy vote of 5memberjohannesnestler3 Nov '10 - 5:10 
great article - helped me a lot - thx.
GeneralBarcode 2 of 5membernilo@computerisation.co.uk1 Sep '10 - 4:19 
I been searching for codes that computes the Code-25 or Barcode 2 of 5 symbology. Can anybody help me?
QuestionString(Alphabatical) value unable to convert to the barcode formatmemberRajiredy17 May '10 - 22:54 
Hi,
Your code is working fine ,if we use the numeric value as input string, but if I use the string then it shows as it is in pixcuture box
GeneralDude you rock :)memberRaphael Shekwolo8 Apr '10 - 1:39 
The code is clean. I like it. Keep em coming buddy. Big Grin | :-D
challenge is the canvas to paint the solution
modified on Thursday, April 8, 2010 8:01 AM

GeneralWant ot read barcode image form Tiff FilememberMember 412614918 Sep '09 - 19:30 
Hi Rui Miguel Barbosa
 
How to read barcode from a tiff file .
 

Thanks
GeneralScanner couldn't scan the printed barcodes.., (scanner says it supports code39)membersaurabhnijhawan198716 Jun '09 - 20:25 
The barcodes are generated perfectly fine , but my scanner is not able to read the printed copy.
I checked reading a bookman code usign another software , the scanner was able to read it.
What may be the problem , any suggestions?
Generalgetting an error while runningmemberkutti krishnan kodoth12 Jun '09 - 19:06 
The request failed with HTTP status 404: Not Found.
 
"we are not human beings having spritual exprience but spritualbeings having human experience"

GeneralScanner Couldn't readmembermurtaza dhari9 Feb '09 - 23:52 
Hi my scanner couldn't read barcode generated by this software y this is happening any suggestion ?
 
If all the tree become pen and all ocean become ink and many more other ocean become ink even then the ALLAH praise could not be written completely. (AL-Quran)

GeneralRe: Scanner Couldn't readmembermurtaza dhari10 Feb '09 - 0:42 
Its done by reading below post.
 
Solutin : * added on both ends.
 
If all the tree become pen and all ocean become ink and many more other ocean become ink even then the ALLAH praise could not be written completely. (AL-Quran)

GeneralExtended (ASCII) character supportmemberMark Rodrigues25 Oct '08 - 13:10 
Wow, 5 years on and this article is still making people (like me) happy Big Grin | :-D
 
As an additional note, on the font authors website (http://www.squaregear.net/fonts/free3of9.shtml[^]) there is an extended font which will handle ascii characters in the barcode.
 
I am sure most of you can work this out but to save you 2 minutes you need to:
- Download the font file from the site above
- Change the reference to the new font file
- The font name is "Free 3 of 9 Extended"
 
Thanks again to the author for this great article.
QuestionRead Bar CodememberSaurabh Sondhi7 Oct '08 - 9:04 
Hello Dear
 
I am succesfully able to create bar code using your web service, it really works awesome...
 
I also want to read the bar code images so as to know the actual data...
 
Do you provide a webservice for the same as well ?
 
Thanks in advance ...
 
Regards
Saurabh Sondhi
GeneralLicensemembervictor.sauermann26 Sep '08 - 22:09 
Hi!
 
I'm interested in license details of your posted Free3of9.ttf font.
Can you please give me more details in using your font?
 
Cheers
Vic
AnswerRe: LicensememberMark Rodrigues25 Oct '08 - 12:47 
The author of the font has made the font freely available as detailed at http://www.squaregear.net/fonts/free3of9.shtml [^]
GeneralWill it work for Other Barcode (code 128 A, 128 B, PDF417 etc)memberNETA200325 Apr '07 - 12:05 
Assuming i am having fonts for other Barcodes code 128 A, 128 B, PDF417 will this solution work by changing Font name in web.config file.
 
Please help me in above case.
 
Really good work !!
 

GeneralNice workmemberAlexandr_K27 Sep '06 - 8:52 
It's a pretty clear example of how to use web services inside regular Windows applications.
Oh, and the gdi+ trick is cool. There are many related samples, but still...
Thanks! Good job!
Alex.

News.GetBuffer() is badmemberSteve Hansen19 Mar '06 - 9:43 
You should use ToArray() instead, GetBuffer() will return the complete byte[] array and that one can be bigger then the size of the image. So in worst case you could be sending lots of extra unneeded zero bytes.
 
In other words, GetBuffer() returns an array of size Capacity and ToArray() returns an array of size Length.
 
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOMemoryStreamClassToArrayTopic.asp[^]
GeneralRe: .GetBuffer() is badmemberdonperry21 May '08 - 3:35 
good observation, and i agree. It was nice work though
GeneralAntialiasing..memberhaphaphaphap1 Nov '05 - 4:24 
Hi,
 
Nice work! Smile | :)
 
..however I had to add some lines to avoid antialias, which would obfuscate the barcode.. Perhaps some of you have the same issue - anyways - it can be solved easily by adding:
 
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
objGraphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
 

 

 
/E
GeneralRe: Antialiasing..memberDuddy16 Dec '05 - 5:19 
Thank you very much!Smile | :)
GeneralRe: Antialiasing..memberdapoussin22 May '06 - 3:21 
Indeed, I had the same problem. Thanks a lot for this nice hack Smile | :)
GeneralRe: Antialiasing..memberLeonelCorso9 Oct '07 - 8:19 
Thanks a lot for this hack! Big Grin | :-D
GeneralIDAutomation Barcode Generator Webservicesussidautomation15 Oct '05 - 5:24 
We about to release the IDAutomation Barcode Generator Webservice. You may find this better to use then this font implementation. For more info:
 
Visit:
http://www.idautomation.com/webservice/[^]
 
For the description or to use the online demo visit:
http://www.idautomation.com/IDAutomationLinearWebService/IDAutomationLinearWebservice.asmx[^]
 
Best Regards,

IDAutomation.com, Inc.
[Your Source for Quality Symbology]
http://www.IDAutomation.com/
Member Better Business Bureau

GeneralIt generates different kind of imagesussAnonymous18 Aug '05 - 20:17 
Is the barcode generated by this application depends upon the operating system of the machine from where its getting generated.
Please help
GeneralBarcode is incorrectmembertyc1008 Oct '04 - 9:48 
I have checked the barcode generated by this app with other barcode software, and found that barcode generated by this app might be incorrect.
Any ideas?
 

Generalabout client sidemembercodehobbist20058 Jun '04 - 20:15 
Hi there...
When I run the WSBarCode, it wors well and return the Base64Binary document.
However, it returns no Barcode image showing when I run the Barcodeclient.
The error message is as below:
 
_____________________________________________________________________
'System.Net.WebException' system.web.services.dll
 
Other information: request failed,HTTP status 401 : Unauthorized。
_____________________________________________________________________
 
Please help me about this problem, thanks!Smile | :)
QuestionProduced Image cannot be scanned??memberkthuya23 May '04 - 22:44 
Hi there,
 
I cannot scan the image produced by the web service after printing it out. the image produced was blurred.
 
Any help??
 
Thanks!

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 1 Apr 2003
Article Copyright 2003 by Rui Miguel Barbosa
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid