AWS LambdaでドキュメントをOCR処理する方法
このハウツー記事では、IronOCR を使用して AWS Lambda 関数を設定するための手順ガイドを提供します。 このガイドに従うことで、IronOCR を設定し、S3 バケットに保存されているドキュメントを効率的に読み取る方法を学習します。
AWS LambdaでドキュメントをOCR処理する方法
- ドキュメントのOCRを実行するためのC#ライブラリをダウンロードする
- プロジェクトテンプレートを作成し、選択
- FunctionHandlerコードを修正
- プロジェクトを設定してデプロイ
- 関数を呼び出し、S3で結果を確認
インストール
この記事では、S3バケットを使用するため、AWSSDK.S3パッケージが必要です。
IronOCR ZIP を使用する場合は、一時フォルダーを設定することが不可欠です。
// 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今日あなたのプロジェクトでIronOCRを無料トライアルで使用開始。
AWS Lambdaプロジェクトを作成
Visual Studioを使用すれば、コンテナ化されたAWS Lambdaを簡単に作成できます:
- AWS Toolkit for Visual Studioをインストールします。
- "AWS Lambda プロジェクト (.NET Core - C#)"を選択します。
- '.NET 8 (Container Image)' ブループリントを選択し、次に '完了' を選択

パッケージ依存関係を追加
.NET 8 で IronOCR ライブラリを使用する場合、AWS Lambda で使用するために追加の依存関係をインストールする必要はありません。 プロジェクトの Dockerfile を次のように変更します。
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" .FunctionHandlerコードの修正
この例では、S3 バケットから画像を取得して処理し、検索可能な PDF を同じバケットに保存します。 IronOCR ZIP を使用する場合、ライブラリが DLL からランタイム フォルダーをコピーするために書き込み権限を必要とするため、一時フォルダーを設定することが不可欠です。
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 Namespacetry ブロックの前に、IronPdfZip ディレクトリから読み取るファイル 'sample.pdf' が指定されています。 次に、 GetPdfFromS3Asyncメソッドを使用して PDF バイトを取得し、 LoadPdfメソッドに渡します。
メモリとタイムアウトの増加
Lambda関数に割り当てられるメモリ量は、処理されるドキュメントのサイズと同時に処理されるドキュメント数に応じて変わります。 基準として、メモリを512 MBに設定し、タイムアウトを300秒にaws-lambda-tools-defaults.jsonで設定します。
{
"function-memory-size": 512,
"function-timeout": 300
}メモリが不足すると、プログラムは 'Runtime exited with error: signal: killed.'とエラーを投げます。メモリサイズを増やすことでこの問題を解決できます。 詳細については、トラブルシューティングの記事" AWS Lambda - ランタイム終了シグナル: Killed"を参照してください。
公開
Visual Studioで公開するには、プロジェクトを右クリックして 'AWS Lambdaに公開...' を選択し、必要な設定を構成します。 Lambdaの公開についてさらに詳しくは、AWSのウェブサイトを参照してください。
試してみましょう!
LambdaコンソールまたはVisual Studioを使用して、Lambda関数をアクティブにすることができます。
よくある質問
C#を使用してAWSでドキュメントにOCRを実行するにはどうすればいいですか?
IronOCRを使用すると、AWS Lambdaと統合することで、Amazon S3バケットに保存されているドキュメントにOCRを実行できます。これは、S3からドキュメントを取得し、IronOCRで処理した後、結果を再びS3にアップロードするC#のLambda関数を作成することを含みます。
C#を使用してAWS LambdaでOCRを設定するためにどのようなステップが必要ですか?
C#を使用してAWS LambdaでOCRを設定するには、IronOCRライブラリをダウンロードし、Visual StudioでAWS Lambdaプロジェクトを作成し、IronOCRを使用して処理する関数ハンドラーを構成して、関数をデプロイする必要があります。この設定により、画像を検索可能なPDFに変換できます。
AWS LambdaでOCRを実行するための推奨構成は何ですか?
AWS LambdaでIronOCRを使用してOCRを実行する際の最適なパフォーマンスのためには、少なくとも512 MBのメモリ割り当てと300秒のタイムアウト期間を設定することが推奨されます。これらの設定は、大規模または複数のドキュメントの処理を管理するのに役立ちます。
AWS Lambdaで「Runtime exited with error: signal: killed」にどのように対処しますか?
このエラーは、Lambda関数が割り当てられたメモリを使い果たしたことを示すことがよくあります。大規模なドキュメントをIronOCRで処理する際、この問題を解決するには、Lambda関数の構成でメモリ割り当てを増やすことができます。
AWS Lambda OCR関数をデプロイ前にローカルでテストできますか?
はい、AWS Toolkit for Visual Studioを使用して、AWS Lambda OCR関数をローカルでテストすることができます。このツールキットは、Lambda実行をシミュレートするためのローカル環境を提供し、デプロイ前に関数のデバッグと改善を行うことができます。
AWS LambdaプロジェクトのDockerfileの目的は何ですか?
AWS LambdaプロジェクトのDockerfileは、Lambda関数の実行環境と依存関係を定義するコンテナイメージを作成するために使用されます。これにより、関数がAWSで適切に実行されるために必要なすべてのコンポーネントを確実に備えることができます。
AWS Lambdaで.NET 8を使用する際にIronOCRを使用するために追加の依存関係は必要ですか?
AWS Lambdaで.NET 8を使用する際にIronOCRライブラリと必要なAWS SDKパッケージ以外の追加の依存関係は必要ありません。これにより、OCRタスクを実行するための統合プロセスが簡素化されます。
C# OCRをAWS Lambdaと統合するための前提条件は何ですか?
C# OCRをAWS Lambdaと統合する前に、AWS SDK for S3、IronOCRライブラリ、およびAWS Toolkit for Visual Studioをインストールする必要があります。また、ドキュメントを保存および取得するための設定済みのS3バケットも必要です。






