Wednesday, August 5, 2009

How To: Generate Barcode in ASP.NET

in this Article I'll Describe How To Generate Barcode Image in ASP.NET Without Using third party.

first thing barcode depending on Fonts and there are many fonts used for barcode
also there are many free fonts you can download it.

I'll Will Use Code 39 Font, You can download it from:
http://www.barcodesinc.com/free-barcode-font/

Copy Font to Windows\Fonts Folder

Steps:

1- Create ASP.NET Web Application.
2- in The Main Web Application Root Create Folder "Images".
3- in The Default Page Create Button "btnBarcode"
4- Copy the Following Code into your page:

public string ProductCode { get; set; }
public string ProductName { get; set; }
public string ProductPrice { get; set; }

Font arial = new Font("Arial", 8, FontStyle.Regular, GraphicsUnit.Point);
public Font Arial
{
get { return arial; }
}

Font threeOfNine = new Font("Free 3 of 9", 15, FontStyle.Regular, GraphicsUnit.Point);
public Font ThreeOfNine
{
get { return threeOfNine; }
}

Bitmap barcodeImage = new Bitmap(85, 55);
public Bitmap BarCodeImage
{
get { return barcodeImage; }
}


private void GenerateBarcode()
{
Graphics graphics = Graphics.FromImage(BarCodeImage);
SizeF dataSize = graphics.MeasureString(ProductCode, ThreeOfNine);

//Refresh our Graphics object with the new bitmap
graphics = Graphics.FromImage(BarCodeImage);

graphics.Clear(Color.White);
graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;

graphics.DrawString(ProductCode, ThreeOfNine, new SolidBrush(Color.Black), 0, 15);
graphics.DrawString(ProductName, Arial, new SolidBrush(Color.Black), 0, 0);
graphics.DrawString(ProductCode, arial, new SolidBrush(Color.Black), 10, 30);
graphics.DrawString("Price " + ProductPrice + " L.E", Arial, new SolidBrush(Color.Black), 0, 40);

//force the Graphics object to execute any pending operations.
graphics.Flush();

//Dispose our objects
threeOfNine.Dispose();
graphics.Dispose();
}


protected void btnBarcode_Click(object sender, EventArgs e)
{
ProductCode = "ABCD-12345";
ProductName = "Congestal";
ProductPrice = "20000";

GenerateBarcode();
BarCodeImage.Save(Server.MapPath("~/Images/barcode.gif"), ImageFormat.Gif);
Response.WriteFile(Server.MapPath("~/Images/barcode.gif"));
}

No comments:

Post a Comment