Uso de IronPDF para crear archivos PDF en AWS Lambda

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

1. Crear AWS Lambda con una plantilla de contenedor (.NET 5)

Consulte la primera parte de este documento oficial de AWS: https://aws.amazon.com/blogs/developer/net-5-aws-lambda-support-with-container-images/

2. Añadir dependencias de paquetes

Estas dependencias son necesarias para Chrome en este entorno de AWS.

Modifique el archivo Docker siguiendo estas instrucciones:

3. Añada el paquete NuGet IronPDF (Linux)

Instalar IronPdf.Linux

  1. En el Explorador de soluciones, haga clic con el botón derecho en Referencias, Administrar paquetes NuGet
  2. Seleccione Examinar y busque IronPdf.Linux.
  3. Seleccione el paquete e instálelo.

4. Modificar el código de FunctionHandler

Este ejemplo creará un archivo pdf a partir de una página web https://ironpdf.com/ y lo guardará en /tmp . Para ver este pdf debes subirlo a otro servicio como S3.

public Casing FunctionHandler(string input, ILambdaContext context)
        {
            try
            {
                context.Logger.LogLine($"START FunctionHandler RequestId: {context.AwsRequestId} Input: {input}");
                var awsTmpPath = @"/tmp/"; // AWS temporary storage
                //[optional] enable logging (please uncomment these code if you face any problem)
                //IronPdf.Logging.Logger.EnableDebugging = true;
                //IronPdf.Logging.Logger.LogFilePath = awsTmpPath;
                //IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
                //set your license key
                IronPdf.License.LicenseKey = "YOUR_LICENSE_KEY";
                //set ChromeGpuMode to Disabled
                IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
                //set IronPDF Temp Path
                Environment.SetEnvironmentVariable("TEMP", awsTmpPath, EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("TMP", awsTmpPath, EnvironmentVariableTarget.Process);
                IronPdf.Installation.TempFolderPath = awsTmpPath;
                IronPdf.Installation.CustomDeploymentDirectory = awsTmpPath;
                //set auto LinuxAndDockerDependenciesAutoConfig
                IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
                context.Logger.LogLine($"creating IronPdf.ChromePdfRenderer");
                var Renderer = new IronPdf.ChromePdfRenderer();
                context.Logger.LogLine($"rendering Pdf");
                using var pdfDoc = Renderer.RenderUrlAsPdf("https://ironpdf.com/");
                var guid = Guid.NewGuid();
                var fileName = $"/tmp/{input}_{guid}.pdf"; //save file to /tmp
                context.Logger.LogLine($"saving pdf name : {fileName}");
                pdfDoc.SaveAs(fileName);
                //here you can upload saved pdf file to anywhere such as S3. 
                context.Logger.LogLine($"COMPLETE!");
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"[ERROR] FunctionHandler : {e.Message}");
            }
            return new Casing(input?.ToLower(), input?.ToUpper());
        }
    }
    public record Casing(string Lower, string Upper);
public Casing FunctionHandler(string input, ILambdaContext context)
        {
            try
            {
                context.Logger.LogLine($"START FunctionHandler RequestId: {context.AwsRequestId} Input: {input}");
                var awsTmpPath = @"/tmp/"; // AWS temporary storage
                //[optional] enable logging (please uncomment these code if you face any problem)
                //IronPdf.Logging.Logger.EnableDebugging = true;
                //IronPdf.Logging.Logger.LogFilePath = awsTmpPath;
                //IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
                //set your license key
                IronPdf.License.LicenseKey = "YOUR_LICENSE_KEY";
                //set ChromeGpuMode to Disabled
                IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
                //set IronPDF Temp Path
                Environment.SetEnvironmentVariable("TEMP", awsTmpPath, EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("TMP", awsTmpPath, EnvironmentVariableTarget.Process);
                IronPdf.Installation.TempFolderPath = awsTmpPath;
                IronPdf.Installation.CustomDeploymentDirectory = awsTmpPath;
                //set auto LinuxAndDockerDependenciesAutoConfig
                IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
                context.Logger.LogLine($"creating IronPdf.ChromePdfRenderer");
                var Renderer = new IronPdf.ChromePdfRenderer();
                context.Logger.LogLine($"rendering Pdf");
                using var pdfDoc = Renderer.RenderUrlAsPdf("https://ironpdf.com/");
                var guid = Guid.NewGuid();
                var fileName = $"/tmp/{input}_{guid}.pdf"; //save file to /tmp
                context.Logger.LogLine($"saving pdf name : {fileName}");
                pdfDoc.SaveAs(fileName);
                //here you can upload saved pdf file to anywhere such as S3. 
                context.Logger.LogLine($"COMPLETE!");
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"[ERROR] FunctionHandler : {e.Message}");
            }
            return new Casing(input?.ToLower(), input?.ToUpper());
        }
    }
    public record Casing(string Lower, string Upper);
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

5. Aumentar la memoria y el tiempo de espera

IronPDF requiere más tiempo y memoria que el valor por defecto de Lambda. Puedes configurarlo en aws-lambda-tools-defaults.json. Ajústelo a su función. En este ejemplo lo fijaremos en 512 (MB) y 330 (segundos)

"function-memory-size" : 512, 
    "function-timeout"     : 330,
"function-memory-size" : 512, 
    "function-timeout"     : 330,
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"function-memory-size" : 512, "function-timeout" : 330,
VB   C#

También puede actualizar esta configuración mediante la consola de Lambda. Navegue hasta el Configuración de las funciones de AWS Lambda para más información.

6. Publique

Por favor, siga las instrucciones de la última parte del.NET 5 Soporte de AWS Lambda con imágenes de contenedorpara publicar y probar su función Lambda.

7. Pruébalo.

Puede activar la función Lambda utilizando el botón Consola Lambda o a través de Visual Studio utilizando la función Kit de herramientas de AWS para Visual Studio.