AWS Lambda에서 문서 OCR 및 pdf 텍스트 추출 수행 방법
이 사용 방법 문서는 IronOCR를 사용하여 AWS Lambda 기능을 설정하는 단계별 가이드를 제공합니다. 이 강력한 OCR 프로그램을 활용하여 IronOCR를 구성하고 S3 버킷에 저장된 문서에서 pdf 텍스트 추출 및 이미지 텍스트 변환을 효율적으로 수행하는 방법을 배울 수 있습니다.
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를 쉽게 생성할 수 있습니다.
- Visual Studio용 AWS Toolkit을 설치합니다.
- '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 Namespace
try 블록 이전에 'sample.pdf' 파일이 IronPdfZip 디렉토리에서 읽도록 지정됩니다. 그런 다음 GetPdfFromS3Async 메서드를 사용하여 PDF 바이트를 검색하고, 이 바이트를 LoadPdf 메서드에 전달합니다.
메모리 및 타임아웃 증가
Lambda 함수에 할당된 메모리 양은 처리 문서의 크기와 동시에 처리되는 문서 수에 따라 달라집니다. 기준점으로 메모리를 512MB로, 타임아웃을 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를 통해 활성화할 수 있습니다.
자주 묻는 질문
C#을 사용하여 AWS에 저장된 문서에 OCR을 적용하려면 어떻게 해야 하나요?
IronOCR을 AWS Lambda와 통합하면 Amazon S3 버킷에 저장된 문서에 OCR을 적용할 수 있습니다. 이를 위해서는 C#으로 Lambda 함수를 생성하여 S3에서 문서를 가져오고, IronOCR로 처리한 후, 결과를 다시 S3에 업로드해야 합니다.
C#을 사용하여 AWS Lambda에서 OCR을 설정하는 데 필요한 단계는 무엇입니까?
C#을 사용하여 AWS Lambda에서 OCR을 설정하려면 IronOCR 라이브러리를 다운로드하고, Visual Studio에서 AWS Lambda 프로젝트를 생성하고, 함수 핸들러가 IronOCR을 처리 도구로 사용하도록 구성한 다음, 함수를 배포해야 합니다. 이렇게 설정하면 이미지를 검색 가능한 PDF로 변환할 수 있습니다.
AWS Lambda에서 OCR을 실행하기 위한 권장 구성은 무엇입니까?
AWS Lambda에서 IronOCR을 사용하여 OCR을 실행할 때 최적의 성능을 얻으려면 최소 512MB의 메모리 할당과 300초의 타임아웃 기간을 설정하는 것이 좋습니다. 이러한 설정은 대용량 문서 또는 여러 문서를 처리하는 데 도움이 됩니다.
AWS Lambda에서 '런타임이 오류로 종료되었습니다: signal: killed' 오류를 어떻게 처리해야 하나요?
이 오류는 Lambda 함수가 할당된 메모리를 모두 소진했음을 나타내는 경우가 많습니다. 특히 IronOCR을 사용하여 대용량 문서를 처리할 때 Lambda 함수 구성에서 메모리 할당량을 늘리면 이 문제를 해결할 수 있습니다.
AWS Lambda OCR 함수를 배포하기 전에 로컬 환경에서 테스트할 수 있나요?
예, AWS 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 버킷도 필요합니다.

