How to Use IronWord on AWS Lambda

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

This article provides a comprehensive guide to setting up an AWS Lambda function using IronWord. You will learn how to configure IronWord to create and manipulate Word documents within an AWS Lambda environment.

Installation

Since this example will read/write Word documents to an S3 bucket, the AWSSDK.S3 NuGet package is required.

Using IronWord ZIP Package on AWS Lambda

When using the IronWord ZIP package, it’s important to set a temporary deployment path because AWS Lambda has a read-only filesystem except for the /tmp/ folder. You must configure IronWord to use this folder for its runtime files:

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

Integrating IronWord with AWS

Create an AWS Lambda Project

Use Visual Studio to create a containerized AWS Lambda project:

  1. Install the AWS Toolkit for Visual Studio
  2. Select AWS Lambda Project (.NET Core - C#)
  3. Choose the .NET 8 (Container Image) blueprint and finish the setup
  4. Select container image as the deployment type

Add Package Dependencies

Add IronWord and AWSSDK.S3 packages to your project via NuGet. The IronWord library works smoothly on AWS Lambda with the correct setup. Run the following command to install IronWord to your AWS project seamlessly:

Install-Package IronWord

Update your project's Dockerfile to use the .NET 8 Lambda base image and copy your build artifacts:

FROM public.ecr.aws/lambda/dotnet:8

RUN dnf update -y

WORKDIR /var/task

COPY "bin/Release/lambda-publish"  .

Modify the FunctionHandler Code

Below is an example Lambda function that creates a simple Word document, saves it as a .docx file, and uploads it to an S3 bucket.

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

Increase Memory and Timeout

Since document processing can be memory-intensive, increase your Lambda function memory to at least 512 MB and timeout to 300 seconds in aws-lambda-tools-defaults.json:

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

If you encounter errors like Runtime exited with error: signal: killed, increase memory or optimize your code.

Publish

To publish your Lambda function:

  • Right-click your project in Visual Studio
  • Select Publish to AWS Lambda...
  • Follow the wizard and configure settings as needed

Try It Out!

Invoke the Lambda function through the AWS Lambda Console or Visual Studio. After execution, check your S3 bucket for the newly created Word document.

常见问题解答

什么是 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 下载 25,807 | 版本: 2025.11 刚刚发布