How to Print Barcode in ASP.NET in C#

In this article, we will learn to print barcode images in ASP.NET web applications using C#. We will use the MVC Framework for this example, although you can use ASPX web forms, Windows Forms, or a web API as per your needs.

A basic knowledge of the ASP.NET MVC framework will give you a better understanding of this article.

The flow of this article will be as follows:

  1. Create an MVC project
  2. Install the barcode library
  3. Generate a barcode
  4. Display a barcode image

Create an MVC Project

Open Microsoft Visual Studio. Click on Create New Project > Select ASP.NET web application from templates > Press Next > Name your Project. Press Next > Select MVC. Click the Create Button. The project will be created as shown below.

Add Model

Right-click on the Models folder > Add > Class.

A new window will appear. Name your class as BarcodeModel.

Write the following code in the model class.

public class BarcodeModel
{
    [Display(Name ="Barcode File Name")]
    public string fileName { get; set; }

    [Display(Name = "Barcode Content")]
    public string barcodeContent { get; set; }
}
public class BarcodeModel
{
    [Display(Name ="Barcode File Name")]
    public string fileName { get; set; }

    [Display(Name = "Barcode Content")]
    public string barcodeContent { get; set; }
}
Public Class BarcodeModel
	<Display(Name :="Barcode File Name")>
	Public Property fileName() As String

	<Display(Name := "Barcode Content")>
	Public Property barcodeContent() As String
End Class
VB   C#

The fileName will be used to get the barcode image name from the user. The barcodeContent is used to take the content for the barcode.

Add Controller

Next, we will add a controller which will communicate with our views and model. The code for generating barcodes consists of just two or three lines. Therefore, I will not create any separate class library for this, rather I will write it inside the controller. To add the controller, right-click on the controller folder > Add > Controller. A new window will appear. Select MVC 5 Controller Empty. Click the Add button. A new box will appear.

Write your controller name. But, don't remove the controller from the name. I have given the name "BarcodeController". Click the Add button. A new controller will be generated.

Next, we need to install the barcode library.

Install the Barcode Library

We need a third-party library to generate barcodes. I personally like the IronBarcode library which is free for development and provides multiple features to customize our barcodes, such as adding a logo to our barcode image, adding value below or above the barcode, adding annotations below or above the barcode, resizing the barcode, saving the barcode in multiple image formats, etc. For more details, please click here.

Go to the Package Manager Console. Type the following command and press Enter.

Install-Package barcode

This command will install the IronBarcode library in our project.

Generate the Barcode

Next, add the following sample code to the controller.

[HttpPost]
public ActionResult CreateBarcode(BarcodeModel model)
{
    try
    {
        var MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.barcodeContent, BarcodeEncoding.Code128);
        string path = Server.MapPath("~/Files/");
        string filepath = Path.Combine(path,model.fileName);
        MyBarCode.AddBarcodeValueTextAboveBarcode();
        MyBarCode.SaveAsJpeg(filepath);
        string image = Directory.GetFiles(path).FirstOrDefault();
        ViewBag.fileName = image;
        return View();
    }
    catch
    {
        return View();
    }
}
[HttpPost]
public ActionResult CreateBarcode(BarcodeModel model)
{
    try
    {
        var MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.barcodeContent, BarcodeEncoding.Code128);
        string path = Server.MapPath("~/Files/");
        string filepath = Path.Combine(path,model.fileName);
        MyBarCode.AddBarcodeValueTextAboveBarcode();
        MyBarCode.SaveAsJpeg(filepath);
        string image = Directory.GetFiles(path).FirstOrDefault();
        ViewBag.fileName = image;
        return View();
    }
    catch
    {
        return View();
    }
}
<HttpPost>
Public Function CreateBarcode(ByVal model As BarcodeModel) As ActionResult
	Try
		Dim MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.barcodeContent, BarcodeEncoding.Code128)
		Dim path As String = Server.MapPath("~/Files/")
		Dim filepath As String = System.IO.Path.Combine(path,model.fileName)
		MyBarCode.AddBarcodeValueTextAboveBarcode()
		MyBarCode.SaveAsJpeg(filepath)
		Dim image As String = Directory.GetFiles(path).FirstOrDefault()
		ViewBag.fileName = image
		Return View()
	Catch
		Return View()
	End Try
End Function
VB   C#

Try-catch is used to catch any runtime exception.

The Create Barcode function provided by the barcode-writer class takes two compulsory arguments. The first argument is the content that we wish to encode, and the second argument is about the encoding scheme we wish to use for generating barcodes. Furthermore, it also accepts 11 other optional arguments that include maximum height, maximum width, and so on.

The Server.MapPath() function is used to map the path where we want to save the generated barcode images. The Path.Combine() Method will combine the path and barcode image name.

The AddBarcodeValueAboveBarcode() function will add the barcode value. IronBarcode provides other barcode settings such as max-height, max-width, barcode color, and so on. You can explore and make use of the various parameters.

The SaveASJpeg() function takes the path as an argument and saves the generated barcodes in that particular path.

The Directory.GetFile() method will get the newly generated barcode image.

ViewBag.fileName is used to send the path of our barcode image to the view for displaying our generated barcode image.

We can also generate QR codes in the same way. We just need to change the encoding scheme from Code128 to QR Code.

Add View

We have to add the view for creating the client side of our ASP.NET web application. Right-click on the name of the controller method. Click the Add View button.

A new window will appear. Select MVC 5 View, and click the Add button.

A new prompt will appear as shown below.

Name your View and click the Add button. A new cshtml file will be created.

Add the following code inside your newly generated view.

@model GenerateBarcodeMVC.Models.BarcodeModel

@{
ViewBag.displayBarcode = false;
}

<h2>Create</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>GenerateBarcode</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.fileName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.fileName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.fileName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.barcodeContent, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.barcodeContent, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.barcodeContent, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <img src="~/Files/@Path.GetFileName(ViewBag.fileName)" alt="Barcode"  />
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
@model GenerateBarcodeMVC.Models.BarcodeModel

@{
ViewBag.displayBarcode = false;
}

<h2>Create</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>GenerateBarcode</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.fileName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.fileName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.fileName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.barcodeContent, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.barcodeContent, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.barcodeContent, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <img src="~/Files/@Path.GetFileName(ViewBag.fileName)" alt="Barcode"  />
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
model ReadOnly Property () As GenerateBarcodeMVC.Models.BarcodeModel
ViewBag.displayBarcode = False
End Property

'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Create</h2> [using](Html.BeginForm())
If True Then
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
Html.AntiForgeryToken() <div class="form-horizontal"> (Of h4) GenerateBarcode</h4> <hr /> Html.ValidationSummary(True, "", New With {Key .class = "text-danger"}) <div class="form-group"> Html.LabelFor(Function(model) model.fileName, htmlAttributes:= New With {Key .class = "control-label col-md-2"}) <div class="col-md-10"> Html.EditorFor(Function(model) model.fileName, New With {
	Key .htmlAttributes = New With {Key .class = "form-control"}
}) Html.ValidationMessageFor(Function(model) model.fileName, "", New With {Key .class = "text-danger"}) </div> </div> <div class="form-group"> Html.LabelFor(Function(model) model.barcodeContent, htmlAttributes:= New With {Key .class = "control-label col-md-2"}) <div class="col-md-10"> Html.EditorFor(Function(model) model.barcodeContent, New With {
	Key .htmlAttributes = New With {Key .class = "form-control"}
}) Html.ValidationMessageFor(Function(model) model.barcodeContent, "", New With {Key .class = "text-danger"}) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <img src="~/Files/@Path.GetFileName(ViewBag.fileName)" alt="Barcode" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div>
End If
Dim Scripts As section
If True Then
Scripts.Render("~/bundles/jqueryval")
End If
VB   C#

Next, right-click inside the view, and click the Run to Browser Button.

Output

Input your barcode image name, and barcode content as shown below:

Click the Create button. The barcode image will be generated and displayed on the screen as shown below.

Summary

In this tutorial, we have learned to generate barcodes using the ASP.NET in C#. We have used the MVC Framework for our web application. Microsoft Visual Studio is used as the IDE. IronPDF is used as a third-party library that is free for development and compatible with all versions of the Dot Net framework, including the newly released Dot Net 6 version. IronBarcode is fast and provides multiple features to work with barcodes. We can also generate QR codes using IronBarcode.

There are other many useful libraries such as IronPDF for working with PDF documents, IronXL for working with Excel documents, and IronOCR for working with OCR. Currently, you can get all five libraries for the price of just two by purchasing the complete Iron Suite. For more details, please click here.

I hope you have enjoyed the article. If you have any other queries, please feel free to add them in the comments section.