Monday 21 July 2014

Generate BarCode in ASP.NET

protected void btnGenerateBarCode_onclick(object sender, EventArgs e) 
 {

 string barcodeDetail =”12345”; 
 GenerateBarCode.CreateBarCode(barcodeDetail, "Free 3 of 9 Extended", 48, "D:\Projects\projectname\ImageFolder\" );
 imgBarcodeImage.ImageUrl = string.Format("ImageFolder/{0}.png", barcodeDetail);

 }


public static void CreateBarCode(string barCodedDetail,stringfontName,int fontSize, string physicalPath) 
 {

 //Find the Width for barcode
 int width = barCodedDetail.Length*35; 

 //create Bitmap object with Width and Height
 Bitmap barCode = new Bitmap(width, 120); 

 //path where you want to save the barcode Image
 string filePath = string.Format("{0}{1}.png", physicalPath, barCodedDetail);

 //create the barcoded font object
 Font barCodeFont = new Font(fontName, fontSize, FontStyle.Regular,GraphicsUnit.Point);

 //creating the graphics object for the Bitmap.
  Graphics graphics = Graphics.FromImage(barCode);

 SizeF sizeF = graphics.MeasureString(barCodedDetail, barCodeFont); 

 barCode = new Bitmap(barCode, sizeF.ToSize()); 

 graphics = Graphics.FromImage(barCode);

 SolidBrush brushBlack = new SolidBrush(Color.Black);

graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;

 //putting * before and after the barCodedDetail,
 //this is because scanner only read the data which is started and end with *
 graphics.DrawString("*" + barCodedDetail + "*", barCodeFont, brushBlack, 1,1); 

 graphics.Dispose(); 
 //Saving the Image file
 barCode.Save(filePath, ImageFormat.Png);
  barCode.Dispose();  
 HttpContext.Current.Response.Clear();

 }