.NET MAUI에서 Android에서 바코드 읽기 및 쓰기

Curtis Chau
Curtis Chau
업데이트됨: 2026년 8월 2일
android

.NET MAUI (Multi-platform App UI)는 Xamarin.Forms의 후속으로, iOS, macOS, Windows 및 Android를 위해 플랫폼 간 애플리케이션을 .NET으로 빌드할 수 있도록 개발자를 지원합니다. 여러 플랫폼에서 원활하게 작동하는 네이티브 사용자 인터페이스를 생성할 수 있도록 개발 프로세스를 간소화합니다.

The BarCode.Android 패키지는 Android에 바코드 지원을 제공합니다!

IronBarcode Android 패키지

The BarCode.Android 패키지는 .NET 크로스 플랫폼 프로젝트를 통해 Android 기기에 바코드 기능을 활성화합니다. 바닐라 BarCode 패키지는 필요하지 않습니다.

PM > Install-Package BarCode.Android

PDF용 C# NuGet 라이브러리

NuGet을 사용하여 설치하세요

Install-Package BarCode.Android

.NET MAUI 프로젝트를 생성합니다.

Visual Studio를 열고 'Create a new project'를 클릭합니다. MAUI를 검색하고 .NET MAUI App을 선택한 후 'Next'를 클릭합니다.

BarCode.Android 라이브러리 포함

라이브러리는 다양한 방법으로 추가할 수 있습니다. 가장 쉬운 방법은 아마도 NuGet을 사용하는 것입니다.

  1. Visual Studio 안에서 'Dependencies'를 마우스 오른쪽 버튼으로 클릭하고 'Manage NuGet Packages ...'를 선택합니다.
  2. "찾아보기" 탭을 선택하고 "BarCode.Android"를 검색합니다.
  3. "BarCode.Android" 패키지를 선택하고 "설치"를 클릭합니다.

다른 플랫폼과의 문제를 방지하기 위해 csproj 파일을 수정하여 Android 플랫폼을 대상으로 할 때만 패키지를 포함하도록 합니다. 이를 수행하려면:

  1. 프로젝트의 *.csproj 파일을 우클릭하고 "Edit Project File"을 선택합니다.

  2. 새로운 ItemGroup 요소를 만듭니다:

    <ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
        <PackageReference Include="BarCode.Android" Version="2025.3.4" />
    </ItemGroup>
    XML
  3. "BarCode.Android" PackageReference를 방금 생성한 ItemGroup으로 이동합니다.

위 단계는 iOS와 같은 플랫폼에서 "BarCode.Android" 패키지 사용을 방지합니다. 이 용도로 BarCode.iOS를 대신 설치하십시오.

Android 번들 구성

Android가 작동하려면 Android 번들 설정을 구성해야 합니다. .csproj 파일에 Android 번들의 구성 파일을 지정하는 다음 항목을 추가합니다:

<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
XML

프로젝트의 루트 디렉토리에 "BundleConfig.json"이라는 파일 생성. 이 JSON 파일에는 라이브러리 기능에 필수적인 Android 번들에 필요한 설정이 포함되어 있습니다.

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

이 구성은 네이티브 라이브러리가 압축되지 않도록 보장하며, 이는 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

바코드 읽기 및 쓰기

위의 MainPage.xaml 코드에서 우리는 체크박스가 생성된 바코드와 QR 코드가 PDF 형식으로 되어야 하는지 여부를 결정하는 것을 볼 수 있습니다. 다음으로, 라이센스 키를 설정합니다. 이 단계에서는 체험판 또는 유료 라이센스 키를 사용해 주세요.

코드는 barcodeInput 변수에서 값을 확인하고 검색한 후, CreateBarcode 메소드를 사용하여 바코드를 생성합니다. 마지막으로, Android와 iOS 모두에 적절하게 파일을 저장하는 SaveToDownloadsAsync 메소드를 호출합니다.

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);
            }
        }
    }
}

프로젝트 실행

이것은 프로젝트를 실행하고 바코드 기능을 사용하는 방법을 보여줄 것입니다.

.NET MAUI 앱 프로젝트 실행

.NET MAUI App 프로젝트 다운로드

이 가이드의 전체 코드를 다운로드할 수 있습니다. 이는 Visual Studio에서 .NET MAUI App 프로젝트로 열 수 있는 압축된 파일 형태로 제공됩니다.

여기를 클릭하여 프로젝트를 다운로드하세요.

자주 묻는 질문

.NET MAUI는 무엇이며, Android에서 바코드 스캔과 어떤 관련이 있나요?

.NET MAUI, 즉 Multi-platform App UI는 Xamarin.Forms의 후속작으로, 개발자가 크로스 플랫폼 애플리케이션을 빌드할 수 있도록 합니다. BarCode.Android 패키지는 .NET MAUI와 통합되어 Android 기기에서 바코드 읽기와 쓰기를 가능하게 합니다.

BarCode.Android 라이브러리를 .NET MAUI 프로젝트에 어떻게 추가하나요?

Visual Studio에서 NuGet을 사용하여 BarCode.Android 라이브러리를 추가할 수 있습니다. 'Dependencies'를 오른쪽 클릭하고 'Manage NuGet Packages'를 선택한 후 'BarCode.Android'를 검색하고 'Install'을 클릭하세요.

BarCode.Android 패키지를 Android 외의 플랫폼에서도 사용할 수 있나요?

BarCode.Android 패키지는 Android에 특화되어 있습니다. iOS에서는 BarCode.iOS 패키지를 대신 사용해야 합니다.

BarCode.Android 라이브러리를 Android에만 포함시키도록 프로젝트를 어떻게 설정할 수 있나요?

TargetFramework 조건을 사용하여 Android를 대상으로 할 때만 BarCode.Android 패키지를 포함하는 조건부 ItemGroup을 .csproj 파일에 추가해야 합니다.

Android에서 BarCode.Android 라이브러리를 사용하기 위한 특정 구성 파일이 필요한가요?

예, .csproj 파일에 Android 번들의 구성 파일을 지정해야 하며, 보통 'BundleConfig.json'이라는 이름으로 기본 라이브러리가 압축 해제되도록 지정합니다.

MAUI 애플리케이션에서 IronBarcode를 사용하여 바코드를 생성하고 저장하려면 어떻게 해야 하나요?

BarcodeWriter 클래스를 사용하여 텍스트 입력에서 바코드를 생성하고, 형식(PDF 또는 PNG)을 결정한 다음 Android 및 iOS에서 SaveToDownloadsAsync와 같은 메소드를 사용하여 저장할 수 있습니다.

IronBarcode에서 생성된 바코드를 저장할 수 있는 파일 형식은 무엇인가요?

IronBarcode는 사용자가 애플리케이션에서 선택한 대로 바코드를 PDF 또는 PNG 형식으로 저장할 수 있습니다.

.NET MAUI Android 앱에서 IronBarcode는 QR 코드 처리에 어떻게 도움이 되나요?

IronBarcode는 QRCodeWriter 클래스를 통해 QR 코드 생성 및 읽기를 용이하게 하며, 입력 텍스트에서 QR 코드를 생성하고 파일에서 바코드 데이터를 읽는 기능을 제공합니다.

.NET MAUI에서 IronBarcode를 시작하기 위한 샘플 프로젝트가 있나요?

네, 가이드에 제공된 예제 코드와 함께 완전한 .NET MAUI 앱 프로젝트를 다운로드하여 빠르게 시작할 수 있습니다.

IronBarcode가 파일에서 바코드 데이터를 읽는 데 제공하는 기능은 무엇인가요?

IronBarcode는 BarcodeReader 클래스를 사용하여 이미지 및 PDF 파일에서 바코드를 읽을 수 있으며, 결과는 애플리케이션에서 형식화되어 표시됩니다.

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

더 읽기

시작할 준비 되셨나요?

NuGet 다운로드 수 2,564,559버전:2026.11방금 출시