Cómo leer y escribir códigos de barras en Android en .NET MAUI
.NET MAUI (Interfaz de usuario de aplicación multiplataforma) es el sucesor de Xamarin.Forms, permitiendo a los desarrolladores construir aplicaciones multiplataforma para Android, iOS, macOS y Windows usando .NET. Simplifica el proceso de desarrollo al permitir la creación de interfaces de usuario nativas que funcionan sin problemas en múltiples plataformas.
¡El paquete BarCode.Android trae soporte para códigos de barras a Android!
Cómo leer y escribir códigos de barras en Android en .NET MAUI
- Descargar la biblioteca C# para leer y escribir códigos de barras en Android
- Crear un proyecto de aplicación .NET MAUI
- Editar el archivo XAML para agregar un botón de activación y mostrar el texto de salida
- Editar el archivo C# correspondiente para gestionar el reconocimiento de códigos de barras
- Descargar el proyecto de ejemplo para un inicio rápido
Paquete IronBarcode para Android
El paquete BarCode.Android habilita funciones de códigos de barras en dispositivos Android a través de proyectos multiplataforma .NET. No se necesita el paquete BarCode estándar.
Instalar con NuGet
Paquete de instalación BarCode.Android
Crear un proyecto .NET MAUI
Abre Visual Studio y haz clic en "Crear un nuevo proyecto". Busca MAUI, selecciona .NET MAUI App y "Siguiente".
Incluir la biblioteca BarCode.Android
La biblioteca se puede agregar de varias maneras. La más fácil es quizás usando NuGet.
- Dentro de Visual Studio, haz clic derecho en "Dependencias" y selecciona "Gestionar paquetes NuGet ...".
- Selecciona la pestaña "Explorar" y busca "BarCode.Android".
- Selecciona el paquete "BarCode.Android" y haz clic en "Instalar".
Para evitar problemas con otras plataformas, modifica el archivo csproj para incluir el paquete solo cuando se apunte a la plataforma Android. Para hacerlo:
-
Haz clic derecho en el archivo *.csproj de tu proyecto y selecciona "Editar archivo del proyecto".
-
Crea un nuevo elemento ItemGroup de la siguiente manera:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true"> <PackageReference Include="BarCode.Android" Version="2025.3.4" /> </ItemGroup>XML -
Mueve la referencia del paquete "BarCode.Android" dentro del ItemGroup que acabamos de crear.
Los pasos anteriores evitarán que el paquete "BarCode.Android" se use en plataformas como iOS. Para ese propósito, instala BarCode.iOS en su lugar.
Configurar el paquete Android
Para que Android funcione, debes configurar las opciones del paquete Android. En tu archivo ".csproj", añade la siguiente entrada para especificar el archivo de configuración para el paquete Android:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
Crea un archivo llamado "BundleConfig.json" en el directorio raíz del proyecto. Este archivo JSON contiene las configuraciones necesarias para el paquete Android, que son cruciales para la funcionalidad de la biblioteca.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
Esta configuración asegura que las bibliotecas nativas no estén comprimidas, lo cual es un paso necesario para que la biblioteca funcione correctamente en el entorno Android.
Diseñar la interfaz de la aplicación
Actualiza el archivo XAML para permitir a los usuarios introducir valores para generar códigos de barras y códigos QR. Además, agrega un botón para elegir un documento para la lectura de códigos de barras. Aquí hay un ejemplo:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="IronBarcodeMauiAndroid.MainPage">
<VerticalStackLayout Padding="20">
<HorizontalStackLayout>
<CheckBox x:Name="generatePdfCheckBox" IsChecked="{Binding IsGeneratePdfChecked}" />
<Label Text="PDF (unchecked for PNG)" VerticalOptions="Center"/>
</HorizontalStackLayout>
<Entry x:Name="barcodeInput" Placeholder="Enter barcode value..." />
<Button Text="Generate and save barcode" Clicked="WriteBarcode" />
<Entry x:Name="qrInput" Placeholder="Enter QR code value..." />
<Button Text="Generate and save QR code" Clicked="WriteQRcode" />
<Button
Text="Read Barcode"
Clicked="ReadBarcode"
Grid.Row="0"
HorizontalOptions="Center"
Margin="20, 20, 20, 10"/>
<ScrollView
Grid.Row="1"
BackgroundColor="LightGray"
Padding="10"
Margin="10, 10, 10, 30">
<Label x:Name="OutputText"/>
</ScrollView>
</VerticalStackLayout>
</ContentPage>
Leer y escribir códigos de barras
Desde el código MainPage.xaml anterior, podemos ver que la casilla de verificación determina si el código de barras generado y el código QR debe estar en formato PDF. Configurar la clave de licencia. Por favor, usa una clave de licencia de prueba o de pago para este paso.
El código verifica y recupera el valor de la variable barcodeInput, luego usa el método CreateBarcode para generar el código de barras. Finalmente, llama al método SaveToDownloadsAsync, que guarda el archivo adecuadamente para Android e iOS.
En iOS, se requiere una ruta de archivo personalizada para exportar el documento a la aplicación Files.
using IronBarCode;
using System;
using System.IO;
using System.Threading.Tasks;
using Xamarin.Essentials;
namespace IronBarcodeMauiAndroid
{
public partial class MainPage : ContentPage
{
public bool IsGeneratePdfChecked
{
get => generatePdfCheckBox.IsChecked;
set
{
generatePdfCheckBox.IsChecked = value;
}
}
public MainPage()
{
InitializeComponent();
// Set the license key for IronBarcode, replace with your actual license key.
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
}
private async void WriteBarcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(barcodeInput.Text))
{
// Create a barcode from the text input with the EAN13 encoding.
var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
// Determine the file extension and data format based on the checkbox state.
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Save the generated barcode to the Downloads folder.
await SaveToDownloadsAsync(fileData, fileName);
await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
}
}
catch (Exception ex)
{
// Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex);
}
}
private async void WriteQRcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(qrInput.Text))
{
// Create a QR code from the text input.
var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
// Determine the file extension and data format based on the checkbox state.
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Save the generated QR code to the Downloads folder.
await SaveToDownloadsAsync(fileData, fileName);
await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
}
}
catch (Exception ex)
{
// Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex);
}
}
private async void ReadBarcode(object sender, EventArgs e)
{
try
{
var options = new PickOptions
{
PickerTitle = "Please select a file"
};
var file = await FilePicker.PickAsync(options);
OutputText.Text = "";
if (file != null)
{
using var stream = await file.OpenReadAsync();
BarcodeResults result;
if (file.ContentType.Contains("image"))
{
// Read barcodes from an image file.
result = BarcodeReader.Read(stream);
}
else
{
// Read barcodes from a PDF file.
result = BarcodeReader.ReadPdf(stream);
}
string barcodeResult = "";
int count = 1;
// Retrieve and format the barcode reading results.
result.ForEach(x => { barcodeResult += $"Barcode {count}: {x.Value}\n"; count++; });
OutputText.Text = barcodeResult;
}
}
catch (Exception ex)
{
// Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex);
}
}
public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
{
var downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadsPath.AbsolutePath, fileName);
try
{
// Create the directory if it doesn't exist.
if (!Directory.Exists(downloadsPath.AbsolutePath))
{
Directory.CreateDirectory(downloadsPath.AbsolutePath);
}
// Save the file to the Downloads folder.
await File.WriteAllBytesAsync(filePath, fileData);
}
catch (Exception ex)
{
// Log errors if file saving fails.
System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
}
}
}
}Imports Microsoft.VisualBasic
Imports IronBarCode
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Xamarin.Essentials
Namespace IronBarcodeMauiAndroid
Partial Public Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked() As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(ByVal value As Boolean)
generatePdfCheckBox.IsChecked = value
End Set
End Property
Public Sub New()
InitializeComponent()
' Set the license key for IronBarcode, replace with your actual license key.
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
End Sub
Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(barcodeInput.Text) Then
' Create a barcode from the text input with the EAN13 encoding.
Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
' Save the generated barcode to the Downloads folder.
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(qrInput.Text) Then
' Create a QR code from the text input.
Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
' Save the generated QR code to the Downloads folder.
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
Dim file = Await FilePicker.PickAsync(options)
OutputText.Text = ""
If file IsNot Nothing Then
Dim stream = Await file.OpenReadAsync()
Dim result As BarcodeResults
If file.ContentType.Contains("image") Then
' Read barcodes from an image file.
result = BarcodeReader.Read(stream)
Else
' Read barcodes from a PDF file.
result = BarcodeReader.ReadPdf(stream)
End If
Dim barcodeResult As String = ""
Dim count As Integer = 1
' Retrieve and format the barcode reading results.
result.ForEach(Sub(x)
barcodeResult &= $"Barcode {count}: {x.Value}" & vbLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
Dim downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
Dim filePath = Path.Combine(downloadsPath.AbsolutePath, fileName)
Try
' Create the directory if it doesn't exist.
If Not Directory.Exists(downloadsPath.AbsolutePath) Then
Directory.CreateDirectory(downloadsPath.AbsolutePath)
End If
' Save the file to the Downloads folder.
Await File.WriteAllBytesAsync(filePath, fileData)
Catch ex As Exception
' Log errors if file saving fails.
System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
End Try
End Function
End Class
End NamespaceImports Microsoft.VisualBasic
Imports IronBarCode
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Xamarin.Essentials
Namespace IronBarcodeMauiAndroid
Partial Public Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked() As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(ByVal value As Boolean)
generatePdfCheckBox.IsChecked = value
End Set
End Property
Public Sub New()
InitializeComponent()
' Set the license key for IronBarcode, replace with your actual license key.
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
End Sub
Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(barcodeInput.Text) Then
' Create a barcode from the text input with the EAN13 encoding.
Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
' Save the generated barcode to the Downloads folder.
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
Try
If Not String.IsNullOrEmpty(qrInput.Text) Then
' Create a QR code from the text input.
Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)
' Determine the file extension and data format based on the checkbox state.
Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
' Save the generated QR code to the Downloads folder.
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
Dim file = Await FilePicker.PickAsync(options)
OutputText.Text = ""
If file IsNot Nothing Then
Dim stream = Await file.OpenReadAsync()
Dim result As BarcodeResults
If file.ContentType.Contains("image") Then
' Read barcodes from an image file.
result = BarcodeReader.Read(stream)
Else
' Read barcodes from a PDF file.
result = BarcodeReader.ReadPdf(stream)
End If
Dim barcodeResult As String = ""
Dim count As Integer = 1
' Retrieve and format the barcode reading results.
result.ForEach(Sub(x)
barcodeResult &= $"Barcode {count}: {x.Value}" & vbLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End If
Catch ex As Exception
' Handle exceptions and log the error.
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
Dim downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
Dim filePath = Path.Combine(downloadsPath.AbsolutePath, fileName)
Try
' Create the directory if it doesn't exist.
If Not Directory.Exists(downloadsPath.AbsolutePath) Then
Directory.CreateDirectory(downloadsPath.AbsolutePath)
End If
' Save the file to the Downloads folder.
Await File.WriteAllBytesAsync(filePath, fileData)
Catch ex As Exception
' Log errors if file saving fails.
System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
End Try
End Function
End Class
End NamespaceEjecutar el proyecto
Esto te mostrará cómo ejecutar el proyecto y usar la función de código de barras.
Descargar proyecto de aplicación .NET MAUI
Puede descargar el código completo de esta guía. Viene como un archivo comprimido que puede abrir en Visual Studio como un proyecto de aplicación .NET MAUI.
Haga clic aquí para descargar el proyecto.
Preguntas frecuentes
¿Qué es .NET MAUI y cómo se relaciona con el escaneo de códigos de barras en Android?
.NET MAUI, o Multi-platform App UI, es el sucesor de Xamarin.Forms, lo que permite a los desarrolladores construir aplicaciones multiplataforma. El paquete BarCode.Android se integra con .NET MAUI para habilitar la lectura y escritura de códigos de barras en dispositivos Android.
¿Cómo agrego la biblioteca BarCode.Android a mi proyecto .NET MAUI?
Puede agregar la biblioteca BarCode.Android usando NuGet en Visual Studio. Haga clic derecho sobre 'Dependencies', elija 'Manage NuGet Packages', busque 'BarCode.Android' y haga clic en 'Install'.
¿Puede usarse el paquete BarCode.Android en plataformas que no sean Android?
El paquete BarCode.Android está específicamente diseñado para Android. Para iOS, necesita usar en su lugar el paquete BarCode.iOS.
¿Cómo puedo configurar mi proyecto para incluir la biblioteca BarCode.Android solo para Android?
Debe editar su archivo .csproj para incluir un grupo de ítems condicional para el paquete BarCode.Android solo al apuntar a Android, usando la condición TargetFramework.
¿Necesito un archivo de configuración específico para usar la biblioteca BarCode.Android en Android?
Sí, necesita especificar el archivo de configuración para el bundle de Android en su archivo .csproj, típicamente nombrado 'BundleConfig.json', para asegurar que las bibliotecas nativas no estén comprimidas.
¿Cómo puedo generar y guardar un código de barras usando IronBarcode en una aplicación MAUI?
Puede usar la clase BarcodeWriter para crear un código de barras a partir de una entrada de texto, determinar el formato (PDF o PNG), y luego guardarlo usando un método como SaveToDownloadsAsync para Android y iOS.
¿Qué formatos de archivo son compatibles para guardar códigos de barras generados en IronBarcode?
IronBarcode permite guardar los códigos de barras en formatos PDF o PNG, según la elección del usuario en la aplicación.
¿Cómo ayuda IronBarcode en el procesamiento de códigos QR en una aplicación .NET MAUI Android?
IronBarcode facilita la creación y lectura de códigos QR a través de la clase QRCodeWriter, habilitando funcionalidades como generar códigos QR a partir de texto de entrada y leer datos de códigos de barras de archivos.
¿Existe un proyecto de ejemplo disponible para comenzar con IronBarcode en .NET MAUI?
Sí, puede descargar un proyecto completo de la aplicación .NET MAUI con el código de ejemplo proporcionado en la guía para comenzar rápidamente.
¿Qué funcionalidades proporciona IronBarcode para leer datos de códigos de barras de archivos?
IronBarcode puede leer códigos de barras de archivos de imagen y PDF usando la clase BarcodeReader, con resultados formateados y mostrados adecuadamente en la aplicación.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.