Pages

Saturday 4 August 2012

How to Generate a Barcode in Asp.Net?(Example-1)

         First, download "IDAutomationHC39M" Font from internet and install it in your system. For installation,simply copy the Font you have downloaded, then go to "Control Panel -> Fonts" and paste the font there. Then you have to restart your System to make the new font work properly.
         After that, create a page having a TextBox,a Button and a PlaceHolder inside it.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Barcode2.aspx.cs" Inherits="Webpages_Barcode2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
    <asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="btnGenerate_Click" />
    <hr />
    <asp:PlaceHolder ID="plBarCode" runat="server" />
    </form>
</body>
</html>

Add System.Drawing and System.IO namespaces to your page. Then write these lines in the button's click Event.
protected void btnGenerate_Click(object sender, EventArgs e)
    {
        string barCode = txtCode.Text;
        System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
        using (Bitmap bitMap = new Bitmap(barCode.Length * 21, 80))
        {
            using (Graphics graphics = Graphics.FromImage(bitMap))
            {
                Font oFont = new Font("IDAutomationHC39M", 15);
                PointF point = new PointF(2f, 2f);
                SolidBrush blackBrush = new SolidBrush(Color.Black);
                SolidBrush whiteBrush = new SolidBrush(Color.White);
                graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
                graphics.DrawString(barCode, oFont, blackBrush, point);
            }
            using (MemoryStream ms = new MemoryStream())
            {
                bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] byteImage = ms.ToArray();                
                Convert.ToBase64String(byteImage);
                imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
            }
            plBarCode.Controls.Add(imgBarCode);
        }
    }


We are done with the coding and ready to test the page. Now, you can debug the page and enter the value whose barcode is to be generated in the textbox. After clicking the "Generate" Button, the Barcode will be generated.
Final Output:



Regards,
Prajanuranjan....



No comments:

Post a Comment

Total Pageviews