Przejdź do treści stopki
KORZYSTANIE Z IRONBARCODE

Jak korzystać z SDK skanera dokumentów w aplikacji .NET MAUI

Wraz z rozwojem technologii mobilnych aplikacje do skanowania dokumentów, takie jak Scanbot SDK i Native SDK, stały się niezbędnymi narzędziami zarówno dla osób prywatnych, jak i firm. W tym samouczku omówimy, jak stworzyć aplikację do skanowania dokumentów przy użyciu najnowszej wersji .NET Multi-platform App UI (MAUI) oraz biblioteki IronOCR, potężnej biblioteki OCR (Optical Character Recognition) dla platformy .NET. .NET MAUI upraszcza tworzenie wielopłatformowych aplikacji mobilnych, zapewniając płynne wdrażanie na urządzeniach takich jak Android. Po przeczytaniu tego przewodnika będziesz w stanie stworzyć własną aplikację SDK do skanowania dokumentów, która z łatwością wyodrębni tekst z obrazów i zeskanowanych plików.

Jak korzystać z zestawu SDK skanera dokumentów w aplikacji .NET MAUI

  1. Zainstaluj bibliotekę IronOCR C#, aby korzystać z zestawu SDK skanera dokumentów.
  2. Zaprojektuj formularz .NET MAUI z niezbędnymi kontrolkami.
  3. Zrób zdjęcie za pomocą metody MediaPicker.CapturePhotoAsync.
  4. Przekonwertuj zrobione zdjęcie na strumień.
  5. Pass the stream to the OcrInput LoadImage method.
  6. Perform OCR using the IronTesseract Read method.
  7. Display the document text using the OcrResult Text property.

IronOCR - The C# OCR Library

IronOCR is a cutting-edge Optical Character Recognition (OCR) software developed by Iron Software, LLC, designed to accurately and efficiently convert images and scanned documents into editable text. OCR technology has revolutionized how businesses handle document processing, making it easier to extract valuable information from various sources such as scanned documents, PDFs, and images.

IronOCR stands out among OCR solutions due to its advanced features, robust performance, and ease of integration. Whether you're a developer looking to incorporate OCR features into your applications or a business seeking to streamline document management processes, IronOCR offers a comprehensive solution.

Najważniejsze cechy IronOCR

  1. High Accuracy: IronOCR employs state-of-the-art algorithms and machine learning techniques to achieve exceptional accuracy in text recognition. It can accurately extract text from complex documents, including images with low resolution or poor-quality scans.
  2. Multi-Language Support: IronOCR supports text recognition in over 125 languages, making it suitable for businesses operating in diverse linguistic environments.
  3. Image Preprocessing: IronOCR provides various image preprocessing capabilities, such as noise reduction, contrast adjustment, and deskewing, to enhance accuracy. These techniques improve OCR results, especially with distorted or imperfect images.
  4. Support for Various File Formats: IronOCR supports a wide range of file formats, including TIFF, JPEG, PNG, and PDF, ensuring compatibility with different document sources.
  5. Customization Options: Developers can customize IronOCR's behavior to meet specific requirements, offering flexibility in recognition parameters and workflow integration.
  6. Fast and Scałable: Optimized for performance, IronOCR rapidly extracts text from large volumes of documents. Its scałable architecture ensures seamless operation, regardless of document volume.
  7. Integration with .NET Applications: IronOCR integrates seamlessly with .NET applications, providing an easy-to-use API for incorporating OCR functionality. This simplifies development and speeds time-to-market for OCR-enabled applications.
  8. Document Classification and Data Extraction: Beyond basic text recognition, IronOCR offers advanced features for document classification and data extraction, identifying specific data fields like names, addresses, or invoice numbers.

Wymagania wstępne

  • Basic knowledge of C# programming.
  • Visual Studio 2022 installed with the .NET MAUI workload.
  • IronOCR package library installed via NuGet Package Manager.

1. Setting Up Your .NET MAUI Project

  • Open Visual Studio 2022 and create a new .NET MAUI App project.

How to Use a Document Scanner SDK in a .NET MAUI Application: Figure 1 - .NET MAUI App Project

  • Choose a suitable project name and configure your project settings.

How to Use a Document Scanner SDK in a .NET MAUI Application: Figure 2 - Project Configuration

  • Ensure you have the necessary Android and iOS SDKs installed for target-platform device development.

2. Installing IronOCR Library

  • Right-click on your Solution in Visual Studio.
    • Select "Manage NuGet Packages for Solution" and in the Browse tab, search for "IronOCR".

How to Use a Document Scanner SDK in a .NET MAUI Application: Figure 3 - IronOCR NuGet Package

  • Install the IronOCR library to your project.

3. Designing the UI

Let's start by designing the layout of our MainPage.xaml. We'll create a simple layout with an image control to display the captured photo, a Capture button to take photos, and a Label to display the extracted text.

Here's the XAML code for MainPage.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"
             xmlns:d="http://schemas.microsoft.com/dotnet/2021/maui/design"
             x:Class="DocumentScanner.MainPage">
    <ScrollView>
        <VerticalStackLayout Padding="30,0" Spacing="25">
            <Image Source="dotnet_bot.png"
                   HeightRequest="185"
                   Aspect="AspectFit"
                   SemanticProperties.Description="dot net bot in a race car number eight" />
            <Label Text="Welcome to .NET MAUI Document Scanner SDK"
                   style="{StaticResource Headline}"
                   SemanticProperties.HeadingLevel="Level1" />
            <Label Text="Using IronOCR"
                   style="{StaticResource SubHeadline}"
                   SemanticProperties.HeadingLevel="Level2"
                   SemanticProperties.Description="Welcome to .NET MAUI Document Scanner SDK" />

            <Image x:Name="cameraPreview" />

            <Button Text="Capture" Clicked="OnCaptureClicked" />

            <Label x:Name="textLabel" Text="Recognized Text:"/>
        </VerticalStackLayout>
    </ScrollView>
</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"
             xmlns:d="http://schemas.microsoft.com/dotnet/2021/maui/design"
             x:Class="DocumentScanner.MainPage">
    <ScrollView>
        <VerticalStackLayout Padding="30,0" Spacing="25">
            <Image Source="dotnet_bot.png"
                   HeightRequest="185"
                   Aspect="AspectFit"
                   SemanticProperties.Description="dot net bot in a race car number eight" />
            <Label Text="Welcome to .NET MAUI Document Scanner SDK"
                   style="{StaticResource Headline}"
                   SemanticProperties.HeadingLevel="Level1" />
            <Label Text="Using IronOCR"
                   style="{StaticResource SubHeadline}"
                   SemanticProperties.HeadingLevel="Level2"
                   SemanticProperties.Description="Welcome to .NET MAUI Document Scanner SDK" />

            <Image x:Name="cameraPreview" />

            <Button Text="Capture" Clicked="OnCaptureClicked" />

            <Label x:Name="textLabel" Text="Recognized Text:"/>
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
XML

In this layout:

  • We use a VerticalStackLayout to stack the controls vertically.
  • The Image control named cameraPreview is used to display the captured photo.
  • The Button control triggers the OnCaptureClicked event handler when clicked.
  • The Label control named textLabel is used to display the extracted text.

Wynik

How to Use a Document Scanner SDK in a .NET MAUI Application: Figure 4 - MainPage.xaml Output

4. Implementing Document Scanning Functionality

To integrate text extraction functionality into our .NET MAUI Document Scanning app, we will follow these steps:

  1. Utilize the Camera API: Leverage the camera API provided by .NET MAUI to capture image files directly within your application.
  2. Pass Image to IronOCR: Once an image is captured, pass it to IronOCR for text extraction, utilizing its robust functionality.
  3. Display Extracted Text: Display the extracted text in the designated area on your app's user interface for user viewing.

Here's the corresponding code snippet implementing these steps:

using IronOcr;

namespace DocumentScanner
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private async void OnCaptureClicked(object sender, EventArgs e)
        {
            License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
            try
            {
                // Request camera permissions
                var status = await Permissions.RequestAsync<Permissions.Camera>();
                if (status == PermissionStatus.Granted)
                {
                    // Take photo
                    var photo = await MediaPicker.CapturePhotoAsync();
                    if (photo != null)
                    {
                        // Display captured photo in Image
                        cameraPreview.Source = ImageSource.FromStream(() => photo.OpenReadAsync().Result);
                        using (var stream = await photo.OpenReadAsync())
                        {
                            // Use a stream from the captured photo for OCR
                            var ocr = new IronTesseract();
                            using var ocrInput = new OcrInput();
                            ocrInput.LoadImage(stream);
                            var ocrResult = ocr.Read(ocrInput);
                            if (string.IsNullOrEmpty(ocrResult.Text))
                            {
                                await DisplayAlert("Error", "No Text Detected!", "OK");
                            }
                            else
                            {
                                await DisplayAlert("Text Detected!", ocrResult.Text, "OK");
                                // Display extracted text
                                textLabel.Text = ocrResult.Text;
                            }
                        }
                    }
                }
                else
                {
                    // Camera permission denied
                    await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exception
                await DisplayAlert("Error", ex.Message, "OK");
            }
        }
    }
}
using IronOcr;

namespace DocumentScanner
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private async void OnCaptureClicked(object sender, EventArgs e)
        {
            License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
            try
            {
                // Request camera permissions
                var status = await Permissions.RequestAsync<Permissions.Camera>();
                if (status == PermissionStatus.Granted)
                {
                    // Take photo
                    var photo = await MediaPicker.CapturePhotoAsync();
                    if (photo != null)
                    {
                        // Display captured photo in Image
                        cameraPreview.Source = ImageSource.FromStream(() => photo.OpenReadAsync().Result);
                        using (var stream = await photo.OpenReadAsync())
                        {
                            // Use a stream from the captured photo for OCR
                            var ocr = new IronTesseract();
                            using var ocrInput = new OcrInput();
                            ocrInput.LoadImage(stream);
                            var ocrResult = ocr.Read(ocrInput);
                            if (string.IsNullOrEmpty(ocrResult.Text))
                            {
                                await DisplayAlert("Error", "No Text Detected!", "OK");
                            }
                            else
                            {
                                await DisplayAlert("Text Detected!", ocrResult.Text, "OK");
                                // Display extracted text
                                textLabel.Text = ocrResult.Text;
                            }
                        }
                    }
                }
                else
                {
                    // Camera permission denied
                    await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exception
                await DisplayAlert("Error", ex.Message, "OK");
            }
        }
    }
}
Imports IronOcr

Namespace DocumentScanner
	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Async Sub OnCaptureClicked(ByVal sender As Object, ByVal e As EventArgs)
			License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
			Try
				' Request camera permissions
				Dim status = Await Permissions.RequestAsync(Of Permissions.Camera)()
				If status = PermissionStatus.Granted Then
					' Take photo
					Dim photo = Await MediaPicker.CapturePhotoAsync()
					If photo IsNot Nothing Then
						' Display captured photo in Image
						cameraPreview.Source = ImageSource.FromStream(Function() photo.OpenReadAsync().Result)
						Using stream = Await photo.OpenReadAsync()
							' Use a stream from the captured photo for OCR
							Dim ocr = New IronTesseract()
							Dim ocrInput As New OcrInput()
							ocrInput.LoadImage(stream)
							Dim ocrResult = ocr.Read(ocrInput)
							If String.IsNullOrEmpty(ocrResult.Text) Then
								Await DisplayAlert("Error", "No Text Detected!", "OK")
							Else
								Await DisplayAlert("Text Detected!", ocrResult.Text, "OK")
								' Display extracted text
								textLabel.Text = ocrResult.Text
							End If
						End Using
					End If
				Else
					' Camera permission denied
					Await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK")
				End If
			Catch ex As Exception
				' Handle exception
				Await DisplayAlert("Error", ex.Message, "OK")
			End Try
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Wyjaśnienie kodu

Let's break down the code step by step:

  • In the MainPage.xaml.cs file, the OnCaptureClicked method is defined to handle the Capture button's click event.
  • The IronOCR license key is set up, necessary to use the IronOCR library. Replace "YOUR-LICENSE-KEY-HERE" with your actual license key.
  • Camera permissions are requested using Permissions.RequestAsync() to ensure that the app can access the device's camera.
  • MediaPicker.CapturePhotoAsync() is called to take a photo using the camera. If successful, the photo is displayed in the cameraPreview Image control.
  • A stream from the captured photo is opened and used as input for IronOCR, creating an IronTesseract instance, loading the image stream into an OcrInput object, and calling the Read method to perform OCR.
  • The extracted text is displayed in the textLabel control if successful. If no text is detected, an error message is shown using DisplayAlert.

For further exploration of IronOCR and additional code examples, visit this code examples page.

5. Testing the Document Scanner App

  • Run the app on various platforms (Android, iOS, and Windows) to ensure cross-platform compatibility.
  • Test different scenarios, such as scanning documents with various fonts, sizes, and orientations.
  • Verify that the extracted text is accurate and displayed correctly on the UI.

Wynik - Scanned Document without Text

How to Use a Document Scanner SDK in a .NET MAUI Application: Figure 5 - Scanned PDF Creation Output

Wynik - Scanned Document with Text

How to Use a Document Scanner SDK in a .NET MAUI Application: Figure 6 - Scanned Documentation

Wnioski

By following this tutorial, you've learned how to use the IronOCR document scanner SDK within .NET MAUI. Document scanning apps have numerous practical applications, from digitizing paper documents to extracting stored information from receipts and invoices. Using the powerful capabilities of IronOCR and the flexibility of .NET MAUI, you can build feature-rich document scanner apps that cater to various use cases. Experiment with different functionalities, explore additional libraries, and continue honing your skills to create even more impressive apps.

For more detailed information on IronOCR capabilities, please visit this documentation page.

IronOCR provides a free trial to test its complete functionality in commercial mode. Its perpetual lite license starts from $799. Download the library from the download page and give it a try.

Często Zadawane Pytania

Jak stworzyć aplikację do skanowania dokumentów przy użyciu .NET MAUI?

Możesz stworzyć aplikację do skanowania dokumentów przy użyciu .NET MAUI, wykorzystując IronOCR do optycznego rozpoznawania znaków. Zacznij od zainstalowania IronOCR za pomocą menedżera pakietów NuGet w Visual Studio, a następnie użyj .NET MAUI do zaprojektowania interfejsu użytkownika aplikacji i zaimplementuj funkcję skanowania za pomocą metody Read biblioteki IronTesseract.

Jakie są zalety korzystania z IronOCR w aplikacji do skanowania dokumentów?

IronOCR zapewnia wysoką dokładność rozpoznawania tekstu, obsługę wielu języków oraz kompatybilność z różnymi formatami plików. Oferuje również przetwarzanie wstępne obrazów, wysoką wydajność oraz płynną integrację z aplikacjami .NET, co czyni go solidnym wyborem dla aplikacji do skanowania dokumentów.

Jak zainstalować IronOCR w projekcie .NET MAUI?

Aby zainstalować IronOCR w projekcie .NET MAUI, otwórz Visual Studio i użyj menedżera pakietów NuGet, aby wyszukać „IronOCR”. Dodaj pakiet do swojego projektu, aby rozpocząć korzystanie z jego funkcji OCR.

Jakie kroki obejmuje przechwytywanie i przetwarzanie obrazów w aplikacji do skanowania dokumentów?

Proces ten obejmuje użycie MediaPicker do przechwytywania obrazów, konwersję ich do formatu strumieniowego, a następnie użycie IronTesseract z IronOCR do wyodrębnienia tekstu. Wyodrębniony tekst może być wyświetlany w interfejsie użytkownika aplikacji.

Jakie formaty plików są obsługiwane przez IronOCR do przetwarzania OCR?

IronOCR obsługuje szeroki zakres formatów plików, w tym TIFF, JPEG, PNG i PDF, co zapewnia wszechstronne możliwości skanowania dokumentów i wyodrębniania tekstu.

Czy IronOCR obsługuje OCR w wielu językach?

Tak, IronOCR obsługuje OCR w ponad 125 językach, dzięki czemu nadaje się do zastosowań wymagających rozpoznawania tekstu w różnych kontekstach językowych.

W jaki sposób .NET MAUI ułatwia tworzenie aplikacji wieloplatformowych?

.NET MAUI umożliwia programistom tworzenie wieloplatformowych aplikacji mobilnych przy użyciu jednego kodu źródłowego, co pozwala na płynne wdrażanie na urządzeniach z systemami Android, iOS i Windows.

Jakie są wymagania wstępne dotyczące tworzenia aplikacji do skanowania dokumentów przy użyciu .NET MAUI?

Wymagania wstępne obejmują podstawową znajomość programowania w języku C#, Visual Studio 2022 z środowiskiem .NET MAUI oraz bibliotekę IronOCR zainstalowaną z NuGet.

Jak mogę sprawdzić kompatybilność mojej aplikacji do skanowania dokumentów na różnych platformach?

Możesz przetestować swoją aplikację do skanowania dokumentów na różnych platformach, wdrażając ją na urządzeniach z systemami Android, iOS i Windows, aby zapewnić funkcjonalność i dokładność wyodrębniania tekstu, wykorzystując możliwości wieloplatformowe .NET MAUI.

Jordi Bardia
Inżynier oprogramowania
Jordi jest najbardziej biegły w Pythonie, C# i C++. Kiedy nie wykorzystuje swoich umiejętności w Iron Software, programuje gry. Dzieląc odpowiedzialność za testowanie produktów, rozwój produktów i badania, Jordi wnosi ogromną wartość do ciągłej poprawy produktów. Różnorodne doświadczenia ...
Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie