Random Posts

Thursday, 31 May 2018

Dynamically Generate BarCode and Display Image in ASP.net

Step 1:
First of all you have to download BarCode Font and Install it.After Installing you have to restart the system.

Step2:
Create one webform and write the following code in .aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BarCodeGenerate.aspx.cs" Inherits="BarCodeGenerate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <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" />
    </div>
    </form>
</body>
</html>
Step3:
Import 3 name space as following:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

Step 4:
Write the following code in button 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 * 40, 80))
        {
            using (Graphics graphics = Graphics.FromImage(bitMap))
            {
                Font oFont = new Font("IDAutomationHC39M", 16);
                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);
        }
}

Step 5:
After write the following code run the page and enter some number in the textbox and see the out put as following:



0 comments:

Post a Comment