Generate barcode using C#.NET

Generate barcode using C#.NET

In this post we are going to know how to generate barcode images using C#.NET native classes. You will not need a third-party tool or external DLL library in order to achieve this. As we all know that barcodes depends on fonts, there are plenty of them used for barcodes.

The most famous font for barcode is “Code 39” and anyone can download it for free. After you download the font and install it to windows fonts, please find below the code that generate barcode images:

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace NB.BlogCode
{
	public class Program
	{

	  static void Main(string[] args)
	  {
            GenerateBarcodes("Product Code", "Product Name", "Product Price");
          }

          public static void GenerateBarcodes(string productCode, string productName, string productPrice)
          {
            Font stringFornt = new Font("Arial", 15, FontStyle.Bold, GraphicsUnit.Point);
            Font barcodeFont = new Font("Free 3 of 9", 40, FontStyle.Regular, GraphicsUnit.Point);
            Bitmap barcodeImage = new Bitmap(140, 110);
            Graphics graph = Graphics.FromImage(barcodeImage);

            graph = Graphics.FromImage(barcodeImage);
            graph.Clear(Color.White);
            graph.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
            graph.DrawString(productName, stringFornt, new SolidBrush(Color.Black), 10, 0);
            graph.DrawString(productCode, barcodeFont, new SolidBrush(Color.Black), 0, 30);
            graph.DrawString(productCode, stringFornt, new SolidBrush(Color.Black), 10, 70);
            graph.DrawString(productPrice, stringFornt, new SolidBrush(Color.Black), 10, 90);
            graph.Flush();

            barcodeImage.Save(@"D:\barcode.jpg", ImageFormat.Jpeg);

            barcodeImage.Dispose();
            graph.Dispose();
            barcodeFont.Dispose();
          }
    }
}

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *