.NET MAUI에서 Android에서 바코드 읽기 및 쓰기
.NET MAUI (Multi-platform App UI)는 Xamarin.Forms의 후속으로, iOS, macOS, Windows 및 Android를 위해 플랫폼 간 애플리케이션을 .NET으로 빌드할 수 있도록 개발자를 지원합니다. 여러 플랫폼에서 원활하게 작동하는 네이티브 사용자 인터페이스를 생성할 수 있도록 개발 프로세스를 간소화합니다.
The BarCode.Android 패키지는 Android에 바코드 지원을 제공합니다!
.NET MAUI에서 Android에서 바코드 읽기 및 쓰기
IronBarcode Android 패키지
The BarCode.Android 패키지는 .NET 크로스 플랫폼 프로젝트를 통해 Android 기기에서 바코드 기능을 활성화합니다. 바닐라 BarCode 패키지는 필요하지 않습니다.
Install-Package BarCode.Android
Install-Package BarCode.Android
.NET MAUI 프로젝트를 생성합니다.
Visual Studio를 열고 'Create a new project'를 클릭합니다. MAUI를 검색하고 .NET MAUI App을 선택한 후 'Next'를 클릭합니다.
BarCode.Android 라이브러리 포함
라이브러리는 다양한 방법으로 추가할 수 있습니다. 가장 쉬운 방법은 아마도 NuGet을 사용하는 것입니다.
- Visual Studio 안에서 'Dependencies'를 마우스 오른쪽 버튼으로 클릭하고 'Manage NuGet Packages ...'를 선택합니다.
- "찾아보기" 탭을 선택하고 "BarCode.Android"를 검색합니다.
- "BarCode.Android" 패키지를 선택하고 "설치"를 클릭합니다.
다른 플랫폼과의 문제를 방지하기 위해 csproj 파일을 수정하여 Android 플랫폼을 대상으로 할 때만 패키지를 포함하도록 합니다. 이를 수행하려면:
- 프로젝트의 *.csproj 파일을 우클릭하고 "Edit Project File"을 선택합니다.
- 새로운 ItemGroup 요소를 만듭니다:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
<PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
<PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
- "BarCode.Android" PackageReference를 방금 생성한 ItemGroup으로 이동합니다.
위 단계는 iOS와 같은 플랫폼에서 "BarCode.Android" 패키지 사용을 방지합니다. 이를 위해 BarCode.iOS를 대신 설치하세요.
Android 번들 구성
Android가 작동하려면 Android 번들 설정을 구성해야 합니다. .csproj 파일에 Android 번들의 구성 파일을 지정하는 다음 항목을 추가합니다:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
프로젝트의 루트 디렉토리에 "BundleConfig.json"이라는 파일 생성. 이 JSON 파일에는 라이브러리 기능에 필수적인 Android 번들에 필요한 설정이 포함되어 있습니다.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
이 구성은 네이티브 라이브러리가 압축되지 않도록 보장하며, 이는 Android 환경에서 라이브러리가 적절히 작동하기 위한 필수 단계입니다.
앱 인터페이스 디자인
사용자가 바코드 및 QR 코드 생성을 위한 값을 입력할 수 있도록 XAML 파일 업데이트. 추가로, 바코드 읽기를 위한 문서를 선택할 수 있는 버튼 추가. 다음은 예시입니다.
<?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 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>
바코드 읽기 및 쓰기
위의 MainPage.xaml 코드에서 체크박스가 생성된 바코드와 QR 코드를 PDF 형식으로 저장할지 여부를 결정합니다. 다음으로, 라이선스 키를 설정합니다. 이 단계에서는 체험판 또는 유료 라이선스 키를 사용해 주세요.
코드는 barcodeInput 변수에서 값을 확인하고 가져온 후 CreateBarcode 메서드를 사용하여 바코드를 생성합니다. 마지막으로, SaveToDownloadsAsync 메서드를 호출하여 Android와 iOS 모두에 적절하게 파일을 저장합니다.
iOS에서는 문서를 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);
}
}
}
}
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 Namespace
프로젝트 실행
이것은 프로젝트를 실행하고 바코드 기능을 사용하는 방법을 보여줄 것입니다.
.NET MAUI App 프로젝트 다운로드
이 가이드의 전체 코드를 다운로드할 수 있습니다. 이는 Visual Studio에서 .NET MAUI App 프로젝트로 열 수 있는 압축된 파일 형태로 제공됩니다.
자주 묻는 질문
.NET MAUI 기반 안드로이드 앱에서 바코드를 생성하고 스캔하는 방법은 무엇인가요?
.NET MAUI 프로젝트에서 BarCode.Android 패키지를 사용하면 Android 기기에서 바코드를 생성하고 스캔할 수 있습니다. 이를 위해서는 Visual Studio에서 NuGet을 통해 패키지를 설정하고, WriteBarcode 및 ReadBarcode 와 같은 제공된 메서드를 사용하여 바코드 기능을 구현해야 합니다.
.NET MAUI 프로젝트에서 Android용 바코드 기능을 설정하려면 어떤 단계가 필요합니까?
.NET MAUI 프로젝트에서 바코드 기능을 설정하려면 NuGet을 사용하여 BarCode.Android 패키지를 설치하고, .csproj 파일에서 Android용 패키지를 조건부로 포함하도록 구성하고, BundleConfig.json 파일을 통해 Android 번들이 구성되었는지 확인하십시오.
안드로이드에서만 바코드 기능을 사용할 수 있도록 .csproj 파일을 어떻게 설정해야 하나요?
.csproj 파일을 편집하여 다음을 추가하세요.
안드로이드 프로젝트에서 BundleConfig.json 파일을 사용하는 목적은 무엇인가요?
BundleConfig.json 파일은 Android 번들 설정을 구성하는 데 사용되며, 네이티브 라이브러리가 압축되지 않도록 합니다. 이는 바코드 라이브러리가 Android 기기에서 올바르게 작동하는 데 필수적입니다.
.NET MAUI 앱에서 바코드 작업을 위한 인터페이스를 어떻게 디자인할 수 있을까요?
XAML을 사용하여 사용자가 바코드 및 QR 코드 생성을 위한 데이터를 입력할 수 있는 앱 인터페이스를 디자인하세요. 바코드를 읽을 문서를 선택하는 버튼과 바코드를 생성, 저장 및 스캔하는 버튼을 포함하세요.
C# 앱에서 바코드를 생성하고 읽는 데 사용되는 메서드는 무엇인가요?
.NET MAUI 앱에서는 WriteBarcode , WriteQRcode , ReadBarcode 와 같은 메서드를 사용하여 각각 바코드를 생성하고, QR 코드를 만들고, 파일에서 바코드를 읽을 수 있습니다.
.NET MAUI 앱에서 바코드 기능을 어떻게 테스트할 수 있나요?
프로젝트에 필요한 구성과 바코드 코드 구현을 완료한 후에는 Visual Studio를 통해 Android 기기 또는 에뮬레이터에서 프로젝트를 실행하여 기능을 테스트할 수 있습니다.
바코드 기능을 포함한 완벽한 .NET MAUI 앱 프로젝트를 어디에서 찾을 수 있나요?
바코드 기능을 포함한 완벽한 .NET MAUI 앱 프로젝트는 IronBarcode 웹사이트에서 압축 파일 형태로 다운로드할 수 있습니다. 이 프로젝트는 Visual Studio에서 열어 추가적인 탐색 및 사용자 정의 작업을 진행할 수 있습니다.
안드로이드 프로젝트에서 바코드 라이브러리를 사용하려면 라이선스가 필요한가요?
네, 프로젝트에서 바코드 라이브러리를 사용하려면 평가판 또는 유료 라이선스 키가 필요합니다. 라이브러리 기능을 활성화하려면 MainPage 생성자에 이 키를 입력해야 합니다.

