如何在 AWS Lambda 上使用 IronWord

This article was translated from English: Does it need improvement?
Translated
View the article in English

本文提供了一份使用 IronWord 設定 AWS Lambda 函式的完整指南。 您將學習如何設定 IronWord,以便在 AWS Lambda 環境中建立及處理 WORD 文件。

安裝

由於此範例將讀寫 WORD 文件至 S3 儲存桶,因此需要 AWSSDK.S3 NuGet 套件

在 AWS Lambda 上使用 IronWord ZIP 套件

使用 IronWord ZIP 套件時,務必設定臨時部署路徑,因為 AWS Lambda 的檔案系統僅 /tmp/ 資料夾具讀寫權限,其餘皆為唯讀。 您必須設定 IronWord,使其使用此資料夾存放執行時檔案:

var awsTmpPath = @"/tmp/";
IronSoftware.Word.Installation.DeploymentPath = awsTmpPath;
var awsTmpPath = @"/tmp/";
IronSoftware.Word.Installation.DeploymentPath = awsTmpPath;
Dim awsTmpPath = "/tmp/"
IronSoftware.Word.Installation.DeploymentPath = awsTmpPath
$vbLabelText   $csharpLabel

將 IronWord 與 AWS 整合

建立 AWS Lambda 專案

使用 Visual Studio 建立容器化的 AWS Lambda 專案:

  1. 安裝 AWS Toolkit for Visual Studio
  2. 選擇 AWS Lambda 專案 (.NET Core - C#)
  3. 選擇 .NET 8 (容器映像) 藍圖並完成設定
  4. 選擇容器映像作為部署類型

新增套件依賴項

請透過 NuGet 將 IronWord 和 AWSSDK.S3 套件加入您的專案。 IronWord程式庫在正確設定下,可在 AWS Lambda 上順暢運作。執行以下指令,即可無縫將 IronWord 安裝至您的 AWS 專案:

Install-Package IronWord

請更新專案的 Dockerfile 以使用 .NET 8 Lambda 基礎映像檔,並複製您的建置產出:

來源:public.ecr.aws/lambda/dotnet:8

執行 dnf update -y

WORKDIR /var/task

COPY "bin/Release/lambda-publish"  .

修改 FunctionHandler 程式碼

以下是一個 Lambda 函式的範例,該函式會建立一個簡單的 WORD 文件,將其儲存為 .docx 檔案,並上傳至 S3 儲存桶。

using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronWord;
using IronWord.Models;
using System.Text;

// 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 IronWordAwsLambda;

public class Function
{
    private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

    public async Task FunctionHandler(ILambdaContext context)
    {
        var awsTmpPath = @"/tmp/";
        License.LicenseKey = "YOUR-LICENSE-KEY"; // Replace if you have one

        string filename = Guid.NewGuid() + ".docx";
        string localPath = Path.Combine(awsTmpPath, filename);
        string bucketName = "your-s3-bucket-name";
        string objectKey = $"IronWordAwsLambda/{filename}";

        try
        {
            // Create Word Document
            var doc = new WordDocument();
            Paragraph paragraph = new Paragraph(new TextContent("Hello from IronWord on AWS Lambda!"));
            doc.AddParagraph(paragraph);
            doc.SaveAs(localPath);

            context.Logger.LogLine("Word document created.");

            // Upload to S3
            byte[] fileBytes = await File.ReadAllBytesAsync(localPath);
            await UploadToS3Async(bucketName, objectKey, fileBytes);

            context.Logger.LogLine($"Document uploaded to S3: {bucketName}/{objectKey}");
        }
        catch (Exception ex)
        {
            context.Logger.LogLine($"[ERROR] {ex.Message}");
        }
    }

    private async Task UploadToS3Async(string bucketName, string objectKey, byte[] fileBytes)
    {
        using var stream = new MemoryStream(fileBytes);
        var request = new PutObjectRequest
        {
            BucketName = bucketName,
            Key = objectKey,
            InputStream = stream,
            ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        };
        await _s3Client.PutObjectAsync(request);
    }
}
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronWord;
using IronWord.Models;
using System.Text;

// 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 IronWordAwsLambda;

public class Function
{
    private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

    public async Task FunctionHandler(ILambdaContext context)
    {
        var awsTmpPath = @"/tmp/";
        License.LicenseKey = "YOUR-LICENSE-KEY"; // Replace if you have one

        string filename = Guid.NewGuid() + ".docx";
        string localPath = Path.Combine(awsTmpPath, filename);
        string bucketName = "your-s3-bucket-name";
        string objectKey = $"IronWordAwsLambda/{filename}";

        try
        {
            // Create Word Document
            var doc = new WordDocument();
            Paragraph paragraph = new Paragraph(new TextContent("Hello from IronWord on AWS Lambda!"));
            doc.AddParagraph(paragraph);
            doc.SaveAs(localPath);

            context.Logger.LogLine("Word document created.");

            // Upload to S3
            byte[] fileBytes = await File.ReadAllBytesAsync(localPath);
            await UploadToS3Async(bucketName, objectKey, fileBytes);

            context.Logger.LogLine($"Document uploaded to S3: {bucketName}/{objectKey}");
        }
        catch (Exception ex)
        {
            context.Logger.LogLine($"[ERROR] {ex.Message}");
        }
    }

    private async Task UploadToS3Async(string bucketName, string objectKey, byte[] fileBytes)
    {
        using var stream = new MemoryStream(fileBytes);
        var request = new PutObjectRequest
        {
            BucketName = bucketName,
            Key = objectKey,
            InputStream = stream,
            ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        };
        await _s3Client.PutObjectAsync(request);
    }
}
Imports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronWord
Imports IronWord.Models
Imports System.Text

' 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 IronWordAwsLambda

	Public Class [Function]
		Private Shared ReadOnly _s3Client As IAmazonS3 = New AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1)

		Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
			Dim awsTmpPath = "/tmp/"
			License.LicenseKey = "YOUR-LICENSE-KEY" ' Replace if you have one

			Dim filename As String = Guid.NewGuid().ToString() & ".docx"
			Dim localPath As String = Path.Combine(awsTmpPath, filename)
			Dim bucketName As String = "your-s3-bucket-name"
			Dim objectKey As String = $"IronWordAwsLambda/{filename}"

			Try
				' Create Word Document
				Dim doc = New WordDocument()
				Dim paragraph As New Paragraph(New TextContent("Hello from IronWord on AWS Lambda!"))
				doc.AddParagraph(paragraph)
				doc.SaveAs(localPath)

				context.Logger.LogLine("Word document created.")

				' Upload to S3
				Dim fileBytes() As Byte = Await File.ReadAllBytesAsync(localPath)
				Await UploadToS3Async(bucketName, objectKey, fileBytes)

				context.Logger.LogLine($"Document uploaded to S3: {bucketName}/{objectKey}")
			Catch ex As Exception
				context.Logger.LogLine($"[ERROR] {ex.Message}")
			End Try
		End Function

		Private Async Function UploadToS3Async(ByVal bucketName As String, ByVal objectKey As String, ByVal fileBytes() As Byte) As Task
			Dim stream = New MemoryStream(fileBytes)
			Dim request = New PutObjectRequest With {
				.BucketName = bucketName,
				.Key = objectKey,
				.InputStream = stream,
				.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
			}
			Await _s3Client.PutObjectAsync(request)
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

增加記憶體與超時設定

由於文件處理可能需要大量記憶體,請在 aws-lambda-tools-defaults.json 中將 Lambda 函式的記憶體增加至至少 512 MB,並將超時設定為 300 秒:

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

若遇到"Runtime exited with error: signal: killed"等錯誤,請增加記憶體或優化您的程式碼。

發佈

要發佈您的 Lambda 函式:

  • 在 Visual Studio 中右鍵點擊您的專案
  • 選擇"發佈至 AWS Lambda..."
  • 請依照精靈指示,並依需求設定相關選項

立即試用!

透過 AWS Lambda 控制台或 Visual Studio 呼叫 Lambda 函式。 執行後,請檢查您的 S3 儲存桶,確認是否已建立新的 WORD 文件。

常見問題

什麼是 IronWord,它如何提升 AWS Lambda 上的 WORD 文件處理能力?

IronWord 是一款用於處理 WORD 文件的強大工具,當與 AWS Lambda 整合時,可提供可擴展且高效的文件管理功能,讓您能自動化並簡化 WORD 文件相關任務。

如何將 IronWord 與 AWS Lambda 整合?

若要將 IronWord 與 AWS Lambda 整合,您需要在 AWS Lambda 環境中設定 IronWord 套件、配置必要的權限,並部署利用 IronWord 功能進行文件處理的函式程式碼。

在 AWS Lambda 上使用 IronWord 有什麼好處?

在 AWS Lambda 上使用 IronWord,可讓您運用無伺服器架構來處理 Word 文件,提供可擴展性、成本效益,並減少基礎架構管理負擔。

我能否使用 IronWord 在 AWS Lambda 上自動化處理 Word 文件任務?

是的,您可以透過在 AWS Lambda 函式中使用 IronWord,來自動化各種 Word 文件任務,例如建立、修改和轉換。

是否可以在 AWS Lambda 上使用 IronWord 處理大型 WORD 文件?

IronWord 旨在高效處理大型 WORD 文件,若與 AWS Lambda 搭配使用,可根據您的 Lambda 設定,以可擴展的方式處理文件。

IronWord 能在 AWS Lambda 上執行哪些 WORD 文件操作?

IronWord 可在 AWS Lambda 環境中對 Word 文件執行多種操作,包括編輯、格式設定、文字擷取,以及將文件轉換為不同格式。

在 AWS Lambda 上部署 IronWord 是否有任何先決條件?

在 AWS Lambda 上部署 IronWord 之前,請確保您已擁有 AWS 帳戶、熟悉 AWS Lambda 的設定流程,並已配置所有必要的 IAM 角色與權限。

IronWord 如何處理 AWS Lambda 上的更新與維護?

IronWord 會定期更新,以確保相容性並提升效能。在 AWS Lambda 環境中,您可以輕鬆將部署套件更新至 IronWord 的最新版本,以維持最佳功能。

關於在 AWS Lambda 上使用 IronWord,有哪些支援資源?

Iron Software 提供文件與技術支援,協助使用者將 IronWord 整合至 AWS Lambda 並加以運用,確保您能有效利用其功能來滿足文件處理需求。

Kye Stuart
技術撰稿人

Kye Stuart 在 Iron Software 將編程熱情與寫作技巧完美結合。他們曾於 Yoobee College 修習軟體部署課程,如今專注於將複雜的技術概念轉化為淺顯易懂的教育內容。Kye 重視終身學習,並樂於迎接新的技術挑戰。

工作之餘,他熱衷於 PC 遊戲、在 Twitch 進行直播,以及園藝和遛狗(愛犬名為 Jaiya)等戶外活動。Kye 直率坦誠的作風,使其成為 Iron Software 實現「為全球開發者解構技術神秘面紗」這項使命的關鍵人物。

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

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronWord
執行範例 觀看您的資料轉為 WORD 文件。