Comment lire et écrire des codes-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 de manière transparente sur plusieurs plateformes.
Le paquet BarCode.Android apporte le support des codes-barres à Android !
Comment lire et écrire des codes-barres sur Android avec .NET MAUI
- Téléchargez la bibliothèque C# pour lire et écrire des codes-barres sur Android
- Create a .NET MAUI App project
- Modifiez le fichier XAML pour ajouter un bouton d'activation et afficher le texte de sortie
- Modifiez le fichier C# correspondant pour gérer la reconnaissance des codes-barres
- Téléchargez l'exemple de projet pour un démarrage rapide
Package Android IronBarcode
Le paquet BarCode.Android active les fonctionnalités de code-barres sur les appareils Android via des projets multiplateformes .NET. Le package BarCode standard n'est pas nécessaire.
Installer avec NuGet
Installer le 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 « Suivant ».
Inclure la bibliothèque BarCode.Android
La bibliothèque peut être ajoutée de différentes manières. La plus simple est peut-être d'utiliser NuGet.
- Dans Visual Studio, faites un clic droit sur « Dépendances » et sélectionnez « Gérer les Packages NuGet ... ».
- Sélectionnez l'onglet « Parcourir » et recherchez « BarCode.Android ».
- 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 package que lors du ciblage de la plateforme Android. Pour ce faire :
-
Faites un clic droit sur le fichier *.csproj de votre projet et sélectionnez « Modifier le fichier projet ».
-
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 -
Déplacez le PackageReference « BarCode.Android » à l'intérieur de l'ItemGroup que nous venons de créer.
Les étapes ci-dessus empêcheront le package « BarCode.Android » d'être utilisé sur des plateformes telles que iOS. À cette fin, installez plutôt BarCode.iOS.
Configurer le Bundle Android
Pour qu'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>
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, lesquels sont cruciaux pour la fonctionnalité de la bibliothèque.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
Cette configuration garantit que les bibliothèques natives ne sont pas 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
Mettez à jour le fichier XAML pour permettre aux utilisateurs d'entrer des valeurs pour générer des codes-barres et QR codes. En outre, ajoutez un bouton pour choisir un document pour la lecture de codes-barres. 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>
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 ou payée 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 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 NamespaceExécuter le projet
Cela vous montrera comment exécuter le projet et utiliser la fonction de code-barres.
Télécharger le projet d'application .NET MAUI
Vous pouvez télécharger le code complet pour ce guide. Il vient sous forme d'un fichier zippé que vous pouvez ouvrir dans Visual Studio en tant que projet d'application .NET MAUI.
Cliquez ici pour télécharger le projet.
Questions fréquemment posées
Qu'est-ce que .NET MAUI et comment cela se rapporte-t-il au scannage de codes-barres sur Android ?
.NET MAUI, ou Multi-platform App UI, est le successeur de Xamarin.Forms, permettant aux développeurs de créer des applications multiplateformes. Le package BarCode.Android s'intègre à .NET MAUI pour permettre la lecture et l'écriture de codes-barres sur les appareils Android.
Comment ajouter la bibliothèque BarCode.Android à mon projet .NET MAUI ?
Vous pouvez ajouter la bibliothèque BarCode.Android en utilisant NuGet dans Visual Studio. Faites un clic droit sur 'Dépendances', choisissez 'Gérer les packages NuGet', recherchez 'BarCode.Android' et cliquez sur 'Installer'.
Le package BarCode.Android peut-il être utilisé pour des plateformes autres qu'Android ?
Le package BarCode.Android est spécifiquement conçu pour Android. Pour iOS, vous devez utiliser à la place le package BarCode.iOS.
Comment puis-je configurer mon projet pour inclure la bibliothèque BarCode.Android uniquement pour Android ?
Vous devez modifier votre fichier .csproj pour inclure un ItemGroup conditionnel pour le package BarCode.Android uniquement lorsque vous ciblez Android, en utilisant la condition TargetFramework.
Ai-je besoin d'un fichier de configuration spécifique pour utiliser la bibliothèque BarCode.Android sur Android ?
Oui, vous devez spécifier le fichier de configuration pour le bundle Android dans votre fichier .csproj, généralement nommé 'BundleConfig.json', pour garantir que les bibliothèques natives ne soient pas compressées.
Comment puis-je générer et enregistrer un code-barres en utilisant IronBarcode dans une application MAUI ?
Vous pouvez utiliser la classe BarcodeWriter pour créer un code-barres à partir d'une entrée texte, déterminer le format (PDF ou PNG), puis l'enregistrer en utilisant une méthode comme SaveToDownloadsAsync pour Android et iOS.
Quels formats de fichier sont pris en charge pour l'enregistrement des codes-barres générés dans IronBarcode ?
IronBarcode permet d'enregistrer les codes-barres aux formats PDF ou PNG, selon le choix de l'utilisateur dans l'application.
Comment IronBarcode aide-t-il à traiter les codes QR dans une application .NET MAUI Android ?
IronBarcode facilite la création et la lecture de codes QR grâce à la classe QRCodeWriter, permettant des fonctionnalités telles que la génération de codes QR à partir de texte d'entrée et la lecture de données de codes-barres à partir de fichiers.
Existe-t-il un projet exemple disponible pour commencer avec IronBarcode dans .NET MAUI ?
Oui, vous pouvez télécharger un projet complet d'application .NET MAUI avec le code exemple fourni dans le guide pour commencer rapidement.
Quelles fonctionnalités IronBarcode fournit-il pour la lecture de données de codes-barres à partir de fichiers ?
IronBarcode peut lire les codes-barres à partir d'images et de fichiers PDF en utilisant la classe BarcodeReader, avec des résultats formatés et affichés en conséquence dans l'application.
Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes et créer des manuels bien structurés et visuellement attrayants.