Pruebas en un entorno real
Pruebe en producción sin marcas de agua.
Funciona donde lo necesites.
Con el auge de la tecnología móvil, las aplicaciones de escaneo de documentos como Scanbot SDK y Native SDK se han convertido en herramientas indispensables o en expertos en soluciones tanto para particulares como para empresas. En este tutorial, vamos a explorar cómo crear una aplicación de escáner de documentos utilizando la última versión de .NET Multi-plataforma App UI (MAUI) y IronOCR, un potente OCR (Reconocimiento óptico de caracteres) para .NET. .NET MAUI simplifica la creación de aplicaciones móviles multiplataforma como Android, garantizando una implementación perfecta en el dispositivo del usuario final. Al final de esta guía, podrá desarrollar su propia aplicación SDK de escáner de documentos que puede extraer texto de imágenes y archivos escaneados con facilidad.
IronOCR es un avanzado sistema de reconocimiento óptico de caracteres (OCR) desarrollado por Iron Software, LLC, diseñado para convertir con precisión y eficacia imágenes y documentos escaneados en texto editable. La tecnología OCR ha revolucionado la forma en que las empresas gestionan el procesamiento de documentos, facilitando la extracción de información valiosa de diversas fuentes, como documentos escaneados, PDF e imágenes.
IronOCR destaca entre las soluciones de OCR por sus funciones avanzadas, su sólido rendimiento y su facilidad de integración. Tanto si es un desarrollador que desea incorporar funciones de OCR a sus aplicaciones como si es una empresa que busca agilizar los procesos de gestión de documentos generados por datos, IronOCR le ofrece una solución integral.
Estas son algunas de las principales características de IronOCR:
Abre Visual Studio 2022 y crea un nuevo proyecto .NET MAUI App.
Elija un nombre de proyecto adecuado y configure los ajustes del proyecto.
Haga clic con el botón derecho en su solución en Visual Studio.
Empecemos diseñando el layout de nuestra MainPage.xaml. Crearemos un diseño sencillo con un control de imagen para mostrar la foto capturada, un botón Capturar para tomar fotos y una Etiqueta para mostrar el texto extraído.
Aquí está el código XAML para 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" />
<!-- Camera preview -->
<Image x:Name="cameraPreview" />
<!-- Capture button -->
<Button Text="Capture" Clicked="OnCaptureClicked" />
<!-- Text display area -->
<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" />
<!-- Camera preview -->
<Image x:Name="cameraPreview" />
<!-- Capture button -->
<Button Text="Capture" Clicked="OnCaptureClicked" />
<!-- Text display area -->
<Label x:Name="textLabel"
Text="Recognized Text:"/>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<?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" /> <!-- Camera preview -- > <Image x:Name="cameraPreview" /> <!-- Capture button -- > <Button Text="Capture" Clicked="OnCaptureClicked" /> <!-- Text display area -- > <Label x:Name="textLabel" Text="Recognized Text:"/> </VerticalStackLayout> </ScrollView> </ContentPage>
En esta disposición:
Para integrar la funcionalidad de extracción de texto en nuestra aplicación .NET MAUI Document Scanning, seguiremos estos pasos:
Mostrar el texto extraído: Por último, muestre el texto extraído en el área designada de la interfaz de usuario de su aplicación. Esto permite a los usuarios ver fácilmente el texto extraído de la imagen capturada o del código QR.
A continuación se muestra el fragmento de código correspondiente que implementa estos pasos:
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
{
// Solicitar permisos de cámara
var status = await Permissions.RequestAsync<Permissions.Camera>();
if (status == PermissionStatus.Granted)
{
// Tomar foto
var photo = await MediaPicker.CapturePhotoAsync();
if (photo != null)
{
// Mostrar foto capturada en Imagen
cameraPreview.Source = ImageSource.FromStream(() => photo.OpenReadAsync().Result);
using (var stream = await photo.OpenReadAsync())
{
// Utilizar una secuencia de la foto capturada para el 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");
// Mostrar el texto extraído
textLabel.Text = ocrResult.Text;
}
}
}
}
else
{
// Permiso de cámara denegado
await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK");
}
}
catch (Exception ex)
{
// Manejar excepción
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
{
// Solicitar permisos de cámara
var status = await Permissions.RequestAsync<Permissions.Camera>();
if (status == PermissionStatus.Granted)
{
// Tomar foto
var photo = await MediaPicker.CapturePhotoAsync();
if (photo != null)
{
// Mostrar foto capturada en Imagen
cameraPreview.Source = ImageSource.FromStream(() => photo.OpenReadAsync().Result);
using (var stream = await photo.OpenReadAsync())
{
// Utilizar una secuencia de la foto capturada para el 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");
// Mostrar el texto extraído
textLabel.Text = ocrResult.Text;
}
}
}
}
else
{
// Permiso de cámara denegado
await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK");
}
}
catch (Exception ex)
{
// Manejar excepción
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
' Solicitar permisos de cámara
Dim status = Await Permissions.RequestAsync(Of Permissions.Camera)()
If status = PermissionStatus.Granted Then
' Tomar foto
Dim photo = Await MediaPicker.CapturePhotoAsync()
If photo IsNot Nothing Then
' Mostrar foto capturada en Imagen
cameraPreview.Source = ImageSource.FromStream(Function() photo.OpenReadAsync().Result)
Using stream = Await photo.OpenReadAsync()
' Utilizar una secuencia de la foto capturada para el 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")
' Mostrar el texto extraído
textLabel.Text = ocrResult.Text
End If
End Using
End If
Else
' Permiso de cámara denegado
Await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK")
End If
Catch ex As Exception
' Manejar excepción
Await DisplayAlert("Error", ex.Message, "OK")
End Try
End Sub
End Class
End Namespace
Desglosemos el código paso a paso:
Si el texto se extrae correctamente, lo mostramos en un control Label llamado textLabel. Si no se detecta ningún texto, mostramos un mensaje de error utilizando DisplayAlert.
Para un uso más robusto de IronOCR y detalles del código, visite este enlace ejemplos de código página.
Siguiendo este tutorial, habrás aprendido a utilizar el SDK de escáner de documentos IronOCR en .NET MAUI. Las aplicaciones de escaneado de documentos tienen numerosas aplicaciones prácticas, desde la digitalización de documentos en papel hasta la extracción de información almacenada en recibos y facturas. Con las potentes funciones de IronOCR y la flexibilidad de .NET MAUI, puede crear aplicaciones de escáner de documentos ricas en funciones que se adapten a diversos casos de uso. Experimenta con distintas funcionalidades, explora bibliotecas adicionales y sigue perfeccionando tus habilidades para crear aplicaciones aún más impresionantes.
Para obtener información más detallada sobre las capacidades de IronOCR, visite este enlace documentación página.
IronOCR proporciona un **Prueba gratuita para probar su funcionalidad completa en modo comercial. Su luz perpetua licencia a partir de 749 Descargue la biblioteca desde descargar **y pruébalo.
9 productos API .NET para sus documentos de oficina