IronOCR 開始 C# PDF OCR 如何在 AWS Lambda 上識別文件 OCR Curtis Chau 更新:7月 22, 2025 下載 IronOCR NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在雙子座打開 請向 Gemini 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 This article was translated from English: Does it need improvement? Translated View the article in English 本文提供了使用 IronOCR 設定 AWS Lambda 函數的逐步指南。 透過本指南,您將學習如何配置 IronOCR 並有效率地讀取儲存在 S3 儲存桶中的文件。 如何在 AWS Lambda 上識別文件 OCR 下載一個 C# 函式庫,用於對文件執行 OCR 識別。 創建並選擇項目模板 修改 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 $vbLabelText $csharpLabel 立即開始在您的項目中使用 IronOCR 並免費試用。 第一步: 免費啟動 建立 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" . 修改函數處理程序程式碼 此範例從 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 - 運行時退出訊號:已終止。 發布 若要在 Visual Studio 中發布,請右鍵按一下專案並選擇"發佈到 AWS Lambda...",然後配置必要的設定。 您可以在AWS 網站上閱讀更多關於發布 Lambda 函數的資訊。 試試看! 您可以透過Lambda 控制台或 Visual Studio 啟動 Lambda 函數。 常見問題解答 如何使用 C# 在 AWS 中對文件執行 OCR? 透過與 AWS Lambda 整合,您可以使用 IronOCR 對儲存於 Amazon S3 buckets 的文件執行 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 時,為了獲得最佳效能,建議設定至少 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,是否需要任何其他相依性? 在 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 bucket 來儲存和擷取文件。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 準備好開始了嗎? Nuget 下載 5,167,857 | Version: 2025.11 剛發表 免費下載 NuGet 下載總數:5,167,857 檢視授權