如何在 AWS Lambda 中運行 IronPDF for Java

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

重要提示:必需設置

  • 由於 IronPDF 需要在執行時執行二進位文件,因此不支援Zip 部署
  • 您必須將PackageType設定為Image ,因為 IronPDF for Java 僅支援 Docker 部署。
  • 您必須使用AmazonLinux2 Docker 映像。
  • 您必須設定以下 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

注意:這是必需的,因為這是 AWS 允許的執行環境的唯一路徑。

  • 增加/tmp大小。預設值為 512 MB。 請將其設定為至少 1024 MB。
  • ironpdf-engine-linux-x64依賴項新增至您的專案:
<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
  • 由於啟動緩慢,將 Lambda 逾時時間設定為 330 秒。
  • 將 Lambda 記憶體大小設定為至少 1024 MB。

IntelliJ IDEA 的 AWS 工具組 (AWS SAM) 快速入門

1.安裝工具:

2.建立專案:( File -> New -> Project...

建立 AWS Lambda 項目

3.配置:

  • 包裝類型: Image
  • 執行時間環境: java8java11
  • SAM 範本: Maven

! AWS Lambda 配置

4.將以下依賴項加入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

5.App.java中的handleRequest函數程式碼改為:

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

6.template.yaml中設定 Lambda 配置:

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

7.更新 Dockerfile:

  • 注意:對於 Java 8,請使用java8.al2鏡像,因為它們使用AmazonLinux2 ,而java8使用舊的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"]

8.建置專案:

sam build -u
sam build -u
SHELL

9.部署專案:

sam deploy --guided
sam deploy --guided
SHELL

10.在 AWS Lambda 中體驗 IronPDF!您的函數現已上線:存取 AWS Lambda 控制台

常見問題解答

如何在 AWS Lambda 上創建和編輯 PDF?

您可以通過設置 'AmazonLinux2' Docker 映像並配置必要設置,如增大 /tmp 目錄大小並設置 Lambda 超時,來在 AWS Lambda 中使用 IronPDF for Java。

為什麼不能在 AWS Lambda 中使用 Zip 部署進行 PDF 處理?

在 AWS Lambda 中,IronPDF 不支持 Zip 部署,因為它需要在運行時進行二進制執行。'PackageType' 必須設置為 'Image' 用於 Docker 部署。

IronPDF 的工作目錄在 AWS Lambda 中的所需配置是什麼?

將 IronPDF 引擎的工作目錄設置為 '/tmp/',並確保目錄大小增加到至少 1024 MB 以有效處理 PDF。

在 AWS Lambda 上的 Maven 項目中,PDF 生成需要包括哪些依賴項?

在您的 Maven 項目的 pom.xml 中包括 'ironpdf-engine-linux-x64' 依賴項,及其他必要庫以啟用 PDF 創建和編輯功能。

如何在 AWS Lambda 上使用 Java 渲染 URL 作為 PDF?

利用 IronPDF 方法 PdfDocument.renderUrlAsPdf 將 URL 轉換為 PDF 文檔,並使用 pdf.saveAs 方法保存它。

建議的 Lambda 超時和內存設置是什麼以進行 PDF 處理?

將 Lambda 超時設置為 330 秒,並分配至少 1024 MB 的內存以滿足 IronPDF 在 AWS Lambda 中的處理需求。

在 Java 上使用 AWS Lambda 運行 PDF 操作,可以使用哪些運行時環境?

IronPDF 支持 'java8' 和 'java11' 運行時環境以在 AWS Lambda 上執行 PDF 處理任務。

如何快速開始在 IntelliJ IDEA 中使用 AWS Toolkit 來進行 Java 的 PDF 處理?

安裝 IntelliJ IDEA、AWS Toolkit、SAM CLI 和 Docker。可選地,為本地測試設置 Java 8 和 Maven,然後遵循快速入門指南創建和配置您的項目。

使用 SAM CLI 在 AWS Lambda 上部署 Java PDF 處理項目的流程是什麼?

首先,使用命令 sam build -u 構建您的項目,然後使用 sam deploy --guided 部署以有效設置您的 PDF 處理在 AWS Lambda。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
版本: 2025.12 剛發表