Cómo realizar OCR de documentos en AWS Lambda

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to Cómo realizar OCR de documentos en AWS Lambda

Este artículo ofrece una guía paso a paso para configurar una función de AWS Lambda usando IronOCR. Al seguir esta guía, aprenderás a configurar IronOCR y leer documentos almacenados en un bucket de S3 de manera eficiente.

Instalación

Este artículo utilizará un bucket S3, por lo que se requiere el paquete AWSSDK.S3.

Si estás utilizando IronOCR ZIP, es esencial configurar la carpeta temporal.

// Set temporary folder path and log file path for IronOCR.
var awsTmpPath = @"/tmp/";
IronOcr.Installation.InstallationPath = awsTmpPath;
IronOcr.Installation.LogFilePath = awsTmpPath;
// Set temporary folder path and log file path for IronOCR.
var awsTmpPath = @"/tmp/";
IronOcr.Installation.InstallationPath = awsTmpPath;
IronOcr.Installation.LogFilePath = awsTmpPath;
' Set temporary folder path and log file path for IronOCR.
Dim awsTmpPath = "/tmp/"
IronOcr.Installation.InstallationPath = awsTmpPath
IronOcr.Installation.LogFilePath = awsTmpPath
$vbLabelText   $csharpLabel

Comience a usar IronOCR en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer

Crear un proyecto de AWS Lambda

Con Visual Studio, crear un AWS Lambda en contenedor es un proceso sencillo:

  • Instalar el AWS Toolkit para Visual Studio.
  • Seleccionar un 'Proyecto AWS Lambda (.NET Core - C#)'.
  • Seleccionar un modelo '.NET 8 (Imagen de Contenedor)', luego seleccionar 'Finalizar'.

Seleccionar imagen de contenedor

Agregar dependencias de paquetes

Usar la biblioteca IronOCR en .NET 8 no requiere dependencias adicionales para su uso en AWS Lambda. Modificar el Dockerfile del proyecto con lo siguiente:

FROM public.ecr.aws/lambda/dotnet:8

# Update all installed packages
RUN dnf update -y

WORKDIR /var/task

# Copy build artifacts from the host machine into the Docker image
COPY "bin/Release/lambda-publish" .

Modificar el código del FunctionHandler

Este ejemplo recupera una imagen de un bucket de S3, la procesa y guarda un PDF con capacidad de búsqueda de nuevo en el mismo bucket. Configurar la carpeta temporal es esencial al usar IronOCR ZIP, ya que la biblioteca requiere permisos de escritura para copiar la carpeta de tiempo de ejecución desde los DLLs.

using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronOcr;
using System;
using System.IO;
using System.Threading.Tasks;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace IronOcrZipAwsLambda
{
    public class Function
    {
        // Initialize the S3 client with a specific region endpoint
        private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

        /// <summary>
        /// Function handler to process OCR on the PDF stored in S3.
        /// </summary>
        /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
        public async Task FunctionHandler(ILambdaContext context)
        {
            // Set up necessary paths for IronOCR
            var awsTmpPath = @"/tmp/";
            IronOcr.Installation.InstallationPath = awsTmpPath;
            IronOcr.Installation.LogFilePath = awsTmpPath;

            // Set license key for IronOCR
            IronOcr.License.LicenseKey = "IRONOCR-MYLICENSE-KEY-1EF01";

            string bucketName = "deploymenttestbucket"; // Your bucket name
            string pdfName = "sample";
            string objectKey = $"IronPdfZip/{pdfName}.pdf";
            string objectKeyForSearchablePdf = $"IronPdfZip/{pdfName}-SearchablePdf.pdf";

            try
            {
                // Retrieve the PDF file from S3
                var pdfData = await GetPdfFromS3Async(bucketName, objectKey);

                // Initialize IronTesseract for OCR processing
                IronTesseract ironTesseract = new IronTesseract();
                OcrInput ocrInput = new OcrInput();
                ocrInput.LoadPdf(pdfData);
                OcrResult result = ironTesseract.Read(ocrInput);

                // Log the OCR result
                context.Logger.LogLine($"OCR result: {result.Text}");

                // Upload the searchable PDF to S3
                await UploadPdfToS3Async(bucketName, objectKeyForSearchablePdf, result.SaveAsSearchablePdfBytes());
                context.Logger.LogLine($"PDF uploaded successfully to {bucketName}/{objectKeyForSearchablePdf}");
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
            }
        }

        /// <summary>
        /// Retrieves a PDF from S3 and returns it as a byte array.
        /// </summary>
        private async Task<byte[]> GetPdfFromS3Async(string bucketName, string objectKey)
        {
            var request = new GetObjectRequest
            {
                BucketName = bucketName,
                Key = objectKey
            };

            using (var response = await _s3Client.GetObjectAsync(request))
            using (var memoryStream = new MemoryStream())
            {
                await response.ResponseStream.CopyToAsync(memoryStream);
                return memoryStream.ToArray();
            }
        }

        /// <summary>
        /// Uploads the generated searchable PDF back to S3.
        /// </summary>
        private async Task UploadPdfToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
        {
            using (var memoryStream = new MemoryStream(pdfBytes))
            {
                var request = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = objectKey,
                    InputStream = memoryStream,
                    ContentType = "application/pdf"
                };

                await _s3Client.PutObjectAsync(request);
            }
        }
    }
}
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronOcr;
using System;
using System.IO;
using System.Threading.Tasks;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace IronOcrZipAwsLambda
{
    public class Function
    {
        // Initialize the S3 client with a specific region endpoint
        private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

        /// <summary>
        /// Function handler to process OCR on the PDF stored in S3.
        /// </summary>
        /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
        public async Task FunctionHandler(ILambdaContext context)
        {
            // Set up necessary paths for IronOCR
            var awsTmpPath = @"/tmp/";
            IronOcr.Installation.InstallationPath = awsTmpPath;
            IronOcr.Installation.LogFilePath = awsTmpPath;

            // Set license key for IronOCR
            IronOcr.License.LicenseKey = "IRONOCR-MYLICENSE-KEY-1EF01";

            string bucketName = "deploymenttestbucket"; // Your bucket name
            string pdfName = "sample";
            string objectKey = $"IronPdfZip/{pdfName}.pdf";
            string objectKeyForSearchablePdf = $"IronPdfZip/{pdfName}-SearchablePdf.pdf";

            try
            {
                // Retrieve the PDF file from S3
                var pdfData = await GetPdfFromS3Async(bucketName, objectKey);

                // Initialize IronTesseract for OCR processing
                IronTesseract ironTesseract = new IronTesseract();
                OcrInput ocrInput = new OcrInput();
                ocrInput.LoadPdf(pdfData);
                OcrResult result = ironTesseract.Read(ocrInput);

                // Log the OCR result
                context.Logger.LogLine($"OCR result: {result.Text}");

                // Upload the searchable PDF to S3
                await UploadPdfToS3Async(bucketName, objectKeyForSearchablePdf, result.SaveAsSearchablePdfBytes());
                context.Logger.LogLine($"PDF uploaded successfully to {bucketName}/{objectKeyForSearchablePdf}");
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
            }
        }

        /// <summary>
        /// Retrieves a PDF from S3 and returns it as a byte array.
        /// </summary>
        private async Task<byte[]> GetPdfFromS3Async(string bucketName, string objectKey)
        {
            var request = new GetObjectRequest
            {
                BucketName = bucketName,
                Key = objectKey
            };

            using (var response = await _s3Client.GetObjectAsync(request))
            using (var memoryStream = new MemoryStream())
            {
                await response.ResponseStream.CopyToAsync(memoryStream);
                return memoryStream.ToArray();
            }
        }

        /// <summary>
        /// Uploads the generated searchable PDF back to S3.
        /// </summary>
        private async Task UploadPdfToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
        {
            using (var memoryStream = new MemoryStream(pdfBytes))
            {
                var request = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = objectKey,
                    InputStream = memoryStream,
                    ContentType = "application/pdf"
                };

                await _s3Client.PutObjectAsync(request);
            }
        }
    }
}
Imports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronOcr
Imports System
Imports System.IO
Imports System.Threading.Tasks

' Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
<Assembly: LambdaSerializer(GetType(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))>

Namespace IronOcrZipAwsLambda
	Public Class [Function]
		' Initialize the S3 client with a specific region endpoint
		Private Shared ReadOnly _s3Client As IAmazonS3 = New AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1)

		''' <summary>
		''' Function handler to process OCR on the PDF stored in S3.
		''' </summary>
		''' <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
		Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
			' Set up necessary paths for IronOCR
			Dim awsTmpPath = "/tmp/"
			IronOcr.Installation.InstallationPath = awsTmpPath
			IronOcr.Installation.LogFilePath = awsTmpPath

			' Set license key for IronOCR
			IronOcr.License.LicenseKey = "IRONOCR-MYLICENSE-KEY-1EF01"

			Dim bucketName As String = "deploymenttestbucket" ' Your bucket name
			Dim pdfName As String = "sample"
			Dim objectKey As String = $"IronPdfZip/{pdfName}.pdf"
			Dim objectKeyForSearchablePdf As String = $"IronPdfZip/{pdfName}-SearchablePdf.pdf"

			Try
				' Retrieve the PDF file from S3
				Dim pdfData = Await GetPdfFromS3Async(bucketName, objectKey)

				' Initialize IronTesseract for OCR processing
				Dim ironTesseract As New IronTesseract()
				Dim ocrInput As New OcrInput()
				ocrInput.LoadPdf(pdfData)
				Dim result As OcrResult = ironTesseract.Read(ocrInput)

				' Log the OCR result
				context.Logger.LogLine($"OCR result: {result.Text}")

				' Upload the searchable PDF to S3
				Await UploadPdfToS3Async(bucketName, objectKeyForSearchablePdf, result.SaveAsSearchablePdfBytes())
				context.Logger.LogLine($"PDF uploaded successfully to {bucketName}/{objectKeyForSearchablePdf}")
			Catch e As Exception
				context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
			End Try
		End Function

		''' <summary>
		''' Retrieves a PDF from S3 and returns it as a byte array.
		''' </summary>
		Private Async Function GetPdfFromS3Async(ByVal bucketName As String, ByVal objectKey As String) As Task(Of Byte())
			Dim request = New GetObjectRequest With {
				.BucketName = bucketName,
				.Key = objectKey
			}

			Using response = Await _s3Client.GetObjectAsync(request)
			Using memoryStream As New MemoryStream()
				Await response.ResponseStream.CopyToAsync(memoryStream)
				Return memoryStream.ToArray()
			End Using
			End Using
		End Function

		''' <summary>
		''' Uploads the generated searchable PDF back to S3.
		''' </summary>
		Private Async Function UploadPdfToS3Async(ByVal bucketName As String, ByVal objectKey As String, ByVal pdfBytes() As Byte) As Task
			Using memoryStream As New MemoryStream(pdfBytes)
				Dim request = New PutObjectRequest With {
					.BucketName = bucketName,
					.Key = objectKey,
					.InputStream = memoryStream,
					.ContentType = "application/pdf"
				}

				Await _s3Client.PutObjectAsync(request)
			End Using
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

Antes del bloque try, se especifica el archivo 'sample.pdf' para leer desde el directorio IronPdfZip. El método GetPdfFromS3Async se utiliza luego para recuperar el byte del PDF, que se pasa al método LoadPdf.

Aumentar la memoria y el tiempo de espera

La cantidad de memoria asignada en la función Lambda variará según el tamaño de los documentos que se procesen y la cantidad de documentos procesados simultáneamente. Como línea base, configura la memoria a 512 MB y el tiempo de espera a 300 segundos en aws-lambda-tools-defaults.json.

{
    "function-memory-size": 512,
    "function-timeout": 300
}

Cuando la memoria es insuficiente, el programa lanzará el error: 'Runtime exited with error: signal: killed.' Aumentar el tamaño de la memoria puede resolver este problema. Para más detalles, consulta el artículo de solución de problemas: AWS Lambda - Runtime Exited Signal: Killed.

Publicar

Para publicar en Visual Studio, haz clic derecho en el proyecto y selecciona 'Publicar en AWS Lambda...', luego configura los ajustes necesarios. Puedes leer más sobre la publicación de un Lambda en el sitio web de AWS.

¡Pruébalo!

Puedes activar la función Lambda ya sea a través de la consola de Lambda o a través de Visual Studio.

Preguntas Frecuentes

¿Cómo puedo realizar OCR en documentos en AWS usando C#?

Puedes usar IronOCR para realizar OCR en documentos almacenados en depósitos Amazon S3 integrándola con AWS Lambda. Esto implica crear una función Lambda en C# que recopile documentos de S3, los procese con IronOCR y luego suba los resultados de nuevo a S3.

¿Qué pasos están involucrados en la configuración de OCR en AWS Lambda con C#?

Para configurar OCR en AWS Lambda usando C#, necesitas descargar la biblioteca IronOCR, crear un proyecto AWS Lambda en Visual Studio, configurar tu manejador de funciones para usar IronOCR para el procesamiento y desplegar tu función. Esta configuración te permite convertir imágenes en PDFs buscables.

¿Cuál es la configuración recomendada para ejecutar OCR en AWS Lambda?

Para un rendimiento óptimo al ejecutar OCR con IronOCR en AWS Lambda, se recomienda establecer una asignación de memoria de al menos 512 MB y un período de tiempo de espera de 300 segundos. Estos ajustes ayudan a manejar el procesamiento de documentos grandes o múltiples.

¿Cómo manejo 'Runtime exited with error: signal: killed' en AWS Lambda?

Este error a menudo indica que tu función Lambda ha agotado su memoria asignada. Aumentar la asignación de memoria en la configuración de la función Lambda puede resolver este problema, especialmente al procesar documentos grandes con IronOCR.

¿Puedo probar mi función OCR de AWS Lambda localmente antes de la implementación?

Sí, puedes probar tu función OCR de AWS Lambda localmente usando AWS Toolkit para Visual Studio. Este conjunto de herramientas proporciona un entorno local para simular ejecuciones Lambda, permitiéndote depurar y perfeccionar tu función antes de su implementación.

¿Cuál es el propósito de un Dockerfile en un proyecto de AWS Lambda?

Un Dockerfile en un proyecto de AWS Lambda se utiliza para crear una imagen de contenedor que define el entorno de ejecución y las dependencias para tu función Lambda. Esto garantiza que tu función tenga todos los componentes necesarios para ejecutarse correctamente en AWS.

¿Necesito dependencias adicionales para usar IronOCR en .NET 8 en AWS Lambda?

No se necesitan dependencias adicionales más allá de la biblioteca IronOCR y los paquetes necesarios del SDK de AWS al usar .NET 8 en AWS Lambda. Esto simplifica el proceso de integración para ejecutar tareas de OCR.

¿Cuáles son los requisitos previos para integrar OCR en C# con AWS Lambda?

Antes de integrar OCR en C# con AWS Lambda, necesitas instalar el SDK de AWS para S3, la biblioteca IronOCR y AWS Toolkit para Visual Studio. También necesitarás un depósito de S3 configurado para almacenar y recuperar documentos.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 5,167,857 | Version: 2025.11 recién lanzado