如何在 AWS Lambda 上使用 IronWord
本文提供了使用 IronWord 設定 AWS Lambda 函數的全面指南。 您將學習如何設定 IronWord,以便在 AWS Lambda 環境中建立和操作 Word 文件。
如何在 AWS Lambda 上使用 IronWord
- 下載 IronWord 並將其新增至您的專案中
- 使用 Visual Studio 建立 AWS Lambda 項目
- 修改 FunctionHandler 程式碼以產生 Word 文檔
- 使用 Docker 容器配置和部署項目
- 呼叫 Lambda 函數並檢查 S3 上的輸出文件
安裝
由於此範例將向 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將 IronWord 與 AWS 集成
建立 AWS Lambda 項目
使用 Visual Studio 建立容器化的 AWS Lambda 專案:
- 安裝適用於 Visual Studio 的 AWS 工具包
- 選擇 AWS Lambda 專案(.NET Core - C#)
- 選擇 .NET 8(容器映像)藍圖並完成安裝
- 選擇容器鏡像作為部署類型
新增包依賴項
透過 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增加記憶體和超時
由於文件處理可能佔用大量內存,請在 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 特性的文件處理程式碼。
使用 IronWord 在 AWS Lambda 上的優勢是什麼?
在 AWS Lambda 上使用 IronWord,您可以利用無伺服器架構進行 Word 文件處理,提供可擴展性、成本效益,並減少基礎架構管理。
我可以使用 IronWord 在 AWS Lambda 上自動化 Word 文件任務嗎?
是的,您可以使用 IronWord 在 AWS Lambda 函數中自動化多種 Word 文件任務,例如創建、修改和轉換。
[21] 在 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 上,確保您可以有效利用其功能滿足您的文件處理需求。






