Comment utiliser IronWord sur AWS Lambda

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

Cet article fournit un guide complet pour configurer une fonction AWS Lambda en utilisant IronWord. Vous apprendrez comment configurer IronWord pour créer et manipuler des documents Word dans un environnement AWS Lambda.

Installation

Étant donné que cet exemple lira/écrira des documents Word dans un compartiment S3, le package NuGet AWSSDK.S3 est requis.

Utiliser le package ZIP IronWord sur AWS Lambda

Lors de l'utilisation du package ZIP IronWord, il est important de définir un chemin de déploiement temporaire car AWS Lambda a un système de fichiers en lecture seule, sauf pour le dossier /tmp/. Vous devez configurer IronWord pour utiliser ce dossier pour ses fichiers d'exécution :

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

Intégrer IronWord avec AWS

Créer un projet AWS Lambda

Utilisez Visual Studio pour créer un projet AWS Lambda conteneurisé :

  1. Installer l'outil AWS pour Visual Studio
  2. Sélectionner Projet AWS Lambda (.NET Core - C#)
  3. Choisir le modèle .NET 8 (Image conteneur) et terminer l'installation
  4. Sélectionner l'image conteneur comme type de déploiement

Ajouter des dépendances de packages

Ajouter les packages IronWord et AWSSDK.S3 à votre projet via NuGet. La bibliothèque IronWord fonctionne sans problème sur AWS Lambda avec la configuration correcte. Exécutez la commande suivante pour installer IronWord sur votre projet AWS en toute transparence :

Install-Package IronWord

Mettez à jour le Dockerfile de votre projet pour utiliser l'image de base Lambda .NET 8 et copiez vos artefacts de build :

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

RUN dnf update -y

WORKDIR /var/task

COPY "bin/Release/lambda-publish"  .

Modifier le code FunctionHandler

Voici un exemple de fonction Lambda qui crée un document Word simple, l'enregistre en tant que fichier .docx, et le télécharge dans un compartiment 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

Augmenter la mémoire et le délai d'attente

Étant donné que le traitement des documents peut être intensif en mémoire, augmentez la mémoire de votre fonction Lambda à au moins 512 MB et le délai d'attente à 300 secondes dans aws-lambda-tools-defaults.json :

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

Si vous rencontrez des erreurs comme Exécution du runtime interrompue avec erreur : signal : tué, augmentez la mémoire ou optimisez votre code.

Publier

Pour publier votre fonction Lambda :

  • Faites un clic droit sur votre projet dans Visual Studio
  • Sélectionnez Publier sur AWS Lambda...
  • Suivez l'assistant et configurez les paramètres selon vos besoins

Essayez-le !

Invoquez la fonction Lambda à travers la console AWS Lambda ou Visual Studio. Après exécution, vérifiez votre compartiment S3 pour le document Word nouvellement créé.

Questions Fréquemment Posées

Qu'est-ce qu'IronWord et comment peut-il améliorer le traitement des documents Word sur AWS Lambda ?

IronWord est un outil puissant pour le traitement des documents Word, et lorsqu'il est intégré avec AWS Lambda, il offre une gestion de document évolutive et efficace, vous permettant d'automatiser et de rationaliser les tâches de documents Word.

Comment intégrer IronWord avec AWS Lambda ?

Pour intégrer IronWord avec AWS Lambda, vous devez configurer le package IronWord dans votre environnement AWS Lambda, configurer les permissions nécessaires et déployer votre code de fonction qui utilise les fonctionnalités d'IronWord pour le traitement des documents.

Quels sont les avantages d'utiliser IronWord sur AWS Lambda ?

Utiliser IronWord sur AWS Lambda vous permet de tirer parti de l'architecture sans serveur pour le traitement de documents Word, offrant évolutivité, rentabilité et gestion réduite de l'infrastructure.

Puis-je automatiser les tâches de documents Word en utilisant IronWord sur AWS Lambda ?

Oui, vous pouvez automatiser diverses tâches de documents Word telles que la création, la modification et la conversion en utilisant IronWord dans les fonctions AWS Lambda.

Est-il possible de traiter de gros documents Word avec IronWord sur AWS Lambda ?

IronWord est conçu pour traiter efficacement de gros documents Word, et lorsqu'il est utilisé avec AWS Lambda, il peut traiter les documents de manière évolutive, selon la configuration de votre Lambda.

Quel type d'opérations sur documents Word IronWord peut-il effectuer sur AWS Lambda ?

IronWord peut effectuer une variété d'opérations sur les documents Word, y compris l'édition, le formatage, l'extraction de texte et la conversion de documents en différents formats, le tout dans un environnement AWS Lambda.

Y a-t-il des prérequis pour déployer IronWord sur AWS Lambda ?

Avant de déployer IronWord sur AWS Lambda, assurez-vous d'avoir un compte AWS, une familiarité avec la configuration AWS Lambda, et tous les rôles et permissions IAM nécessaires configurés.

Comment IronWord gère-t-il les mises à jour et la maintenance sur AWS Lambda ?

IronWord est régulièrement mis à jour pour assurer la compatibilité et les améliorations de performance. Dans un environnement AWS Lambda, vous pouvez facilement mettre à jour votre package de déploiement avec la dernière version d'IronWord pour maintenir une fonctionnalité optimale.

Quel support est disponible pour l'utilisation d'IronWord avec AWS Lambda ?

Iron Software fournit de la documentation et du support pour assister les utilisateurs dans l'intégration et l'utilisation d'IronWord sur AWS Lambda, en s'assurant que vous pouvez utiliser efficacement ses capacités pour vos besoins en traitement de documents.

Kye Stuart
Rédacteur technique

Kye Stuart fusionne la passion du codage et l'habileté rédactionnelle chez Iron Software. Éduqué au Yoobee College en déploiement de logiciels, ils transforment maintenant des concepts technologiques complexes en contenu éducatif clair. Kye valorise l'apprentissage tout au long de la vie et relève de nouveaux dé...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 28,054 | Version : 2025.12 vient de sortir