Cómo leer y escribir códigos de barras en Android en .NET MAUI

Chaknith Bin
Chaknith Bin
28 de febrero, 2022
Actualizado 17 de diciembre, 2024
Compartir:
This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to Cómo leer y escribir códigos de barras en Android en .NET MAUI

.NET MAUI (Interfaz de Usuario de Aplicaciones Multiplataforma) es el sucesor de Xamarin.Forms, permitiendo a los desarrolladores crear 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 perfectamente en múltiples plataformas.

El paquete BarCode.Android lleva el soporte de códigos de barras a Android.

IronBarcode Android Package

El paquete BarCode.Android habilita funciones de códigos de barras en dispositivos Android a través de proyectos multiplataforma de .NET. El paquete estándar de BarCode no es necesario.

PM > Install-Package BarCode.Android
Biblioteca NuGet de C# para PDF

Instalar con NuGet

Install-Package BarCode.Android

Crear un proyecto .NET MAUI

Abra Visual Studio y haga clic en "Crear un nuevo proyecto". Busca MAUI, selecciona .NET MAUI App y "Siguiente".

Incluir la biblioteca BarCode.Android

La biblioteca puede añadirse de varias maneras. La forma más sencilla es quizás utilizando NuGet.

  1. Dentro de Visual Studio, haga clic con el botón derecho en "Dependencias" y seleccione "Administrar paquetes NuGet ...".

  2. Seleccione la pestaña "Examinar" y busque "BarCode.Android".

  3. Seleccione el paquete "BarCode.Android" y haga clic en "Instalar".

    Para evitar problemas con otras plataformas, modifique el archivo csproj para que sólo incluya el paquete cuando se dirija a la plataforma Android. Para ello:

  4. Haga clic con el botón derecho del ratón en el archivo *.csproj de su proyecto y seleccione "Editar archivo de proyecto".

  5. Cree un nuevo elemento ItemGroup como tal:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    <PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
XML
  1. Mueva la referencia del paquete "BarCode.Android" dentro del ItemGroup que acabamos de crear.

    Los pasos anteriores evitarán que el paquete "BarCode.Android" se utilice en plataformas como iOS. Para ese propósito, instale BarCode.iOS en su lugar.

Configurar el paquete de Android

Para que Android funcione, necesitas configurar los ajustes del paquete de Android. En su archivo ".csproj", agregue la siguiente entrada para especificar el archivo de configuración del paquete de Android:

<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
XML

Crea un archivo llamado "BundleConfig.json" en el directorio raíz del proyecto. Este archivo JSON contiene la configuración necesaria para el paquete de Android, que es crucial para la funcionalidad de la biblioteca.

{
    "optimizations" : 
    {
        "uncompress_native_libraries" : {}
    }
}

Esta configuración asegura que las bibliotecas nativas se descompriman, lo cual es un paso necesario para que la biblioteca funcione correctamente en el entorno de Android.

Diseñar la interfaz de la aplicación

Actualice el archivo XAML para permitir a los usuarios ingresar valores para generar códigos de barras y códigos QR. Además, añade un botón para elegir un documento para la lectura de código de barras. He aquí 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>
XML

Leer y Escribir Códigos de Barras

A partir del código MainPage.xaml anterior, podemos ver que la casilla de verificación determina si el código de barras y el código QR generados deben estar en formato PDF. A continuación, establecemos la clave de licencia. Utilice 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 utiliza el método CreateBarcode para generar el código de barras. Finalmente, llama al método SaveToDownloadsAsync, que guarda el archivo adecuadamente tanto para Android como para iOS.

En iOS, se requiere una ruta de archivo personalizada para exportar el documento a la aplicación Archivos.

using IronBarCode;

namespace IronBarcodeMauiAndroid
{
    public partial class MainPage : ContentPage
    {
        public bool IsGeneratePdfChecked
        {
            get => generatePdfCheckBox.IsChecked;
            set
            {
                generatePdfCheckBox.IsChecked = value;
            }
        }

        public MainPage()
        {
            InitializeComponent();
            License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
        }

        private async void WriteBarcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(barcodeInput.Text))
                {
                    var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);

                    // Generate file name
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void WriteQRcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(qrInput.Text))
                {
                    var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);

                    // Generate file name
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions
                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"))
                    {
                        result = BarcodeReader.Read(stream);
                    }
                    else
                    {
                        result = BarcodeReader.ReadPdf(stream);
                    }

                    string barcodeResult = "";
                    int count = 1;

                    result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });

                    OutputText.Text = barcodeResult;
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
        {
#if ANDROID
            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)
            {
                System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
            }
#endif
        }
    }
}
using IronBarCode;

namespace IronBarcodeMauiAndroid
{
    public partial class MainPage : ContentPage
    {
        public bool IsGeneratePdfChecked
        {
            get => generatePdfCheckBox.IsChecked;
            set
            {
                generatePdfCheckBox.IsChecked = value;
            }
        }

        public MainPage()
        {
            InitializeComponent();
            License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
        }

        private async void WriteBarcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(barcodeInput.Text))
                {
                    var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);

                    // Generate file name
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void WriteQRcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(qrInput.Text))
                {
                    var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);

                    // Generate file name
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions
                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"))
                    {
                        result = BarcodeReader.Read(stream);
                    }
                    else
                    {
                        result = BarcodeReader.ReadPdf(stream);
                    }

                    string barcodeResult = "";
                    int count = 1;

                    result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });

                    OutputText.Text = barcodeResult;
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
        {
#if ANDROID
            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)
            {
                System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
            }
#endif
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronBarCode

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()
			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
					Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)

					' Generate file name
					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())

					' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
					Await SaveToDownloadsAsync(fileData, fileName)

					Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
				End If
			Catch ex As Exception
				' Handle exceptions
				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
					Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)

					' Generate file name
					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())

					' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
					Await SaveToDownloadsAsync(fileData, fileName)

					Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
				End If
			Catch ex As Exception
				' Handle exceptions
				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
						result = BarcodeReader.Read(stream)
					Else
						result = BarcodeReader.ReadPdf(stream)
					End If

					Dim barcodeResult As String = ""
					Dim count As Integer = 1

					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
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
#If ANDROID Then
			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
				System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
			End Try
#End If
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

Ejecutar el proyecto

Esto te mostrará cómo ejecutar el proyecto y usar la función de código de barras.

Ejecutar proyecto .NET MAUI App

Descargar proyecto de aplicación .NET MAUI

Puedes descargar el código completo de esta guía. Viene como un archivo comprimido que puedes abrir en Visual Studio como un proyecto de aplicación .NET MAUI.

Haz clic aquí para descargar el proyecto.

Chaknith Bin
Ingeniero de software
Chaknith trabaja en IronXL e IronBarcode. Tiene una gran experiencia en C# y .NET, ayudando a mejorar el software y a apoyar a los clientes. Sus conocimientos de las interacciones con los usuarios contribuyen a mejorar los productos, la documentación y la experiencia general.