Saltar al pie de página
USO DE IRONBARCODE

Cómo Imprimir un Código de Barras en una Aplicación Windows en C#

1.0 Introduction

A way to present data in a visible, machine-readable format is through the use of barcodes. At first, parallel lines were spaced, widened, and sized differently to represent data in barcodes. These modern linear or one-dimensional (1D) barcodes can be read by specialized optical scanners known as barcode readers, of which there are several varieties. Later, two-dimensional (2D) variations were created, known as matrix codes or 2D barcodes, even though they don't really use bars. These variations use rectangles, dots, hexagons, and other patterns in place of the traditional barcodes. 2D optical scanners that are specifically designed to read 2D barcodes are available in a variety of configurations. Another method of reading 2D barcodes is by using a digital camera attached to a computer running software that takes a picture of the barcode and decodes it using the image. The latter form of 2D barcode scanner can be used by a mobile device with an integrated camera, such as a smartphone, by installing specialized application software.

2.0 IronBarcode Features

Generating a dynamic barcode is made easy using IronBarcode's Barcode Library. This simple library can generate a barcode with just a few lines of code. IronBarcode's Barcode Readers include robust barcode generators that enable them to produce high-quality barcodes. This makes it simple for the barcode scanner to read your barcode.

  • IronBarcode can read and write the majority of barcode formats and QR standards, including UPC A/E, Databar, EAN 8/13, MSI, Code 39/93/128, CodaB, RSS 14/Expanded, and ITF.
  • While reading scans and real-time video frames, IronBarcode can rectify rotation, noise, distortion, and skewing. While producing Barcodes, IronBarcode automatically preprocesses barcode pictures to improve reading speed and precision. Dynamic barcodes are popular because they enable content modification.
  • IronBarcode can utilize several cores and threads, which is beneficial for batch processing servers.
  • In single- and multipage documents, IronBarcode can automatically find one or more barcodes.
  • IronBarcode supports both 32-bit and 64-bit architectures and is compatible with both the .NET Framework and .NET Core implementations.
  • IronBarcode supports console, desktop, cloud, and online apps on PC and mobile platforms.
  • IronBarcode can create barcode images for a variety of file and stream types, including PDF, JPG, TIFF, GIF, BMP, PNG, and HTML.

3.0 Creating a New Project in Visual Studio

To use the IronBarcode framework, a Visual Studio .NET project must first be created. Any version of Visual Studio can be used, although the latest version is recommended. Depending on your needs, you can create a .NET Windows Forms application or choose from a variety of project templates. For this lesson, we will use the Windows Forms Application to keep things simple.

How to Print Barcode in C# Windows Application Figure 1 - Windows Forms App

Enter the project's name and location.

How to Print Barcode in C# Windows Application Figure 2

.NET Framework 4.7 will be used in this project.

How to Print Barcode in C# Windows Application Figure 3 - Form1 Application

After creating the project, the Form1.cs file will open in designer view. You can insert the program code, design the user interface, and build/run the program. To use the IronBarcode library in the solution, you need to download the required package. This can be done by using the following code in the Package Manager Console:

Install-Package BarCode

How to Print Barcode in C# Windows Application Figure 4 - Install package Barcode

Alternatively, you can use the NuGet Package Manager to search for and download the "Barcode" package, which will list all the search results. From there, you can select the required package to download.

How to Print Barcode in C# Windows Application Figure 5 - NuGet Package Manager

In our form, we have placed a SaveFileDialog box which allows us to save the generated barcode images to a selected location.

4.0 Generate Barcode Using IronBarcode

The IronBarcode library allows us to generate barcodes quickly with just a few lines of code. Below is a sample code for generating a barcode label using a Windows Form:

using IronBarCode;  // Import IronBarcode namespace for barcode generation
using System;
using System.Windows.Forms;  // For creating Windows Forms applications

namespace IronBarcode_demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();  // Initializes the form components
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                saveFileDialog1.Filter = ".png|*.png";  // Set file filter for saving as PNG
                DialogResult result = saveFileDialog1.ShowDialog();  // Show save file dialog
                if (result == DialogResult.OK)
                {
                    string filename = saveFileDialog1.FileName;  // Get the filename chosen by the user
                    // Create a QR code using data from textBox1, and save it as a PNG
                    QRCodeWriter.CreateQrCode(textBox1.Text, 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0).SaveAsPng(filename);
                    MessageBox.Show("Barcode Generated Successfully");  // Inform user of success
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  // Display error message in case of exception
            }
        }
    }
}
using IronBarCode;  // Import IronBarcode namespace for barcode generation
using System;
using System.Windows.Forms;  // For creating Windows Forms applications

namespace IronBarcode_demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();  // Initializes the form components
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                saveFileDialog1.Filter = ".png|*.png";  // Set file filter for saving as PNG
                DialogResult result = saveFileDialog1.ShowDialog();  // Show save file dialog
                if (result == DialogResult.OK)
                {
                    string filename = saveFileDialog1.FileName;  // Get the filename chosen by the user
                    // Create a QR code using data from textBox1, and save it as a PNG
                    QRCodeWriter.CreateQrCode(textBox1.Text, 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0).SaveAsPng(filename);
                    MessageBox.Show("Barcode Generated Successfully");  // Inform user of success
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  // Display error message in case of exception
            }
        }
    }
}
Imports IronBarCode ' Import IronBarcode namespace for barcode generation
Imports System
Imports System.Windows.Forms ' For creating Windows Forms applications

Namespace IronBarcode_demo
	Partial Public Class Form1
		Inherits Form

		Public Sub New()
			InitializeComponent() ' Initializes the form components
		End Sub

		Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
			Try
				saveFileDialog1.Filter = ".png|*.png" ' Set file filter for saving as PNG
				Dim result As DialogResult = saveFileDialog1.ShowDialog() ' Show save file dialog
				If result = System.Windows.Forms.DialogResult.OK Then
					Dim filename As String = saveFileDialog1.FileName ' Get the filename chosen by the user
					' Create a QR code using data from textBox1, and save it as a PNG
					QRCodeWriter.CreateQrCode(textBox1.Text, 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0).SaveAsPng(filename)
					MessageBox.Show("Barcode Generated Successfully") ' Inform user of success
				End If
			Catch ex As Exception
				MessageBox.Show(ex.Message) ' Display error message in case of exception
			End Try
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Before starting the code, add a text box to the .NET WinForms application. This will allow us to enter the text to generate the barcode. Then add a button to the Windows Forms application and add the required code from the sample code. We are also using the SaveFileDialog tool, which will help to save the generated barcode image to the desired location.

How to Print Barcode in C# Windows Application Figure 6 - Barcode Text

The "Save As" dialog box will pop up when the user clicks the "save barcode" button, and it allows the user to choose the filename and location for the generated barcode image to be saved as a PNG file. The barcode is generated based on the text entered in the text box.

How to Print Barcode in C# Windows Application Figure 7 - SaveAs

The only required argument for the CreateQrCode function is the data that needs to be encoded in the QR code image (a string or a Stream that we are getting from the text box). The method also accepts three additional optional parameters:

  • The default size of the graphic is 500 pixels wide by 500 pixels high.
  • A level for error correction. IronBarcode has four levels of error correction: Low, Medium, High, and Highest. The highest level of correction is used by default when creating QR codes (QRCodeWriter.QrErrorCorrectionLevel.greatest).
  • The QR code's version number. If the value is 0 (the default value), the method is instructed to use the appropriate version number based on the data it will encode.

The example above creates a 500 by 500 pixel graphic using the medium degree of error correction. By using the SaveAsPng function on the custom QR code that was generated, we can save the QR code as a PNG file at a designated file location which we got from the SaveAs file dialog.

Click here for a more comprehensive IronBarcode guide.

5.0 Conclusion

The IronBarcode library is considered one of the top options for generating and recognizing barcodes due to its efficiency and compatibility with various operating systems. It offers a range of features for creating and customizing different barcode types, including the ability to adjust the text, color, line width, and height. Licensing details for the library are available on the website, which includes both paid and free versions for developers. Updates and support are provided for free for one year.

Preguntas Frecuentes

¿Cómo puedo generar un código de barras en una aplicación de formularios de Windows en C#?

Para generar un código de barras en una aplicación de formularios de Windows en C#, puede integrar la biblioteca IronBarcode a través del Gestor de Paquetes NuGet. Cree un cuadro de texto para ingresar los datos del código de barras y un botón para activar la generación del código de barras utilizando el código de ejemplo proporcionado por IronBarcode.

¿Qué pasos están involucrados en configurar un proyecto de Visual Studio para la generación de códigos de barras?

Comience configurando una aplicación de formularios de Windows en Visual Studio con el .NET Framework 4.7 o posterior. Luego, instale el paquete IronBarcode usando el Gestor de Paquetes NuGet para habilitar las capacidades de generación de códigos de barras.

¿Cómo puedo guardar un código de barras generado como un archivo de imagen?

IronBarcode le permite guardar códigos de barras generados como archivos PNG. Puede usar la herramienta 'SaveFileDialog' en una aplicación de formularios de Windows para elegir el nombre de archivo y la ubicación para guardar la imagen del código de barras.

¿Cuáles son los beneficios de usar códigos de barras 2D sobre códigos de barras lineales tradicionales?

Los códigos de barras 2D, como los códigos QR, pueden almacenar más datos que los códigos de barras lineales tradicionales y pueden ser leídos por cámaras digitales o escáneres ópticos especializados, haciéndolos versátiles para diversas aplicaciones.

¿Puedo personalizar el nivel de corrección de errores al generar un código QR?

Sí, IronBarcode le permite establecer el nivel de corrección de errores al generar códigos QR. Esto se puede ajustar a Bajo, Medio, Alto o Máximo, dependiendo de cuán robusto necesite que sea el código QR contra daños o pérdida de datos.

¿Es posible procesar códigos de barras en lotes usando IronBarcode?

Sí, IronBarcode admite procesamiento por lotes utilizando múltiples núcleos e hilos, lo cual es particularmente útil para aplicaciones del lado del servidor que requieren procesamiento de códigos de barras de alto volumen.

¿En qué plataformas se puede usar IronBarcode?

IronBarcode es compatible con tanto .NET Framework como .NET Core, respaldando arquitecturas de 32 bits y 64 bits. Puede usarse en aplicaciones de consola, aplicaciones de escritorio, servicios en la nube y aplicaciones en línea tanto en plataformas PC como móviles.

¿Por qué es clave el preprocesamiento de imágenes en códigos de barras?

El preprocesamiento de imágenes es crucial porque mejora la precisión y velocidad de lectura de códigos de barras al corregir problemas como rotación, ruido, distorsión y sesgado, asegurando la generación y reconocimiento de códigos de barras de alta calidad.

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