Saltar al pie de página
USO DE IRONBARCODE
Cómo imprimir un código de barras en ASP.NET

Cómo Imprimir un Código de Barras en ASP.NET en C#

This article will demonstrate how to print barcode images in ASP.NET Web Applications using C#. The MVC Framework will be used for this example, but you can also use ASP.NET Web Forms, Windows Forms, or Web API as per your needs.

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


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.

How to Print Barcode in ASP.NET in C#, Figure 1: Create a new ASP.NET project Create a new ASP.NET project

Add Model

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

How to Print Barcode in ASP.NET in C#, Figure 2: Navigate to add Class Dialog Navigate to add Class Dialog

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

Write the following code in the model class.

using System.ComponentModel.DataAnnotations;

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

    [Display(Name = "Barcode Content")]
    public string BarcodeContent { get; set; }
}
using System.ComponentModel.DataAnnotations;

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

    [Display(Name = "Barcode Content")]
    public string BarcodeContent { get; set; }
}
Imports System.ComponentModel.DataAnnotations

Public Class BarcodeModel
	<Display(Name :="Barcode File Name")>
	Public Property FileName() As String

	<Display(Name := "Barcode Content")>
	Public Property BarcodeContent() As String
End Class
$vbLabelText   $csharpLabel

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, a Controller is added to the project. It will communicate with a View and Model using the MVC model. The code for generating barcodes consists of just two or three lines. Therefore, there is no need for a separate class; instead, the code is added inside the Controller.

To add the Controller, right-click on the Controllers folder > Add > Controller. A new window will appear. Select MVC 5 Controller Empty. Click the Add button. A new box will appear.

How to Print Barcode in ASP.NET in C#, Figure 3: Add Controller Dialog Add Controller Dialog

Write your Controller name, for example, BarcodeController. Click the Add button. A new Controller will be generated.

The next step is to install the barcode library.

Install the Barcode Library

The IronBarcode library is recommended as a third-party library for generating barcodes. It is free for development and provides multiple features to customize barcodes, such as adding a logo to a 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 the project.

Generate the Barcode

Next, add the following sample code to the controller.

using System.IO;
using System.Linq;
using System.Web.Mvc;
using IronBarCode;

public class BarcodeController : Controller
{
    [HttpPost]
    public ActionResult CreateBarcode(BarcodeModel model)
    {
        try
        {
            // Create a barcode with the specified content and encoding
            var MyBarCode = BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);

            // Define the path where the barcode image will be saved
            string path = Server.MapPath("~/Files/");
            string filepath = Path.Combine(path, model.FileName);

            // Add the barcode value text above the barcode
            MyBarCode.AddBarcodeValueTextAboveBarcode();

            // Save the generated barcode as a JPEG file
            MyBarCode.SaveAsJpeg(filepath);

            // Retrieve the first file from the directory as a sample image
            string image = Directory.GetFiles(path).FirstOrDefault();

            // Pass the image path to the view
            ViewBag.FileName = image;
            return View();
        }
        catch
        {
            // Handle any exceptions that occur
            return View();
        }
    }
}
using System.IO;
using System.Linq;
using System.Web.Mvc;
using IronBarCode;

public class BarcodeController : Controller
{
    [HttpPost]
    public ActionResult CreateBarcode(BarcodeModel model)
    {
        try
        {
            // Create a barcode with the specified content and encoding
            var MyBarCode = BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);

            // Define the path where the barcode image will be saved
            string path = Server.MapPath("~/Files/");
            string filepath = Path.Combine(path, model.FileName);

            // Add the barcode value text above the barcode
            MyBarCode.AddBarcodeValueTextAboveBarcode();

            // Save the generated barcode as a JPEG file
            MyBarCode.SaveAsJpeg(filepath);

            // Retrieve the first file from the directory as a sample image
            string image = Directory.GetFiles(path).FirstOrDefault();

            // Pass the image path to the view
            ViewBag.FileName = image;
            return View();
        }
        catch
        {
            // Handle any exceptions that occur
            return View();
        }
    }
}
Imports System.IO
Imports System.Linq
Imports System.Web.Mvc
Imports IronBarCode

Public Class BarcodeController
	Inherits Controller

	<HttpPost>
	Public Function CreateBarcode(ByVal model As BarcodeModel) As ActionResult
		Try
			' Create a barcode with the specified content and encoding
			Dim MyBarCode = BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128)

			' Define the path where the barcode image will be saved
			Dim path As String = Server.MapPath("~/Files/")
			Dim filepath As String = System.IO.Path.Combine(path, model.FileName)

			' Add the barcode value text above the barcode
			MyBarCode.AddBarcodeValueTextAboveBarcode()

			' Save the generated barcode as a JPEG file
			MyBarCode.SaveAsJpeg(filepath)

			' Retrieve the first file from the directory as a sample image
			Dim image As String = Directory.GetFiles(path).FirstOrDefault()

			' Pass the image path to the view
			ViewBag.FileName = image
			Return View()
		Catch
			' Handle any exceptions that occur
			Return View()
		End Try
	End Function
End Class
$vbLabelText   $csharpLabel
  • try-catch is used to catch any runtime exception.
  • The CreateBarcode function provided by the BarcodeWriter class takes two arguments: the barcode content, and the encoding scheme. 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 the generated barcode images will be saved. The Path.Combine method will combine the path and barcode image name.
  • The AddBarcodeValueTextAboveBarcode 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.GetFiles method will get the newly generated barcode image.
  • ViewBag.FileName is used to send the barcode image's path to the view for displaying the generated barcode image.

QR codes can also be generated in the same way by changing the encoding scheme from Code128 to QRCode.

Add View

The next step is to provide the client-side for this ASP.NET Web Application by adding a new View. Right-click on the name of the Controller method and click the "Add View" button.

How to Print Barcode in ASP.NET in C#, Figure 4: Navigate to add View Dialog Navigate to add View Dialog

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

A new prompt will appear as shown below.

How to Print Barcode in ASP.NET in C#, Figure 5: Add View Dialog Add View Dialog

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")
}
HTML

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

Output

How to Print Barcode in ASP.NET in C#, Figure 6: Run Web Application to display Create form Run Web Application to display Create form

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

How to Print Barcode in ASP.NET in C#, Figure 7: Input your barcode content Input your barcode content

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

How to Print Barcode in ASP.NET in C#, Figure 8: Generate a barcode from a URL Generate a barcode from a URL

Summary

This tutorial demonstrated how to generate barcodes using ASP.NET in C#, combined with the MVC Framework. Microsoft Visual Studio is used as the IDE. IronPDF is a third-party library that is free for development and compatible with all versions of the .NET Framework, including the newly released version. IronBarcode is fast and provides multiple features for working with barcodes. It can also generate QR codes by specifying different types.

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. Visit our licensing page for more details.

Preguntas Frecuentes

¿Cómo puedo generar e imprimir imágenes de códigos de barras en ASP.NET MVC usando C#?

Puedes usar la biblioteca IronBarcode para generar e imprimir imágenes de códigos de barras en aplicaciones ASP.NET MVC. Esto implica crear un proyecto MVC, instalar IronBarcode a través de la Consola del Administrador de Paquetes, y usar el método `BarcodeWriter.CreateBarcode` para generar códigos de barras.

¿Qué pasos están involucrados en crear un nuevo proyecto MVC para imprimir códigos de barras?

Para crear un nuevo proyecto MVC para imprimir códigos de barras, abre Microsoft Visual Studio, selecciona 'Crear nuevo proyecto', elige 'Aplicación web ASP.NET' y selecciona 'MVC' de las plantillas disponibles.

¿Cómo instalo la biblioteca IronBarcode para generar códigos de barras en C#?

Instala la biblioteca IronBarcode abriendo la Consola del Administrador de Paquetes en Visual Studio y ejecutando el comando: Install-Package IronBarcode.

¿Cómo guardo una imagen de código de barras generada en C#?

Puedes guardar una imagen de código de barras generada usando el método `SaveAsJpeg` proporcionado por IronBarcode, especificando la ruta del archivo donde se debe guardar la imagen.

¿Puedo personalizar imágenes de códigos de barras en aplicaciones ASP.NET?

Sí, IronBarcode permite la personalización de imágenes de códigos de barras, incluyendo agregar logotipos, anotaciones y cambiar el tamaño y las dimensiones para ajustarlas a tus necesidades.

¿Cómo puedo mostrar un código de barras generado en una vista MVC?

Para mostrar un código de barras generado en una vista MVC, crea una Vista en tu proyecto y pasa la ruta de la imagen del código de barras a la vista usando `ViewBag`. Esto permite la visualización del código de barras en el lado del cliente.

¿Qué debo hacer si encuentro errores durante la generación de códigos de barras?

Usa un bloque try-catch en tu código C# para manejar cualquier excepción en tiempo de ejecución que pueda ocurrir durante el proceso de generación de códigos de barras, asegurando un manejo de errores robusto.

¿Es posible generar códigos QR usando el mismo método que los códigos de barras?

Sí, utilizando IronBarcode, puedes generar códigos QR configurando el esquema de codificación a `QRCode` en el método `BarcodeWriter.CreateBarcode`.

¿Qué otras bibliotecas de software Iron se recomiendan para la gestión de documentos?

Aparte de IronBarcode, Iron Software ofrece otras bibliotecas como IronPDF, IronXL e IronOCR. Estas bibliotecas proporcionan soluciones integrales para tareas de gestión de documentos.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más