How to OCR documents on AWS Lambda

This article was translated from English: Does it need improvement?
Translated
View the article in English
class="container-fluid">
class="row">
class="col-md-2"> Amazon Lambda Architecture Logo related to How to OCR documents on AWS Lambda

Dieser Artikel bietet eine Schritt-für-Schritt-Anleitung zur Einrichtung einer AWS Lambda-Funktion mit IronOCR. Indem Sie dieser Anleitung folgen, lernen Sie, wie Sie IronOCR konfigurieren und Dokumente, die in einem S3-Bucket gespeichert sind, effizient lesen können.

class="hsg-featured-snippet">

Wie man Dokumente auf AWS Lambda OCR bearbeitet

  1. Laden Sie eine C#-Bibliothek herunter, um OCR auf Dokumenten durchzuführen
  2. Erstellen und wählen Sie die Projektvorlage aus
  3. Ändern Sie den FunctionHandler-Code
  4. Konfigurieren und bereitstellen Sie das Projekt
  5. Rufen Sie die Funktion auf und überprüfen Sie die Ergebnisse in S3

Installation

Für diesen Artikel wird ein S3-Bucket verwendet. Daher ist das AWSSDK.S3-Paket erforderlich.

Wenn Sie IronOCR ZIP verwenden, ist es wichtig, den temporären Ordner festzulegen.

// 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

Nutzen Sie IronOCR heute kostenlos in Ihrem Projekt.

Erster Schritt:
green arrow pointer

Erstellen Sie ein AWS Lambda-Projekt

Mit Visual Studio ist die Erstellung eines containerisierten AWS Lambda ein einfacher Prozess:

  • Installieren Sie das AWS Toolkit für Visual Studio.
  • Wählen Sie ein 'AWS Lambda-Projekt (.NET Core - C#)'.
  • Wählen Sie eine '.NET 8 (Container Image)' Blaupause aus und wählen dann 'Fertigstellen'.

Container Image auswählen

Abhängigkeitspakete hinzufügen

Die Verwendung der IronOCR-Bibliothek in .NET 8 erfordert keine zusätzlichen Abhängigkeiten für die Nutzung auf AWS Lambda. Ändern Sie die Dockerfile des Projekts wie folgt:

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" .

Ändern Sie den FunctionHandler-Code

Dieses Beispiel holt ein Bild von einem S3-Bucket, verarbeitet es und speichert eine durchsuchbare PDF-Datei zurück in denselben Bucket. Das Festlegen des temporären Ordners ist entscheidend, wenn Sie IronOCR ZIP verwenden, da die Bibliothek Schreibberechtigungen benötigt, um den Laufzeitsordner aus den DLLs zu kopieren.

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

Vor dem try-Block wird die Datei 'sample.pdf' zum Lesen aus dem IronPdfZip-Verzeichnis angegeben. Die Methode GetPdfFromS3Async wird dann verwendet, um das PDF-Byte abzurufen, das an die Methode LoadPdf übergeben wird.

Erhöhen Sie Speicher und Timeout

Die Menge des in der Lambda-Funktion zugewiesenen Speichers hängt von der Größe der zu verarbeitenden Dokumente und der Anzahl der gleichzeitig verarbeiteten Dokumente ab. Als Ausgangspunkt stellen Sie den Speicher auf 512 MB und das Timeout auf 300 Sekunden in aws-lambda-tools-defaults.json ein.

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

Wenn der Speicher nicht ausreicht, wirft das Programm den Fehler: 'Runtime exited with error: signal: killed.' Eine Erhöhung der Speichergröße kann dieses Problem lösen. Für weitere Details lesen Sie den Artikel zur Fehlerbehebung: AWS Lambda - Runtime Exited Signal: Killed.

Veröffentlichen

Um in Visual Studio zu veröffentlichen, klicken Sie mit der rechten Maustaste auf das Projekt und wählen 'Publish to AWS Lambda...', dann die erforderlichen Einstellungen konfigurieren. Weitere Informationen zum Veröffentlichen von Lambda finden Sie auf der AWS-Website.

Probieren Sie es aus!

Sie können die Lambda-Funktion entweder über die Lambda-Konsole oder über Visual Studio aktivieren.

Häufig gestellte Fragen

Wie kann ich OCR auf Dokumenten in AWS mit C# durchführen?

Sie können IronOCR verwenden, um OCR auf Dokumenten in Amazon S3-Buckets durchzuführen, indem Sie es in AWS Lambda integrieren. Dies umfasst das Erstellen einer Lambda-Funktion in C#, die Dokumente aus S3 abruft, mit IronOCR verarbeitet und die Ergebnisse dann wieder in S3 hochlädt.

Welche Schritte sind erforderlich, um OCR mit C# auf AWS Lambda einzurichten?

Um OCR auf AWS Lambda mit C# einzurichten, müssen Sie die IronOCR-Bibliothek herunterladen, ein AWS Lambda-Projekt in Visual Studio erstellen, Ihren Funktions-Handler für die Verwendung von IronOCR zur Verarbeitung konfigurieren und Ihre Funktion bereitstellen. Diese Einrichtung ermöglicht es Ihnen, Bilder in durchsuchbare PDFs zu konvertieren.

Was ist die empfohlene Konfiguration für die Ausführung von OCR in AWS Lambda?

Für eine optimale Leistung beim Ausführen von OCR mit IronOCR in AWS Lambda wird empfohlen, mindestens 512 MB Arbeitsspeicher und eine Timeout-Periode von 300 Sekunden festzulegen. Diese Einstellungen helfen bei der Verarbeitung von großen oder mehreren Dokumenten.

Wie gehe ich mit 'Runtime exited with error: signal: killed' in AWS Lambda um?

Dieser Fehler weist oft darauf hin, dass Ihre Lambda-Funktion ihren zugewiesenen Speicher erschöpft hat. Eine Erhöhung der Speicherzuweisung in der Konfiguration der Lambda-Funktion kann dieses Problem lösen, besonders bei der Verarbeitung großer Dokumente mit IronOCR.

Kann ich meine AWS Lambda OCR-Funktion lokal testen, bevor ich sie bereitstelle?

Ja, Sie können Ihre AWS Lambda OCR-Funktion lokal mit dem AWS Toolkit für Visual Studio testen. Dieses Toolkit bietet eine lokale Umgebung zur Simulation von Lambda-Ausführungen, wodurch Sie Ihre Funktion vor der Bereitstellung debuggen und optimieren können.

Was ist der Zweck einer Docker-Datei in einem AWS Lambda-Projekt?

Eine Docker-Datei in einem AWS Lambda-Projekt wird verwendet, um ein Container-Image zu erstellen, das die Ausführungsumgebung und Abhängigkeiten für Ihre Lambda-Funktion definiert. Dies stellt sicher, dass Ihre Funktion alle notwendigen Komponenten hat, um in AWS ordnungsgemäß zu funktionieren.

Benötige ich zusätzliche Abhängigkeiten, um IronOCR in .NET 8 auf AWS Lambda zu verwenden?

Es sind keine zusätzlichen Abhängigkeiten erforderlich, abgesehen von der IronOCR-Bibliothek und den notwendigen AWS SDK-Paketen, wenn Sie .NET 8 auf AWS Lambda verwenden. Dies vereinfacht den Integrationsprozess zur Ausführung von OCR-Aufgaben.

Was sind die Voraussetzungen für die Integration von C# OCR mit AWS Lambda?

Bevor Sie C# OCR mit AWS Lambda integrieren, müssen Sie das AWS SDK für S3, die IronOCR-Bibliothek und das AWS Toolkit für Visual Studio installieren. Sie benötigen auch einen konfigurierten S3-Bucket zum Speichern und Abrufen von Dokumenten.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen
Bereit anzufangen?
Nuget Downloads 5,044,537 | Version: 2025.11 gerade veröffentlicht