How to Use IronWord on AWS Lambda
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.
How to Use IronWord on AWS Lambda
- Download and add IronWord to your project
- Create an AWS Lambda project using Visual Studio
- Modify the FunctionHandler code to generate Word documents
- Configure and deploy the project with a Docker container
- Invoke the Lambda function and check output files on S3
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
Integrating IronWord with AWS
Create an AWS Lambda Project
Use Visual Studio to create a containerized AWS Lambda project:
- Install the AWS Toolkit for Visual Studio
- Select AWS Lambda Project (.NET Core - C#)
- Choose the .NET 8 (Container Image) blueprint and finish the setup
- 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
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.
Frequently Asked Questions
What is IronWord and how can it enhance Word document processing on AWS Lambda?
IronWord is a powerful tool for processing Word documents, and when integrated with AWS Lambda, it offers scalable and efficient document management, allowing you to automate and streamline Word document tasks.
How do I integrate IronWord with AWS Lambda?
To integrate IronWord with AWS Lambda, you need to set up the IronWord package in your AWS Lambda environment, configure the necessary permissions, and deploy your function code that utilizes IronWord's features for document processing.
What are the benefits of using IronWord on AWS Lambda?
Using IronWord on AWS Lambda allows you to leverage serverless architecture for Word document processing, providing scalability, cost-effectiveness, and reduced infrastructure management.
Can I automate Word document tasks using IronWord on AWS Lambda?
Yes, you can automate various Word document tasks such as creation, modification, and conversion by using IronWord within AWS Lambda functions.
Is it possible to handle large Word documents with IronWord on AWS Lambda?
IronWord is designed to efficiently handle large Word documents, and when used with AWS Lambda, it can process documents in a scalable manner, depending on your Lambda configuration.
What kind of Word document operations can IronWord perform on AWS Lambda?
IronWord can perform a variety of operations on Word documents, including editing, formatting, extracting text, and converting documents to different formats, all within an AWS Lambda environment.
Are there any prerequisites for deploying IronWord on AWS Lambda?
Before deploying IronWord on AWS Lambda, ensure that you have an AWS account, familiarity with AWS Lambda setup, and any necessary IAM roles and permissions configured.
How does IronWord handle updates and maintenance on AWS Lambda?
IronWord is regularly updated to ensure compatibility and performance improvements. In an AWS Lambda environment, you can easily update your deployment package with the latest version of IronWord to maintain optimal functionality.
What support is available for using IronWord with AWS Lambda?
Iron Software provides documentation and support to assist users with integrating and using IronWord on AWS Lambda, ensuring you can effectively utilize its capabilities for your document processing needs.