How to Run IronPDF for Java in AWS Lambda

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

Important: Required Settings

  • Zip Deployment is not supported since IronPDF requires the execution of binaries at runtime.
  • You must set PackageType to Image because IronPDF for Java only supports Docker deployment.
  • You must use an AmazonLinux2 Docker image.
  • You must set the following IronPdfEngineWorkingDirectory:
import com.ironsoftware.ironpdf.Settings;
import java.nio.file.Paths;

// Setting the working directory for IronPDF engine
Settings.setIronPdfEngineWorkingDirectory(Paths.get("/tmp/"));
import com.ironsoftware.ironpdf.Settings;
import java.nio.file.Paths;

// Setting the working directory for IronPDF engine
Settings.setIronPdfEngineWorkingDirectory(Paths.get("/tmp/"));
JAVA

Note: This is required because it is the only path that AWS allows for the execution environment.

  • Increase the /tmp size. The default value is 512 MB. Please set it to at least 1024 MB.
  • Include the ironpdf-engine-linux-x64 dependency in your project:
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf-engine-linux-x64</artifactId>
    <version>2022.xx.x</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf-engine-linux-x64</artifactId>
    <version>2022.xx.x</version>
</dependency>
XML
  • Set Lambda timeout to 330 seconds due to a slow start.
  • Set Lambda memory size to at least 1024 MB.

Quick Start with AWS Toolkit for IntelliJ IDEA (AWS SAM)

  1. Install Tools:

    Optional (for local testing):

  2. Create Project: (File -> New -> Project...)

AWS Lambda Project Creation

  1. Configuration:
    • Package Type: Image
    • Runtime: java8 or java11
    • SAM Template: Maven

AWS Lambda Configuration

  1. Add the following dependencies to your pom.xml:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.3</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf-engine-linux-x64</artifactId>
    <version>2022.11.1</version>
</dependency>
<dependency>
    <groupId>io.perfmark</groupId>
    <artifactId>perfmark-api</artifactId>
    <version>0.26.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-okhttp</artifactId>
    <version>1.50.2</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty-shaded</artifactId>
    <version>1.50.2</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.3</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf-engine-linux-x64</artifactId>
    <version>2022.11.1</version>
</dependency>
<dependency>
    <groupId>io.perfmark</groupId>
    <artifactId>perfmark-api</artifactId>
    <version>0.26.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-okhttp</artifactId>
    <version>1.50.2</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty-shaded</artifactId>
    <version>1.50.2</version>
</dependency>
XML
  1. Change the handleRequest function code in App.java to:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.Settings;

import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

// AWS Lambda function to generate a PDF from a URL using IronPDF.
public class App {
    public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
        APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();

        // Enable debugging for IronPDF (optional)
        Settings.setDebug(true);

        // Set the working directory for the IronPDF engine (required)
        Settings.setIronPdfEngineWorkingDirectory(Paths.get("/tmp/"));

        try {
            context.getLogger().log("RENDER PDF");

            // Render the PDF from a URL
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.google.com");

            context.getLogger().log("RENDER PDF SUCCESS");

            // Save the generated PDF to a file
            pdf.saveAs("/tmp/my-first-pdf.pdf");

            // Set HTTP response headers
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("X-Custom-Header", "application/json");

            // Return the successful response
            return response
                    .withHeaders(headers)
                    .withStatusCode(200)
                    .withBody("ENJOY IRON-PDF!");

        } catch (Exception e) {
            // Return the error response
            return response
                    .withBody("{" + e.getMessage() + "}")
                    .withStatusCode(500);
        }
    }
}
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.Settings;

import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

// AWS Lambda function to generate a PDF from a URL using IronPDF.
public class App {
    public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
        APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();

        // Enable debugging for IronPDF (optional)
        Settings.setDebug(true);

        // Set the working directory for the IronPDF engine (required)
        Settings.setIronPdfEngineWorkingDirectory(Paths.get("/tmp/"));

        try {
            context.getLogger().log("RENDER PDF");

            // Render the PDF from a URL
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.google.com");

            context.getLogger().log("RENDER PDF SUCCESS");

            // Save the generated PDF to a file
            pdf.saveAs("/tmp/my-first-pdf.pdf");

            // Set HTTP response headers
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("X-Custom-Header", "application/json");

            // Return the successful response
            return response
                    .withHeaders(headers)
                    .withStatusCode(200)
                    .withBody("ENJOY IRON-PDF!");

        } catch (Exception e) {
            // Return the error response
            return response
                    .withBody("{" + e.getMessage() + "}")
                    .withStatusCode(500);
        }
    }
}
JAVA
  1. Set Lambda config in template.yaml:
Globals:
  Function:
    Timeout: 400
    MemorySize: 2048
    EphemeralStorage:
      Size: 1024
# Do not modify other configurations
Globals:
  Function:
    Timeout: 400
    MemorySize: 2048
    EphemeralStorage:
      Size: 1024
# Do not modify other configurations
YAML
  1. Update Dockerfile:
    • Note: For Java 8, use java8.al2 images because they use AmazonLinux2, while java8 uses the old AmazonLinux.
FROM public.ecr.aws/sam/build-java8.al2:latest as build-image
WORKDIR "/task"
COPY src/ src/
COPY pom.xml ./
RUN mvn -q clean install
RUN mvn dependency:copy-dependencies -DincludeScope=compile

FROM public.ecr.aws/lambda/java:8.al2
RUN yum update -y
RUN yum install -y pango.x86_64 libXcomposite.x86_64 libXcursor.x86_64 \
    libXdamage.x86_64 libXext.x86_64 libXi.x86_64 libXtst.x86_64 \
    cups-libs.x86_64 libXScrnSaver.x86_64 libXrandr.x86_64 GConf2.x86_64 \
    alsa-lib.x86_64 atk.x86_64 gtk3.x86_64 ipa-gothic-fonts \
    xorg-x11-fonts-100dpi xorg-x11-fonts-75dpi xorg-x11-utils \
    xorg-x11-fonts-cyrillic xorg-x11-fonts-Type1 xorg-x11-fonts-misc \
    glibc-devel.x86_64 at-spi2-atk.x86_64 mesa-libgbm.x86_64 libxkbcommon \
    amazon-linux-extras
RUN amazon-linux-extras install epel -y
RUN yum install -y libgdiplus
RUN chmod 777 /tmp/
COPY --from=build-image /task/target/classes /var/task/
COPY --from=build-image /task/target/dependency /var/task/lib

# Command can be overridden by providing a different command in the template directly.
CMD ["helloworld.App::handleRequest"]
  1. Build the project:
sam build -u
sam build -u
SHELL
  1. Deploy the project:
sam deploy --guided
sam deploy --guided
SHELL
  1. Enjoy IronPDF in AWS Lambda! Now your function is live at: Access AWS Lambda Console

Preguntas Frecuentes

¿Cómo puedo crear y editar PDFs en Java en AWS Lambda?

Puede usar IronPDF para Java dentro de AWS Lambda configurando el entorno con una imagen Docker 'AmazonLinux2' y configurando los ajustes necesarios, como aumentar el tamaño del directorio /tmp y establecer el tiempo de espera de Lambda.

¿Por qué no puedo usar Zip Deployment para el procesamiento de PDF en AWS Lambda?

Zip Deployment no es compatible con IronPDF en AWS Lambda porque requiere ejecución binaria en tiempo de ejecución. El 'PackageType' debe configurarse a 'Image' para el despliegue con Docker.

¿Cuáles son las configuraciones requeridas para el directorio de trabajo de IronPDF en AWS Lambda?

Establezca el directorio de trabajo para el motor IronPDF en '/tmp/' y asegúrese de que el tamaño del directorio se incremente a al menos 1024 MB para manejar el procesamiento de PDF eficientemente.

¿Qué dependencias deben incluirse para la generación de PDF en un proyecto Maven en AWS Lambda?

Incluya la dependencia 'ironpdf-engine-linux-x64' en el pom.xml de su proyecto Maven, junto con otras bibliotecas necesarias para habilitar la creación y edición de PDF.

¿Cómo puedo renderizar un PDF desde una URL en AWS Lambda usando Java?

Utilice el método de IronPDF PdfDocument.renderUrlAsPdf para convertir una URL en un documento PDF y guárdelo con el método pdf.saveAs.

¿Cuáles son los ajustes recomendados para el tiempo de espera y la memoria de Lambda para el procesamiento de PDF?

Configure el tiempo de espera de Lambda a 330 segundos y asigne al menos 1024 MB de memoria para satisfacer las necesidades de procesamiento de IronPDF en AWS Lambda.

¿Qué entornos de tiempo de ejecución pueden usarse para ejecutar operaciones de PDF en Java en AWS Lambda?

IronPDF admite entornos de tiempo de ejecución 'java8' y 'java11' para ejecutar tareas de procesamiento de PDF en AWS Lambda.

¿Cómo puedo empezar rápidamente con AWS Toolkit para IntelliJ IDEA para el procesamiento de PDF en Java?

Instale IntelliJ IDEA, AWS Toolkit, SAM CLI y Docker. Opcionalmente, para pruebas locales, configure Java 8 y Maven, luego siga la guía de inicio rápido para crear y configurar su proyecto.

¿Cuál es el proceso para desplegar un proyecto de procesamiento de PDF en Java en AWS Lambda usando SAM CLI?

Primero, construya su proyecto con el comando sam build -u, luego despliegue usando sam deploy --guided para configurar efectivamente su procesamiento de PDF en AWS Lambda.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Versión: 2025.11 recién lanzado