Comment lire et écrire un code-barres sur Android avec .NET MAUI

Chaknith Bin
Chaknith Bin
février 28, 2022
Mise à jour décembre 17, 2024
Partager:
This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to Comment lire et écrire un code-barres sur Android avec .NET MAUI

.NET MAUI (Multi-platform App UI) est le successeur de Xamarin.Forms, permettant aux développeurs de créer des applications multiplateformes pour Android, iOS, macOS et Windows en utilisant .NET. Il simplifie le processus de développement en permettant la création d'interfaces utilisateur natives qui fonctionnent parfaitement sur plusieurs plateformes.

Le package BarCode.Android apporte la prise en charge des codes-barres à Android !!

Package Android IronBarcode

Le package BarCode.Android permet d'activer les fonctionnalités de code-barres sur les appareils Android via des projets .NET multiplateformes. Le package vanilla BarCode n'est pas nécessaire.

PM > Install-Package BarCode.Android
Bibliothèque C# NuGet pour PDF

Installer avec NuGet

Install-Package BarCode.Android

Créer un projet .NET MAUI

Ouvrez Visual Studio et cliquez sur "Créer un nouveau projet". Recherchez MAUI, sélectionnez .NET MAUI App et cliquez sur "Next".

Inclure la bibliothèque BarCode.Android

La bibliothèque peut être ajoutée de différentes manières. Le plus simple est sans doute d'utiliser NuGet.

  1. Dans Visual Studio, faites un clic droit sur "Dependencies" et sélectionnez "Manage NuGet Packages ...".

  2. Sélectionnez l'onglet "Parcourir" et recherchez "BarCode.Android".

  3. Sélectionnez le package "BarCode.Android" et cliquez sur "Installer".

    Pour éviter les problèmes avec d'autres plateformes, modifiez le fichier csproj pour n'inclure le paquet que lorsqu'il s'agit de la plateforme Android. Pour ce faire :

  4. Cliquez avec le bouton droit de la souris sur le fichier *.csproj de votre projet et sélectionnez "Edit Project File".

  5. Créez un nouvel élément ItemGroup comme suit :
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    <PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
XML
  1. Déplacez la PackageReference "BarCode.Android" à l'intérieur du ItemGroup que nous venons de créer.

    Les étapes ci-dessus empêcheront le package "BarCode.Android" d'être utilisé sur des plateformes telles qu'iOS. À cette fin, installez BarCode.iOS à la place.

Configurer le bundle Android

Pour que Android fonctionne, vous devez configurer les paramètres du bundle Android. Dans votre fichier ".csproj", ajoutez l'entrée suivante pour spécifier le fichier de configuration pour le bundle Android :

<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
XML

Créez un fichier nommé "BundleConfig.json" dans le répertoire racine du projet. Ce fichier JSON contient les paramètres requis pour le bundle Android, qui sont essentiels pour le fonctionnement de la bibliothèque.

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

Cette configuration garantit que les bibliothèques natives sont décompressées, ce qui est une étape nécessaire pour que la bibliothèque fonctionne correctement dans l'environnement Android.

Concevoir l'interface de l'application

Mettre à jour le fichier XAML pour permettre aux utilisateurs de saisir des valeurs pour générer des codes-barres et des codes QR. De plus, ajoutez un bouton pour choisir un document pour la lecture de codes-barres. En voici un exemple :

<?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

Lire et écrire des codes-barres

À partir du code MainPage.xaml ci-dessus, nous pouvons voir que la case à cocher détermine si le code-barres et le code QR générés doivent être au format PDF. Ensuite, nous définissons la clé de licence. Veuillez utiliser soit une clé de licence d'essai, soit une clé de licence payante pour cette étape.

Le code vérifie et récupère la valeur de la variable barcodeInput, puis utilise la méthode CreateBarcode pour générer le code-barres. Enfin, il appelle la méthode SaveToDownloadsAsync, qui enregistre le fichier de manière appropriée pour Android et iOS.

Sur iOS, un chemin de fichier personnalisé est nécessaire pour exporter le document vers l'application Fichiers.

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

Exécuter le projet

Cela vous montrera comment exécuter le projet et utiliser la fonctionnalité de code-barres.

Exécuter le projet .NET MAUI App

Télécharger le projet d'application .NET MAUI

Vous pouvez télécharger le code complet de ce guide. Il s'agit d'un fichier zippé que vous pouvez ouvrir dans Visual Studio en tant que projet .NET MAUI App.

Cliquez ici pour télécharger le projet.

Chaknith Bin
Ingénieur logiciel
Chaknith travaille sur IronXL et IronBarcode. Il possède une expertise approfondie en C# et .NET, aidant à améliorer le logiciel et à soutenir les clients. Ses idées issues des interactions avec les utilisateurs contribuent à de meilleurs produits, une documentation améliorée et une expérience globale enrichie.