Wie man OCR-Dokumente auf AWS Lambda erstellt
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.
OCR von Dokumenten auf AWS Lambda
- Laden Sie eine C#-Bibliothek herunter, um OCR auf Dokumenten durchzuführen
- Erstellen und wählen Sie die Projektvorlage
- Ändern Sie den FunctionHandler-Code
- Konfigurieren und stellen Sie das Projekt bereit
- Rufen Sie die Funktion auf und überprüfen Sie die Ergebnisse in S3
Installation
Dieser Artikel wird einen S3-Bucket verwenden, daher wird das AWSSDK.S3-Paket benötigt.
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.
Dim awsTmpPath As String = "/tmp/"
IronOcr.Installation.InstallationPath = awsTmpPath
IronOcr.Installation.LogFilePath = awsTmpPath' Set temporary folder path and log file path for IronOCR.
Dim awsTmpPath As String = "/tmp/"
IronOcr.Installation.InstallationPath = awsTmpPath
IronOcr.Installation.LogFilePath = awsTmpPathBeginnen Sie noch heute, IronOCR in Ihrem Projekt mit einer kostenlosen Testversion zu verwenden.
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'.

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 NamespaceImports 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 NamespaceVor dem try-Block wird die Datei 'sample.pdf' zum Lesen aus dem IronPDFZip-Verzeichnis angegeben. Die GetPdfFromS3Async Methode wird dann verwendet, um das PDF-Byte abzurufen, das an die LoadPdf Methode ü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. Setzen Sie als Ausgangspunkt den Speicher auf 512 MB und das Timeout auf 300 Sekunden in aws-lambda-tools-defaults.json.
{
"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 - Laufzeit beenden: Signal: Getötet.
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. Mehr über das Veröffentlichen einer Lambda-Funktion können Sie auf der AWS-Website lesen.
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 IronOCR mit AWS in einem C#-Projekt integrieren?
Um IronOCR mit AWS in einem C#-Projekt zu integrieren, müssen Sie eine AWS Lambda-Funktion einrichten. Befolgen Sie die Schritt-für-Schritt-Anleitung im Tutorial, um IronOCR zu konfigurieren und Dokumente effizient in einem S3-Bucket zu lesen.
Welche Voraussetzungen sind für die Verwendung von IronOCR auf AWS Lambda erforderlich?
Bevor Sie IronOCR auf AWS Lambda verwenden, müssen Sie das AWS Toolkit für Visual Studio installiert haben, ein AWS Lambda-Projekt in .NET Core einrichten und das AWSSDK.S3-Paket für die Verwaltung von S3-Operationen installieren.
Wie bearbeite ich die OCR-Verarbeitung in einer Lambda-Funktion mit IronOCR?
In einer AWS Lambda-Funktion kann IronOCR Bilder verarbeiten, indem es sie aus einem S3-Bucket abruft, IronTesseract verwendet, um den Inhalt zu lesen, und die Ergebnisse als durchsuchbare PDFs zurück in den S3-Bucket speichert.
Warum ist das Festlegen des temporären Ordners wichtig, wenn IronOCR ZIP verwendet wird?
Das Festlegen des temporären Ordnerpfads ist wichtig, wenn IronOCR ZIP verwendet wird, da Schreibrechte erforderlich sind, um den Laufwerksordner aus den DLLs zu kopieren. Diese Konfiguration ermöglicht es IronOCR, ordnungsgemäß in der Lambda-Umgebung zu funktionieren.
Was sollte ich tun, wenn ich einen 'signal: killed'-Fehler beim Verwenden von IronOCR auf AWS Lambda erhalte?
Wenn Sie auf einen 'Runtime exited with error: signal: killed'-Fehler stoßen, kann dies auf unzureichende Speicherzuweisung für Ihre Lambda-Funktion zurückzuführen sein. Die Erhöhung der Speichergröße und der Timeout-Einstellungen in der aws-lambda-tools-defaults.json-Datei kann dieses Problem lösen.
Wie kann ich mein AWS Lambda-Projekt mit Visual Studio veröffentlichen?
Um ein AWS Lambda-Projekt aus Visual Studio zu veröffentlichen, klicken Sie mit der rechten Maustaste auf Ihr Projekt, wählen Sie 'Publish to AWS Lambda...' und konfigurieren Sie die erforderlichen Einstellungen gemäß der AWS-Dokumentation zur Veröffentlichung von Lambda-Funktionen.
Welche Speicher- und Timeout-Einstellungen werden empfohlen, um große Dokumente mit IronOCR auf AWS Lambda zu verarbeiten?
Für die Verarbeitung großer Dokumente wird empfohlen, mindestens 512 MB Speicher zuzuweisen und einen Timeout von 300 Sekunden festzulegen, um sicherzustellen, dass die Lambda-Funktion reibungslos ohne Fehler ausgeführt wird.
Kann IronOCR PDFs direkt in AWS Lambda verarbeiten?
Ja, IronOCR kann PDFs direkt in AWS Lambda verarbeiten, indem die IronTesseract-Klasse verwendet wird, um PDFs aus einem S3-Bucket zu lesen und durchsuchbare PDFs zurück in den Bucket zu senden.
Wie protokolliere ich OCR-Ergebnisse in einer AWS Lambda-Funktion mit IronOCR?
Verwenden Sie in Ihrer AWS Lambda-Funktion die Logger.LogLine-Methode des Lambda-Kontexts, um OCR-Ergebnisse zu protokollieren. Dadurch können Sie die von IronOCR verarbeiteten OCR-Ausgaben nachverfolgen und überprüfen.
Ist es notwendig, zusätzliche Abhängigkeiten für IronOCR in .NET 8 bei der Bereitstellung in AWS Lambda zu installieren?
Für die Verwendung der IronOCR-Bibliothek in einem .NET 8 AWS Lambda-Projekt sind keine zusätzlichen Abhängigkeiten erforderlich, abgesehen vom Festlegen der richtigen Pfade und der Konfiguration notwendiger Pakete wie AWSSDK.S3 für S3-Operationen.
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 Handbücher.