So lesen und schreiben Sie Barcode auf Android in .NET MAUI

Chaknith Bin
Chaknith Bin
28. Februar 2022
Aktualisiert 17. Dezember 2024
Teilen Sie:
This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to So lesen und schreiben Sie Barcode auf Android in .NET MAUI

.NET MAUI (Multi-platform App UI) ist der Nachfolger von Xamarin.Forms und ermöglicht Entwicklern, plattformübergreifende Anwendungen für Android, iOS, macOS und Windows mithilfe von .NET zu erstellen. Es rationalisiert den Entwicklungsprozess, indem es die Erstellung nativer Benutzeroberflächen ermöglicht, die nahtlos über mehrere Plattformen hinweg funktionieren.

Das BarCode.Android-Paket bringt Barcode-Unterstützung auf Android!!

IronBarcode Android-Paket

Das BarCode.Android-Paket ermöglicht Barcode-Funktionen auf Android-Geräten über .NET plattformübergreifende Projekte. Das standardmäßige BarCode-Paket wird nicht benötigt.

PM > Install-Package BarCode.Android
C# NuGet-Bibliothek für PDF

Mit NuGet installieren

Install-Package BarCode.Android

Ein .NET MAUI-Projekt erstellen

Öffnen Sie Visual Studio und klicken Sie auf "Ein neues Projekt erstellen". Suchen Sie nach MAUI, wählen Sie .NET MAUI App und "Weiter".

BarCode.Android-Bibliothek einbeziehen

Die Bibliothek kann auf verschiedene Weise hinzugefügt werden. Am einfachsten ist es vielleicht, wenn Sie NuGet verwenden.

  1. Klicken Sie in Visual Studio mit der rechten Maustaste auf "Dependencies" und wählen Sie "Manage NuGet Packages ...".

  2. Wählen Sie die Registerkarte "Browse" und suchen Sie nach "BarCode.Android".

  3. Wählen Sie das Paket "BarCode.Android" aus und klicken Sie auf "Installieren".

    Um Probleme mit anderen Plattformen zu vermeiden, ändern Sie die csproj-Datei so, dass sie das Paket nur dann enthält, wenn es für die Android-Plattform bestimmt ist. Um dies zu tun:

  4. Klicken Sie mit der rechten Maustaste auf die *.csproj-Datei für Ihr Projekt und wählen Sie "Projektdatei bearbeiten".

  5. Erstellen Sie ein neues ItemGroup-Element als solches:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    <PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
XML
  1. Verschieben Sie den "BarCode.Android" PackageReference in die gerade erstellte ItemGroup.

    Die obigen Schritte verhindern, dass das Paket "BarCode.Android" auf Plattformen wie iOS verwendet wird. Dafür installieren Sie stattdessen BarCode.iOS.

Konfigurieren Sie das Android-Bundle

Damit Android funktioniert, müssen Sie die Android-Paket-Einstellungen konfigurieren. Fügen Sie in Ihrer ".csproj"-Datei den folgenden Eintrag hinzu, um die Konfigurationsdatei für das Android-Bundle anzugeben:

<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
XML

Erstellen Sie eine Datei mit dem Namen "BundleConfig.json" im Stammverzeichnis des Projekts. Diese JSON-Datei enthält die erforderlichen Einstellungen für das Android-Bundle, die entscheidend für die Funktionalität der Bibliothek sind.

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

Diese Konfiguration stellt sicher, dass native Bibliotheken dekomprimiert werden, was ein notwendiger Schritt ist, damit die Bibliothek in der Android-Umgebung ordnungsgemäß funktioniert.

Gestalten Sie die App-Oberfläche

Aktualisieren Sie die XAML-Datei, um Benutzern die Eingabe von Werten zur Generierung von Barcodes und QR-Codes zu ermöglichen. Fügen Sie außerdem eine Schaltfläche hinzu, um ein Dokument zum Barcode-Lesen auszuwählen. Hier ist ein Beispiel:

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

Barcodes lesen und schreiben

Aus dem obigen MainPage.xaml-Code können wir sehen, dass das Kontrollkästchen bestimmt, ob der generierte Barcode und QR-Code im PDF-Format sein soll. Als Nächstes setzen wir den Lizenzschlüssel. Bitte verwenden Sie für diesen Schritt entweder einen Test- oder einen bezahlten Lizenzschlüssel.

Der Code überprüft und ruft den Wert der Variablen barcodeInput ab und verwendet dann die CreateBarcode-Methode, um den Barcode zu generieren. Schließlich wird die Methode SaveToDownloadsAsync aufgerufen, die die Datei sowohl für Android als auch für iOS entsprechend speichert.

Auf iOS ist ein benutzerdefinierter Dateipfad erforderlich, um das Dokument in die Dateien-Anwendung zu exportieren.

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

Das Projekt ausführen

Dies wird Ihnen zeigen, wie Sie das Projekt ausführen und die Barcode-Funktion verwenden können.

Ausführen des .NET MAUI App-Projekts

.NET MAUI App Projekt herunterladen

Sie können den vollständigen Code für diese Anleitung herunterladen. Er wird als gezippte Datei geliefert, die Sie in Visual Studio als .NET MAUI App-Projekt öffnen können.

Klicken Sie hier, um das Projekt herunterzuladen.

Chaknith Bin
Software-Ingenieur
Chaknith arbeitet an IronXL und IronBarcode. Er hat tiefgehende Expertise in C# und .NET und hilft, die Software zu verbessern und Kunden zu unterstützen. Seine Erkenntnisse aus Benutzerinteraktionen tragen zu besseren Produkten, Dokumentation und einem insgesamt besseren Erlebnis bei.