Skip to main content
All docs
V24.1

Amazon Lambda Function for Office File API

  • 7 minutes to read

This topic uses the Microsoft Visual Studio UI to create and deploy a sample AWS Lambda function that uses the Office File API library. The application merges documents uploaded to Amazon S3, adds a barcode, creates a PDF file, and saves the file to Amazon S3.

Prerequisites

  1. Active AWS IAM Credentials.
  2. Visual Studio 2022 with the ASP.NET and web development workload.
  3. AWS Toolkit for Visual Studio.
  4. The latest version of Docker desktop. You can find more information about Docker in the following topic: Get Docker.
  5. Your personal DevExpress NuGet credentials. Refer to the following help topic for instructions on how to obtain the feed URL and authorization key: Choose Between Offline and Online DevExpress NuGet Feeds.
  6. Amazon S3 bucket with uploaded source files (documents in DOCX format). This example uses the dx-office-bucket bucket. Note that bucket names must be unique across all AWS accounts in all AWS Regions within a partition. For more information, review the following document: Bucket naming rules.

    The lambda function uses Amazon S3 keys to retrieve files from the bucket.

  7. Amazon Elastic Container Registry with a private repository to hold the docker image created in this project.
  8. IAM role for Lambda execution with a policy that allows you to interact with the S3 bucket. For more information, review the following document: Lambda execution role. You can use the following permission statement for the policy assigned to the selected (or newly created) role:
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:GetObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::dx-office-bucket/*"
            ]
        }
    ]
    

Office File API Linux Support

For more information on Office File API on Linux, review the following help topics:

Create an AWS Lambda Project

  • From the File menu, select New > Project.
  • Enter AWS in the search box.
  • Select the AWS Lambda Project (.NET Core - C#) template and click Next:

    Create AWS Lambda Project (.NET Core - C#)

  • In the Configure your new project dialog, name the project AWSLambda1 and click Next.
  • The Select Blueprint wizard appears. Select the .NET 8 (Container Image) blueprint and click Finish:

    Select AWS Blueprint

Install NuGet Packages

Install the AWSSDK.S3 NuGet package from the NuGet source:

AWSSDK.S3
Amazon Simple Storage Service (Amazon S3) gives developers and IT teams secure, durable, and highly-scalable object storage.

Visit nuget.devexpress.com, log in to your account, and click Obtain Feed URL. Open the NuGet Package Manager in Visual Studio and register the DevExpress NuGet feed as the package source. Install the following packages:

DevExpress.Document.Processor
This package includes the Word Processing Document API and other Office File API libraries. You need a license for the DevExpress Office File API Subscription or the DevExpress Universal Subscription to use this package in production code.
DevExpress.Drawing.Skia
This package implements the cross-platform PDF renderer based on the Skia Graphics Library. For more information, review the following help topic: DevExpress.Drawing Graphics Library.

If you are new to NuGet packages, see the following installation guide for assistance: Install DevExpress Packages Using NuGet Package Manager.

Implement a Lambda Function

In this example, we use the Stockholm (eu-north-1) Amazon location and the previously created dx-office-bucket S3 bucket. You can change the BucketName, AmazonRegionCode, and AmazonRegionEndPoint values in the code example if needed.

Open the Functions.cs file and replace the content of the Functions.cs file with the following code snippet:

using Amazon.Lambda.Core;
using Amazon.S3.Model;
using Amazon.S3;
using DevExpress.Office.Services;
using DevExpress.XtraRichEdit.API.Native;
using DevExpress.XtraRichEdit;
using DevExpress.XtraSpreadsheet.Services;
using DevExpress.BarCodes;
using DevExpress.Drawing;
using System.Drawing;
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 AWSLambda1;

public class Function
{
    //const string BucketName = "dx-office-bucket";
    const string AmazonRegionCode = "eu-north-1";
    //Amazon.RegionEndpoint AmazonRegionEndPoint = Amazon.RegionEndpoint.EUNorth1;
    //readonly string BucketUrl = $"https://{BucketName}.s3.{AmazonRegionCode}.amazonaws.com/";

    /// <summary>
    /// An Office API function that takes file keys and returns a file key for a PDF file in S3.
    /// </summary>
    /// <param name="input">File keys in S3 storage.</param>
    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    /// <returns></returns>



    public async Task<string> FunctionHandler(FunctionInput input, ILambdaContext context)
    {
        OfficeCharts.Instance.ActivateCrossPlatformCharts(); // Enable chart support
        using (var server = new RichEditDocumentServer()) {
            var config = new AmazonS3Config()
            {
                RegionEndpoint = Amazon.RegionEndpoint.EUNorth1 // AWS Region Code
            };
            // Get source files from Amazon S3.
            using var client = new AmazonS3Client(config);
            var getResponses = new List<Task<GetObjectResponse>>();

            foreach (var fileName in input.FileNames.Select((value, index) => (value, index))) {
                var getRequest = new GetObjectRequest()
                {
                    BucketName = input.BucketName,
                    Key = fileName.value,
                };
                var file = await client.GetObjectAsync(getRequest);
                await MergeDocuments(server, (file, fileName.index));
            }

            server.Document.AppendSection();

            Stream imageStream = GenerateBarCode();
            server.Document.Images.Append(DocumentImageSource.FromStream(imageStream));

            MemoryStream resultStream = new MemoryStream();
            await server.ExportToPdfAsync(resultStream);
            resultStream.Seek(0, SeekOrigin.Begin);

            // Save the resulting file to Amazon S3.
            var pdfFileName = $"{Guid.NewGuid()}.pdf";
            var response = await client.PutObjectAsync(new PutObjectRequest()
            {
                BucketName = input.BucketName,
                Key = pdfFileName,
                InputStream = resultStream,
                ContentType = "application/pdf"
            });
            return pdfFileName;
        }
    }

    public class FunctionInput {
        public required string[] FileNames { get; set; }
        public required string BucketName { get; set; }
    }

    async Task MergeDocuments(RichEditDocumentServer server, 
        (GetObjectResponse file, int index) response) 
        {
        using (var stream = new MemoryStream()) {
            await response.file.ResponseStream.CopyToAsync(stream);
            stream.Seek(0, SeekOrigin.Begin);
            if (response.index == 0) {
                server.Document.LoadDocument(stream);
            }
            else {
                server.Document.AppendDocumentContent(stream);
            }
        }
    }

    Stream GenerateBarCode() {
        BarCode barCode = new BarCode();
        barCode.Symbology = Symbology.QRCode;
        barCode.CodeText = "https://www.devexpress.com";
        barCode.BackColor = Color.White;
        barCode.ForeColor = Color.Black;
        barCode.RotationAngle = 0;
        barCode.CodeBinaryData = Encoding.Default.GetBytes(barCode.CodeText);
        barCode.Options.QRCode.CompactionMode = QRCodeCompactionMode.Byte;
        barCode.Options.QRCode.ErrorLevel = QRCodeErrorLevel.Q;
        barCode.Options.QRCode.ShowCodeText = false;
        barCode.DpiX = 72;
        barCode.DpiY = 72;
        barCode.Module = 2f;

        var stream = new MemoryStream();
        barCode.Save(stream, DXImageFormat.Png);
        return stream;
    }
}

Test the Function Locally

The AWS Toolkit for Visual Studio 2022 installs the Mock Lambda Test Tool that enables the developer to debug .NET Lambda function code in Visual Studio. For more information, review the following document: The AWS .NET Mock Lambda Test Tool.

The tool integrates in Visual Studio so you can click the button to run the Mock Lambda Test Tool and test the project:

Mock Lambda Test Tool Button

A page is opened in a browser that enables you to send a sample request and examine the response:

Mock Test Page

Open the Amazon S3 console and upload source document files to the dx-office-bucket bucket. Obtain the necessary keys to pass as parameters to the function.

Specify a sample request in JSON format, as follows:

{
  "FileNames": [
    "fileKeyOne", 
    "fileKeyTwo"
  ],
  "BucketName": "dx-office-bucket"
}

You can see that the request was processed successfully. The function works as expected and returns the PDF file.

Deploy to AWS

With the AWS Toolkit for Visual Studio installed, you can right-click on the AWSLambda1 project in Solution Explorer and select Publish to AWS Lambda to initiate deployment:

Publish to AWS Lambda

A wizard appears that prompts you to name a function and specify the Amazon Elastic Container Registry name (Image Repo field):

Upload lambda Function Dialog

Select Image Repo (the Amazon Elastic Container Registry name mentioned earlier in the Prerequisites section) from the drop-down box and click Next.

The Advanced Function Details page prompts you to select the Role Name (mentioned earlier in the Prerequisites section) and click Upload:

Advanced Function Details Page

The upload process starts. When it has completed, you can test the uploaded function.

Test the Uploaded Function

Open the Amazon S3 console and upload source document files to the dx-office-bucket bucket. Obtain the necessary keys to pass as parameters to the function.

Open the AWS Console and navigate to the Lambda service. Click the DxOfficeFileAPi function name in the list and switch to the Test tab to test the function as follows:

Lambda Function Test Online

Specify a sample request in JSON format, as follows:

{
  "FileNames": [
    "fileKeyOne", 
    "fileKeyTwo"
  ],
  "BucketName": "dx-office-bucket"
}

Navigate to the S3 section to view the resulting file in the dx-office-bucket bucket:

Lambda Bucket Result

Click Open to view the PDF file:

View the Result