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.
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 = awsTmpPath오늘 무료 체험으로 프로젝트에서 IronOCR 사용을 시작하십시오.
AWS Lambda 프로젝트 생성
Visual Studio를 사용하면 컨테이너화된 AWS Lambda를 쉽게 생성할 수 있습니다.
- AWS Toolkit for Visual Studio 설치.
- 'AWS Lambda Project (.NET Core - C#)'를 선택합니다.
- ' .NET 8(컨테이너 이미지)' 블루프린트를 선택한 다음 '완료'를 선택합니다.

패키지 종속성 추가
.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" .
함수 핸들러 코드를 수정하세요
이 예제는 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 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 Namespacetry 블록 이전에 'sample.pdf' 파일이 IronPDFZip 디렉토리에서 읽도록 지정됩니다. GetPdfFromS3Async 메서드는 PDF 바이트를 검색하는 데 사용된 후, LoadPdf 메서드로 전달됩니다.
메모리 및 타임아웃 증가
Lambda 함수에 할당된 메모리 양은 처리 문서의 크기와 동시에 처리되는 문서 수에 따라 달라집니다. 기본값으로, 메모리를 512 MB로 설정하고 aws-lambda-tools-defaults.json에서 타임아웃을 300초로 설정하십시오.
{
"function-memory-size": 512,
"function-timeout": 300
}
메모리가 부족할 경우 프로그램이 'Runtime exited with error: signal: killed.' 오류를 발생시킵니다. 메모리 크기를 늘려 이 문제를 해결할 수 있습니다. 자세한 내용은 문제 해결 기사: AWS Lambda - Runtime Exited Signal: Killed를 참조하십시오.
게시
Visual Studio에서 배포하려면 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 'Publish to AWS Lambda...'를 선택한 후 필요한 설정을 구성합니다. Lambda를 게시하는 것에 대한 더 많은 정보를 AWS 웹사이트에서 읽을 수 있습니다.
한번 시도해 보세요!
Lambda 함수를 Lambda 콘솔 또는 Visual Studio를 통해 활성화할 수 있습니다.
자주 묻는 질문
IronOCR를 C# 프로젝트에서 AWS와 통합하려면 어떻게 해야 하나요?
C# 프로젝트에서 IronOCR를 AWS와 통합하려면 AWS Lambda 함수를 설정해야 합니다. 튜토리얼에 제공된 단계별 지침을 따라 IronOCR를 구성하고 S3 버킷에 저장된 문서를 효율적으로 읽도록 합니다.
AWS Lambda에서 IronOCR를 사용하기 위한 사전 요구 사항은 무엇인가요?
AWS Lambda에서 IronOCR를 사용하기 전에 Visual Studio용 AWS Toolkit을 설치하고, .NET Core에서 AWS Lambda 프로젝트를 설정하며, S3 작업을 관리하기 위한 AWSSDK.S3 패키지를 준비해야 합니다.
IronOCR를 사용하여 Lambda 함수에서 OCR 처리를 어떻게 수행하나요?
AWS Lambda 함수에서 IronOCR는 S3 버킷에서 이미지를 가져와 IronTesseract를 사용하여 내용을 읽고, 결과를 검색 가능한 PDF로 S3 버킷에 다시 저장할 수 있습니다.
IronOCR ZIP을 사용할 때 임시 폴더를 설정하는 것이 왜 중요한가요?
IronOCR ZIP을 사용할 때 임시 폴더 경로를 설정하는 것은 DLL에서 런타임 폴더를 복사하기 위한 쓰기 권한이 필요하기 때문입니다. 이러한 구성은 Lambda 환경 내에서 IronOCR가 올바르게 작동할 수 있도록 합니다.
IronOCR를 AWS Lambda에서 사용할 때 'signal: killed' 오류가 발생하면 어떻게 해야 하나요?
‘Runtime exited with error: signal: killed’ 오류가 발생하면 Lambda 함수에 할당된 메모리가 부족할 수 있습니다. aws-lambda-tools-defaults.json 파일에서 메모리 크기와 타임아웃 설정을 늘리면 이 문제를 해결할 수 있습니다.
Visual Studio를 사용하여 AWS Lambda 프로젝트를 배포하려면 어떻게 해야 하나요?
Visual Studio에서 AWS Lambda 프로젝트를 배포하려면 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 'Publish to AWS Lambda...'를 선택한 다음 AWS 문서에 따라 필요한 설정을 구성하십시오.
IronOCR를 AWS Lambda에서 큰 문서를 처리할 때 권장 메모리 및 시간 초과 설정은 무엇인가요?
큰 문서를 처리하기 위해서는 Lambda 함수가 오류 없이 원활하게 실행될 수 있도록 최소 512 MB의 메모리를 할당하고 300초의 시간 초과를 설정하는 것이 좋습니다.
IronOCR가 AWS Lambda에서 PDF를 직접 처리할 수 있나요?
네, IronOCR는 S3 버킷에서 로드한 PDF를 읽기 위해 IronTesseract 클래스를 사용하여 AWS Lambda에서 PDF를 직접 처리하고, 검색 가능한 PDF로 버킷에 반환할 수 있습니다.
IronOCR를 사용하여 AWS Lambda 함수에서 OCR 결과를 어떻게 기록하나요?
AWS Lambda 함수에서 Lambda 컨텍스트의 Logger.LogLine 메서드를 사용하여 OCR 결과를 기록하십시오. 이를 통해 IronOCR가 처리한 OCR 출력을 추적하고 확인할 수 있습니다.
AWS Lambda에 배포할 때 .NET 8에서 IronOCR용 추가 종속성을 설치해야 하나요?
S3 작업을 위한 AWSSDK.S3와 같은 필요한 패키지를 설정하고 올바른 경로를 설정하는 것 외에는 .NET 8 AWS Lambda 프로젝트에서 IronOCR 라이브러리를 사용하는 데 추가 종속성이 필요하지 않습니다.
커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.