IRONSOFTWAREHOME

如何在AWS Lambda上進行文件OCR

Curtis Chau
Curtis Chau
Updated: 2026年6月4日

這篇如何文章提供了一個使用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;

Start using IronOCR in your project today with a free trial.

第一步:
arrow pointer

建立AWS Lambda專案

使用Visual Studio,建立容器化的AWS Lambda是一個簡單的過程:

  • 安裝Visual Studio的AWS工具包
  • 選擇'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" .
Text

修改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);
            }
        }
    }
}

在try塊之前,指定'sample.pdf'從IronPdfZip目錄中讀取。 然後使用LoadPdf方法。

增加記憶體和超時時間

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

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

當記憶體不足時,程式將拋出錯誤:'運行時退出,錯誤:訊號:被殺死'。增加記憶體大小可以解決此問題。 欲了解更多詳情,請參考故障排除文章:AWS Lambda - 運行時退出,訊號:被殺死

發佈

在Visual Studio中發佈,右鍵單擊專案並選擇'發佈到AWS Lambda...',然後配置所需的設置。 您可以在AWS網站上閱讀有關發佈Lambda的更多資訊。

試一下!

您可以通過Lambda主控台或通過Visual Studio激活Lambda函式。

常見問題

我如何在AWS上使用C#對文件進行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。

運行OCR在AWS Lambda中的推薦配置是什麼?

在AWS Lambda中使用IronOCR運行OCR時,建議設置至少512 MB的記憶體分配和300秒的超時期限。這些設置有助於管理大型或多個文件的處理。

我如何處理AWS Lambda中的“Runtime exited with error: signal: killed”?

此錯誤通常表示您的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是否需要任何其他依賴項?

除了IronOCR程式庫和必要的AWS SDK套件外,不需要其他依賴項,這簡化了在AWS Lambda上進行OCR任務的整合過程。

將C# OCR與AWS Lambda整合的前提條件是什麼?

在整合C# OCR與AWS Lambda之前,您需要安裝AWS SDK for S3、IronOCR程式庫,並在Visual Studio中安裝AWS Toolkit。此外,您還需要配置一個S3桶來儲存和檢索文件。

How do I log OCR results in an AWS Lambda function using IronOCR?

In your AWS Lambda function, use the Lambda context's `Logger.LogLine` method to log OCR results. This allows you to track and verify the OCR output processed by IronOCR.

Is it necessary to install additional dependencies for IronOCR in .NET 8 when deploying to AWS Lambda?

No additional dependencies are required for utilizing the IronOCR library in a .NET 8 AWS Lambda project, aside from setting the correct paths and configuring necessary packages like AWSSDK.S3 for S3 operations.

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

準備開始了嗎?

Nuget Downloads 6,236,385版本:2026.9剛剛發布

立即獲取您的30天試用金鑰
無需信用卡或帳戶建立
C# PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronOcr
nuget.org/packages/IronOcr/
  1. 在解決方案資源管理器中,右鍵點擊參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronOCR"
  3. 選擇包並安裝
C# PDF DLL
下載 DLL

版本: 2026.9

這裡下載Windows安裝程式。

  1. 下載並解壓IronOCR至您的方案目錄下的~/Libs等位置
  2. 在Visual Studio解決方案資源管理器中,右鍵點擊參考。選擇瀏覽,"IronOCR.dll"

授權從$999

有問題嗎?聯絡我們的開發團隊。

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
獲取您的無義務諮詢
填寫以下表格或發送電子郵件至sales@ironsoftware.com
您的詳細資訊將始終保密。
被全球數百萬工程師信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立