Dynamically Generate and Display Barcode Image in ASP.Net c# - cSharp Coder

Latest

cSharp Coder

Sharp Future

Tuesday, September 1, 2020

Dynamically Generate and Display Barcode Image in ASP.Net c#

 

Downloading and installing Barcode Font
First you will need to download the Free Barcode Font from the following link.
Once downloaded follow the following steps.
1. Extract the Font from the ZIP file.
2. Double Click, Open the File and then click the Install Button as shown below.
3. After installation is completed, restart your machine.

 
HTML Markup
The HTML Markup consists of an ASP.Net TextBox, a Button and an Image control.
The barcode entered in the TextBox will be converted to an Image Barcode and then later displayed in the Image control.
<asp:TextBox ID="txtBarcode" runat="server"></asp:TextBox>
<asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="GenerateBarcode" />
<hr />
<asp:Image ID="imgBarcode" runat="server" Visible="false" />
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
 
Dynamically generating and displaying Barcode Image in ASP.Net
Inside the GenerateBarcode event handler, first a Bitmap Image is created and then using the Free Barcode Font, the Barcode Graphics is drawn on the Bitmap Image.
Then the Bitmap Image saved into MemoryStream object and then it is converted into a BASE64 string and assigned to the Image control.
Finally, the Image control is made visible by setting the Visible property to True.
C#
protected void GenerateBarcode(object sender, EventArgs e)
{
    string barCode = txtBarcode.Text;
    using (Bitmap bitMap = new Bitmap(barCode.Length * 40, 80))
    {
        using (Graphics graphics = Graphics.FromImage(bitMap))
        {
            Font oFont = new Font("IDAutomationHC39M Free Version", 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, ImageFormat.Png);
            imgBarcode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
            imgBarcode.Visible = true;
        }
    }
}
 

No comments:

Post a Comment