In this article I will explain how to dynamically generate and display barcode image using ASP.Net
Barcode Font
First you will need to download the Free Barcode Font from the following URL
Once downloaded follow the following steps.
1. Extract the ZIP file.
2. Click and Execute INSTALL.exe file.
3. After installation is completed restart your machine.
Desingner Source Code :
<%@ Page
Language="C#"
AutoEventWireup="true"
CodeFile="BarCodegenerate.aspx.cs"
Inherits="BarCodegenerate"
%>
<!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>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public partial class BarCodegenerate
: System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
}
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);
}
}
}
No comments:
Post a Comment