In this blog, we will learn how to generate a barcode using asp.net by simply entering numbers and alphabet letters in the textbox and clicking generate. (I have added a downloaded file in zip folder of the project.)
Step 1
Download the barcode font from the link given below:
https://www.idautomation.com/free-barcode-products/code39-font/
Step 2
Extract the zip file and install on your system. After installation, restart your system.
Step 3
Create an empty project in the Visual Studio version of your choice. Give it a meaningful name.
Step 4
Add web form right on the project from solution explorer, add new item, choose web form and give it a name of your choice.
Step 5
Add script and styles cdn link in head section of your web form.
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
Step 6 - Design HTML web form
- <body>
- <form id="form1" runat="server">
- <div class="container">
- <h3 class="text-center text-uppercase">How to create barcode in asp.net</h3>
- <div class="row">
- <div class="form-group">
- <label>Enter Number:</label>
- <div class="input-group">
- <asp:TextBox ID="txtBarcode" CssClass="form-control" runat="server"></asp:TextBox>
- <div class="input-group-append">
- <asp:Button ID="btnGenrate" CssClass="btn btn-outline-primary" runat="server" Text="Genrate" OnClick="btnGenrate_Click" />
- </div>
- </div>
- </div>
- </div>
- <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
- </div>
- </form>
- </body>
Step 7
Double click or enter Button control.
Add namespace
using System.Drawing;
using System.IO;
Write the following code
- protected void btnGenrate_Click(object sender, EventArgs e)
- {
- string barCode = txtBarcode.Text;
- System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
- using (Bitmap bitMap = new Bitmap(barCode.Length * 20, 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);
- }
- PlaceHolder1.Controls.Add(imgBarCode);
- }
- }
Step 8
Run project ctr+F5
Final output
No comments:
Post a Comment