如何在 AWS Lambda 上對文件進行 OCR 處理

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to 如何在 AWS Lambda 上對文件進行 OCR 處理

這篇操作指南將逐步說明如何使用 IronOCR 設定 AWS Lambda 函式。 遵循本指南,您將學會如何設定 IronOCR 並高效讀取儲存於 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
$vbLabelText   $csharpLabel

立即透過免費試用,在您的專案中開始使用 IronOCR。

第一步:
green arrow pointer

建立 AWS Lambda 專案

透過 Visual Studio,建立容器化的 AWS Lambda 是一項簡易的流程:

  • 安裝 AWS Toolkit for Visual Studio
  • 選擇"AWS Lambda 專案 (.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" .

修改 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 Namespace
$vbLabelText   $csharpLabel

在 try 區塊之前,已指定從 IronPdfZip 目錄讀取檔案 'sample.pdf'。 接著使用 GetPdfFromS3Async 方法擷取 PDF 位元組,並將其傳遞給 LoadPdf 方法。

增加記憶體與超時設定

Lambda 函式中分配的記憶體量,將根據處理中文件的大小以及同時處理的文件數量而有所不同。 作為基準設定,請在 aws-lambda-tools-defaults.json 中將記憶體設為 512 MB,並將超時時間設為 300 秒。

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

當記憶體不足時,程式會拋出錯誤訊息:"執行時因錯誤而終止:信號:被終止。"增加記憶體大小可解決此問題。 如需更多詳細資訊,請參閱疑難排解文章:AWS Lambda - 執行時退出訊號:Killed

發佈

要在 Visual Studio 中發佈,請右鍵點擊專案並選擇"發佈至 AWS Lambda...",然後配置必要的設定。 您可以在 AWS 網站上閱讀更多關於發佈 Lambda 的資訊。

立即試用!

您可以透過 Lambda 控制台或 Visual Studio 來啟用 Lambda 函式。

常見問題

如何使用 C# 在 AWS 上對文件執行 OCR?

您可以透過將 IronOCR 與 AWS Lambda 整合,對儲存於 Amazon S3 儲存桶中的文件執行 OCR 處理。這涉及使用 C# 建立一個 Lambda 函式,該函式會從 S3 擷取文件、透過 IronOCR 進行處理,然後將結果上傳回 S3。

在 AWS Lambda 上使用 C# 設定 OCR 需要哪些步驟?

若要使用 C# 在 AWS Lambda 上設定 OCR,您需要下載 IronOCR程式庫、在 Visual Studio 中建立 AWS Lambda 專案、將函式處理程序設定為使用 IronOCR 進行處理,並部署該函式。此設定可讓您將圖片轉換為可搜尋的 PDF 檔案。

在 AWS Lambda 上執行 OCR 的建議設定為何?

若要在 AWS Lambda 中使用 IronOCR 執行 OCR 並獲得最佳效能,建議將記憶體分配設定為至少 512 MB,並將超時設定為 300 秒。這些設定有助於處理大型或多份文件。

如何處理 AWS Lambda 中的「執行時因錯誤而退出:信號:被終止」?

此錯誤通常表示您的 Lambda 函式已耗盡其分配的記憶體。在 Lambda 函式的設定中增加記憶體分配可解決此問題,特別是在使用 IronOCR 處理大型文件時。

我可以在部署前在本地端測試我的 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 S3 SDK、IronOCR程式庫以及 AWS Toolkit for Visual Studio。此外,您還需要一個已設定好的 S3 儲存桶,用於儲存和檢索文件。

IronOCR 能否用於雲端應用程式?

確實,IronOCR 可部署於雲端環境,使其適用於需要 OCR 功能的網路應用程式與服務。

如何使用 IronOCR 提升 OCR 結果的準確性?

若要提升 IronOCR 的 OCR 準確度,請確保輸入影像品質優良、使用適當的語言套件,並善用該程式庫的影像預處理功能。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 5,896,332 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronOcr
執行範例 觀看您的圖片轉為可搜尋文字。