如何在 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 文档。

安装

由于此示例将向 S3 存储桶读取/写入 Word 文档,因此需要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. 安装适用于 Visual Studio 的 AWS 工具包
  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

工作目录 /var/task

复制"bin/Release/lambda-publish"。

修改函数处理程序代码

下面是一个 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
}

如果遇到类似"运行时退出并出现错误:信号:终止"的错误,请增加内存或优化代码。

发布

发布 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 文档任务,如创建、修改和转换。

IronWord 在 AWS Lambda 上能否处理大型 Word 文档?

IronWord 被设计为高效处理大型 Word 文档,并且当与 AWS Lambda 一起使用时,可以根据您的 Lambda 配置以可扩展的方式处理文档。

IronWord 在 AWS Lambda 上可以执行哪些 Word 文档操作?

在 AWS Lambda 环境中,IronWord 可以对 Word 文档执行各种操作,包括编辑、格式化、提取文本和将文档转换为不同格式。

在 AWS Lambda 上部署 IronWord 有哪些先决条件?

在部署 IronWord 到 AWS Lambda 之前,确保您拥有一个 AWS 账户,对 AWS Lambda 设置熟悉,并配置了任何必要的 IAM 角色和权限。

IronWord 如何在 AWS Lambda 上处理更新和维护?

IronWord 会定期更新以确保兼容性和性能改进。在 AWS Lambda 环境中,您可以轻松地使用最新版本的 IronWord 更新您的部署包,以保持最佳功能。

使用 IronWord 与 AWS Lambda 相关的支持有哪些?

Iron 软件提供文档和支持,以协助用户将 IronWord 集成并用于 AWS Lambda,确保您能够有效地利用其功能满足您的文档处理需求。

Kye Stuart
技术作家

Kye Stuart 在 Iron Software 中将编码热情与写作技能结合在一起。他在 Yoobee 学院接受软件部署教育,现在将复杂的技术概念转化为清晰的教育内容。Kye 重视终身学习,接受新的技术挑战。

工作之余,他们喜欢 PC 游戏、Twitch 上的直播,以及户外活动如园艺和带狗 Jaiya 散步。Kye 的直截了当的方法使他们成为 Iron Software 使命的关键,即为全球开发者解密技术。

准备开始了吗?
Nuget 下载 27,129 | Version: 2025.11 刚刚发布