Conversión de Documentos en AWS

Si estás construyendo aplicaciones nativas de la nube en AWS y requieres capacidades robustas de generación, manipulación o conversión de PDF, integrar Aspose.PDF for .NET en funciones de AWS Lambda ofrece una solución potente y escalable. Este enfoque te permite aprovechar las extensas características de Aspose.PDF dentro del entorno sin servidor de AWS, integrándose potencialmente con otros servicios como S3 para almacenamiento.

Este artículo te guía a través de la configuración y ejecución de Aspose.PDF for .NET en AWS Lambda, cubriendo la creación básica de PDF y abordando desafíos comunes como la gestión de fuentes en la nube.

Requisitos Previos

  • Cuenta activa de AWS. Requerida para crear e implementar funciones Lambda. Si no tienes una, regístrate en aws.amazon.com.
  • Visual Studio 2017, 2019 o 2022 con el AWS Toolkit for Visual Studio instalado. Esto simplifica la creación, implementación y prueba de proyectos.

Ejecutar una aplicación Aspose.PDF for .NET en AWS Lambda

Sigue estos pasos para crear una función Lambda simple que genere un documento PDF utilizando Aspose.PDF y lo guarde en Amazon S3:

  1. Crear Proyecto de AWS Lambda. En Visual Studio, crea un nuevo proyecto utilizando la plantilla AWS Lambda Project (.NET Core - C#). Selecciona la plantilla Empty Function cuando se te solicite. Esto proporciona una estructura básica de función.
  2. Agregar Paquetes NuGet. Haz clic derecho en tu proyecto en el Explorador de Soluciones, selecciona “Administrar paquetes NuGet…” e instala lo siguiente:
  • Aspose.PDF. La biblioteca principal para la manipulación de PDF.
  • AWSSDK.S3. La biblioteca del SDK de AWS para .NET para interactuar con el almacenamiento S3.
  1. Implementar la Función Lambda. Reemplaza el contenido de tu archivo de controlador de función (por ejemplo, Function.cs) con el siguiente código. Este ejemplo crea un documento PDF básico con texto y lo guarda en un bucket de S3.
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using Aspose.Pdf;
using Aspose.Pdf.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 TestAsposePdfLambda
{
    public class Function
    {
        private IAmazonS3 S3Client { get; set; }
        private const string BucketName = "your-s3-bucket-name";

        /// <summary>
        /// Default constructor. Initializes the S3 client.
        /// </summary>
        public Function()
        {
            S3Client = new AmazonS3Client();
            // Consider setting the License here if needed, e.g., in a static constructor
            Aspose.Pdf.License lic = new Aspose.Pdf.License();
            // Assumes license file is an embedded resource
            lic.SetLicense("Aspose.PDF.lic");
        }

        /// <summary>
        /// Lambda function handler: Creates a PDF document and saves it to S3.
        /// </summary>
        public async Task<string> FunctionHandler(string input, ILambdaContext context)
        {
            context.Logger.LogLine($"Function processing input: {input}");

            // Create PDF document
            Document pdfDocument = new Document();

            // Add a page
            Page page = pdfDocument.Pages.Add();

            // Add text elements
            page.Paragraphs.Add(new TextFragment($"Hello {input} from Aspose.PDF!"));
            page.Paragraphs.Add(new TextFragment($"You are running on: {System.Environment.OSVersion.VersionString}"));

            // Save the PDF to a MemoryStream
            using (MemoryStream ms = new MemoryStream())
            {
                // Aspose.PDF saves directly to PDF format
                pdfDocument.Save(ms);
                // Reset stream position for reading
                ms.Position = 0;

                // Upload the stream to S3
                string outputKey = $"AP_out_{DateTime.UtcNow:yyyyMMddHHmmss}.pdf";
                context.Logger.LogLine($"Attempting to upload {outputKey} to bucket {BucketName}");
                bool putResult = await PutS3Object(BucketName, outputKey, ms, context);

                return putResult ? $"OK - PDF saved as s3://{BucketName}/{outputKey}" : "FAILED to upload PDF to S3";
            }
        }

        /// <summary>
        /// Helper method to upload a stream to an S3 bucket.
        /// </summary>
        private async Task<bool> PutS3Object(string bucket, string key, Stream content, ILambdaContext context)
        {
            try
            {
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = bucket,
                    Key = key,
                    InputStream = content,
                    // Set appropriate content type
                    ContentType = "application/pdf"
                };
                var response = await S3Client.PutObjectAsync(request);
                context.Logger.LogLine($"S3 PutObject Response: {response.HttpStatusCode}");
                return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
            }
            catch (AmazonS3Exception s3ex)
            {
                context.Logger.LogLine($"Error uploading to S3: {s3ex.Message} (AWS Request ID: {s3ex.RequestId}, Error Code: {s3ex.ErrorCode})");
                return false;
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"General error during S3 upload: {ex.Message}");
                return false;
            }
        }
    }
}
  1. Desplegar y Probar
  • Reemplaza "your-s3-bucket-name" en el código con el nombre de un bucket de S3 al que tengas acceso de escritura.
  • Haz clic derecho en el proyecto en Visual Studio y selecciona Publicar en AWS Lambda…. Sigue el asistente para configurar e implementar tu función.
  • Una vez desplegada, puedes invocar la función desde el Explorador de AWS de Visual Studio o desde la Consola de Administración de AWS. Pasa cualquier cadena como entrada.
  • Verifica tu bucket de S3 para el archivo PDF generado (por ejemplo, AP_out_... .pdf).

Problema Potencial: Disponibilidad de Fuentes

Cuando examines el PDF generado, podrías notar que el texto no utiliza las fuentes estándar que esperarías (como Arial o Times New Roman). En su lugar, Aspose.PDF podría usar una fuente de reserva. Los entornos de ejecución de AWS Lambda son contenedores de Linux mínimos. Por lo general, carecen de las fuentes TrueType comunes que se encuentran en Windows o distribuciones de Linux de escritorio. Cuando Aspose.PDF no puede encontrar las fuentes especificadas o predeterminadas, las sustituye por fuentes de reserva disponibles para asegurar que el texto aún se renderice. Esto puede afectar la fidelidad visual de tu documento.

Cómo Usar Fuentes Personalizadas Almacenadas en S3 con Aspose.PDF for .NET

Para asegurar que tus PDFs se rendericen con las fuentes correctas, necesitas proporcionarlas a Aspose.PDF dentro del entorno Lambda. Almacenar fuentes en un bucket de S3 es un enfoque flexible y común para aplicaciones en la nube:

  • Subir Fuentes a S3. Crea una carpeta (por ejemplo, Fonts) en tu bucket de S3 y sube los archivos de fuentes TrueType (.ttf) o OpenType (.otf) necesarios. Para demostración, podrías usar un conjunto disponible gratuitamente como “Noto Sans”.
  • Cargar Fuentes desde S3 en Lambda. Modifica tu función Lambda para obtener estos archivos de fuentes de S3 y registrarlos con el FontRepository de Aspose.PDF.

Aquí te mostramos cómo puedes adaptar el código de la función Lambda anterior:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using Aspose.Pdf;
using Aspose.Pdf.Text;

// Assembly attribute
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace TestAsposePdfLambda
{
    public class Function
    {
        private IAmazonS3 S3Client { get; set; }
        private const string BucketName = "your-s3-bucket-name"; // Replace with your bucket name
        private const string FontsS3Folder = "Fonts/"; // Folder in your bucket containing .ttf/.otf files

        private static bool _fontsLoaded = false; // Flag to load fonts only once per container instance
        private static readonly object _fontLoadLock = new object(); // Lock for thread safety

        /// <summary>
        /// Static constructor: Ensures fonts are loaded when the class is first accessed
        /// within a Lambda execution environment instance.
        /// </summary>
        static Function()
        {
            // Consider setting the License here if needed
            Aspose.Pdf.License lic = new Aspose.Pdf.License();
            lic.SetLicense("Aspose.PDF.lic");
        }

        /// <summary>
        /// Default constructor. Initializes S3 client.
        /// </summary>
        public Function()
        {
            S3Client = new AmazonS3Client();
            // Ensure fonts are loaded
            EnsureFontsLoaded(S3Client, BucketName, FontsS3Folder);
        }

        /// <summary>
        /// Lambda function handler: Creates a PDF with custom fonts loaded from S3.
        /// </summary>
        public async Task<string> FunctionHandler(string input, ILambdaContext context)
        {
            context.Logger.LogLine($"Function processing input: {input}");
            // Ensure fonts loaded (important for warm starts)
            EnsureFontsLoaded(S3Client, BucketName, FontsS3Folder, context);

            // Create PDF document
            Document pdfDocument = new Document();

            // Add a page
            Page page = pdfDocument.Pages.Add();

            // Create TextFragment and specify the font
            TextFragment titleFragment = new TextFragment($"Hello {input} from Aspose.PDF!");

            // Attempt to find the font loaded from S3. Use the actual font name
            titleFragment.TextState.Font = FontRepository.FindFont("Noto Sans");
            // If the font wasn't found/loaded, FindFont might return a default/fallback font
            titleFragment.TextState.FontSize = 14;
            page.Paragraphs.Add(titleFragment);

            TextFragment infoFragment = new TextFragment($"Running on: {System.Environment.OSVersion.VersionString}");
            // Example using a specific style
            infoFragment.TextState.Font = FontRepository.FindFont("Noto Sans Regular");
            infoFragment.TextState.FontSize = 10;
            page.Paragraphs.Add(infoFragment);

            // Save PDF to stream
            using (MemoryStream ms = new MemoryStream())
            {
                pdfDocument.Save(ms);
                ms.Position = 0;

                // Upload to S3
                string outputKey = $"AP_Font_out_{DateTime.UtcNow:yyyyMMddHHmmss}.pdf";
                context.Logger.LogLine($"Attempting to upload {outputKey} to bucket {BucketName}");
                bool putResult = await PutS3Object(BucketName, outputKey, ms, context);
                return putResult ? $"OK - PDF saved as s3://{BucketName}/{outputKey}" : "FAILED to upload PDF to S3";
            }
        }

        /// <summary>
        /// Loads fonts from S3 into Aspose.PDF's FontRepository if not already loaded.
        /// </summary>
        private void EnsureFontsLoaded(IAmazonS3 s3Client, string bucketName, string fontsFolderKey, ILambdaContext context = null)
        {
            // Prevent multiple threads/invocations trying to load simultaneously
            lock (_fontLoadLock)
            {
                if (_fontsLoaded)
                {
                    return;
                }

                context?.Logger.LogLine("Attempting to load fonts from S3...");
                try
                {
                    // Get font sources from S3
                    var fontSources = Task.Run(async () => await GetS3FontSources(s3Client, bucketName, fontsFolderKey, context)).Result;

                    if (fontSources.Any())
                    {
                        // Clear existing default sources (optional, ensures only S3 fonts are primary)
                        // FontRepository.Sources.Clear();

                        // Add the sources loaded from S3
                        FontRepository.Sources.AddRange(fontSources);
                        context?.Logger.LogLine($"Successfully loaded {fontSources.Count()} font sources from S3.");
                        _fontsLoaded = true;
                    }
                    else
                    {
                        context?.Logger.LogLine("No font sources found in S3 folder.");
                        // Set _fontsLoaded to true anyway to avoid retrying every invocation if folder is empty/missing
                        _fontsLoaded = true;
                    }
                }
                catch (AggregateException aggEx) when (aggEx.InnerException is AmazonS3Exception s3Ex)
                {
                    context?.Logger.LogLine($"S3 Error loading fonts: {s3Ex.Message} (Request ID: {s3Ex.RequestId}, Error Code: {s3Ex.ErrorCode}) - Check bucket/folder name and permissions.");
                    // Avoid retrying constantly on permission errors
                    _fontsLoaded = true;
                }
                catch (Exception ex)
                {
                    context?.Logger.LogLine($"Error loading fonts from S3: {ex.ToString()}");
                    // Decide if you want to retry or not. Setting _fontsLoaded = true prevents retries.
                    _fontsLoaded = true;
                }
            }
        }

        /// <summary>
        /// Lists font files in an S3 folder and creates MemoryFontSource for each.
        /// </summary>
        private static async Task<List<MemoryFontSource>> GetS3FontSources(IAmazonS3 client, string bucketName, string fontsFolderKey, ILambdaContext context)
        {
            List<MemoryFontSource> fontSources = new List<MemoryFontSource>();
            ListObjectsV2Request request = new ListObjectsV2Request()
            {
                BucketName = bucketName,
                // e.g., "Fonts/"
                Prefix = fontsFolderKey,
            };

            context?.Logger.LogLine($"Listing objects in {bucketName}/{fontsFolderKey}");
            ListObjectsV2Response response;
            do
            {
                // Requires s3:ListBucket permission on the bucket
                response = await client.ListObjectsV2Async(request);

                foreach (S3Object entry in response.S3Objects)
                {
                    // Skip the folder itself and non-font files (simple check)
                    if (entry.Key.EndsWith("/") || !(entry.Key.EndsWith(".ttf", StringComparison.OrdinalIgnoreCase) || entry.Key.EndsWith(".otf", StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    context?.Logger.LogLine($"Found font file: {entry.Key}");
                    try
                    {
                        // Requires s3:GetObject permission on the font files
                        GetObjectRequest fontRequest = new GetObjectRequest
                        {
                            BucketName = bucketName,
                            Key = entry.Key
                        };
                        using (GetObjectResponse fontResponse = await client.GetObjectAsync(fontRequest))
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                await fontResponse.ResponseStream.CopyToAsync(ms);
                                // IMPORTANT: Aspose.PDF needs the raw byte array for MemoryFontSource.
                                // It manages the stream internally after this.
                                fontSources.Add(new MemoryFontSource(ms.ToArray()));
                                context?.Logger.LogLine($" -- Added MemoryFontSource for {entry.Key}");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        context?.Logger.LogLine($" -- Failed to load font {entry.Key}: {ex.Message}");
                        // Decide how to handle failures - continue or stop?
                    }
                }
                request.ContinuationToken = response.NextContinuationToken;
            } while (response.IsTruncated);

            return fontSources;
        }

        /// <summary>
        /// Helper method to upload a stream to an S3 bucket.
        /// </summary>
        private async Task<bool> PutS3Object(string bucket, string key, Stream content, ILambdaContext context)
        {
            try
            {
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = bucket,
                    Key = key,
                    InputStream = content,
                    // Set appropriate content type
                    ContentType = "application/pdf"
                };
                var response = await S3Client.PutObjectAsync(request);
                context.Logger.LogLine($"S3 PutObject Response: {response.HttpStatusCode}");
                return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
            }
            catch (AmazonS3Exception s3ex)
            {
                context.Logger.LogLine($"Error uploading to S3: {s3ex.Message} (AWS Request ID: {s3ex.RequestId}, Error Code: {s3ex.ErrorCode})");
                return false;
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"General error during S3 upload: {ex.Message}");
                return false;
            }
        }
    }
}