如何在 Azure 函數中執行IronPDF for Java

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

  • IronPDF for Java 僅支援 Docker 部署。
  • 由於IronPDF需要在運行時執行二進位文件,因此不支援 Zip 部署。

  1. 請依照微軟官方指南,使用自訂映像在 Linux 上建立函數。
    • 對於 Choose a programming language -> 選擇 Java
    • 按照指南操作,直到您的應用程式啟動並運行。
  2. 新增IronPDF依賴項

    • 將以下內容新增至您的 pom 檔案中,並包含最新的 <version>:
    <dependencies>
        <dependency>
            <groupId>com.ironsoftware</groupId>
            <artifactId>ironpdf</artifactId>
            <version>2022.xx.x</version>
        </dependency>
        <dependency>
            <groupId>com.ironsoftware</groupId>
            <artifactId>ironpdf-engine-linux-x64</artifactId>
            <version>2022.xx.x</version>
        </dependency>
    </dependencies>
    <dependencies>
        <dependency>
            <groupId>com.ironsoftware</groupId>
            <artifactId>ironpdf</artifactId>
            <version>2022.xx.x</version>
        </dependency>
        <dependency>
            <groupId>com.ironsoftware</groupId>
            <artifactId>ironpdf-engine-linux-x64</artifactId>
            <version>2022.xx.x</version>
        </dependency>
    </dependencies>
    XML
    • 注意:在 Docker 中執行IronPDF需要ironpdf-engine-linux-x64
  3. 新增 RenderPdf 函數

    • Function.java 中新增函數
    • 此函數將接收一個 URL 並傳回一個渲染後的 PDF。
    import com.microsoft.azure.functions.*;
    import com.ironsoftware.ironpdf.PdfDocument;
    import java.util.Optional;
    
    public class Function {
    
        /**
         * Azure function to render a URL as a PDF and return it.
         * Triggered by an HTTP request with a URL query string parameter.
         */
        @FunctionName("RenderPdf")
        public HttpResponseMessage renderPdf(
                @HttpTrigger(
                        name = "req",
                        methods = {HttpMethod.GET, HttpMethod.POST},
                        authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
                final ExecutionContext context) {
            context.getLogger().info("Java HTTP trigger processed a request. (RenderPdf)");
    
            // Parse query parameter for the URL
            final String url = request.getQueryParameters().get("url");
    
            // Check if the URL parameter is provided
            if (url == null) {
                return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                        .body("Please pass a url on the query string")
                        .build();
            } else {
                try {
                    context.getLogger().info("IronPDF is attempting to render the URL: " + url);
    
                    // Render the given URL as a PDF
                    PdfDocument pdfDocument = PdfDocument.renderUrlAsPdf(url);
    
                    // Convert the PDF document to binary data
                    byte[] content = pdfDocument.getBinaryData();
    
                    // Return the PDF as an attachment in the response
                    return request.createResponseBuilder(HttpStatus.OK)
                            .body(content)
                            .header("Content-Disposition", "attachment; filename=ironpdf_result.pdf")
                            .build();
                } catch (Exception e) {
                    context.getLogger().severe("Failed to render PDF: " + e.getMessage());
                    return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
                            .body("An error occurred while rendering the PDF.")
                            .build();
                }
            }
        }
    }
    import com.microsoft.azure.functions.*;
    import com.ironsoftware.ironpdf.PdfDocument;
    import java.util.Optional;
    
    public class Function {
    
        /**
         * Azure function to render a URL as a PDF and return it.
         * Triggered by an HTTP request with a URL query string parameter.
         */
        @FunctionName("RenderPdf")
        public HttpResponseMessage renderPdf(
                @HttpTrigger(
                        name = "req",
                        methods = {HttpMethod.GET, HttpMethod.POST},
                        authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
                final ExecutionContext context) {
            context.getLogger().info("Java HTTP trigger processed a request. (RenderPdf)");
    
            // Parse query parameter for the URL
            final String url = request.getQueryParameters().get("url");
    
            // Check if the URL parameter is provided
            if (url == null) {
                return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                        .body("Please pass a url on the query string")
                        .build();
            } else {
                try {
                    context.getLogger().info("IronPDF is attempting to render the URL: " + url);
    
                    // Render the given URL as a PDF
                    PdfDocument pdfDocument = PdfDocument.renderUrlAsPdf(url);
    
                    // Convert the PDF document to binary data
                    byte[] content = pdfDocument.getBinaryData();
    
                    // Return the PDF as an attachment in the response
                    return request.createResponseBuilder(HttpStatus.OK)
                            .body(content)
                            .header("Content-Disposition", "attachment; filename=ironpdf_result.pdf")
                            .build();
                } catch (Exception e) {
                    context.getLogger().severe("Failed to render PDF: " + e.getMessage());
                    return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
                            .body("An error occurred while rendering the PDF.")
                            .build();
                }
            }
        }
    }
    JAVA
  4. 更新 Dockerfile

    • 新增IronPDF Linux 所需的軟體包。 從範例中可以看出,基礎 Docker 映像為 mcr.microsoft.com/azure-functions/java:4-java$JAVA_VERSION-build,它是基於 Debian 11。 所以我們需要將這些軟體包加入到 Dockerfile 中。
    RUN apt update \
    && apt install -y libgdiplus libxkbcommon-x11-0 libc6 libc6-dev libgtk2.0-0 libnss3 \
                     libatk-bridge2.0-0 libx11-xcb1 libxcb-dri3-0 libdrm-common libgbm1 \
                     libasound2 libxrender1 libfontconfig1 libxshmfence1
    RUN apt-get install -y xvfb libva-dev libgdiplus
  5. 將函數重新部署到 Azure

    1. 建置與打包:mvn clean package
    2. 建置 Docker 映像:docker build --tag <DOCKER_ID>/azurefunctionsimage:v1.0.0 .
    3. 推送 Docker 映像:docker push <DOCKER_ID>/azurefunctionsimage:v1.0.0
    4. 更新 Azure 函數:
      az functionapp create --name <APP_NAME> --storage-account <STORAGE_NAME> \
                          --resource-group AzureFunctionsContainers-rg --plan myPremiumPlan \
                          --deployment-container-image-name <DOCKER_ID>/azurefunctionsimage:v1.0.0
      az functionapp create --name <APP_NAME> --storage-account <STORAGE_NAME> \
                          --resource-group AzureFunctionsContainers-rg --plan myPremiumPlan \
                          --deployment-container-image-name <DOCKER_ID>/azurefunctionsimage:v1.0.0
      SHELL
  6. 盡情享受IronPDF 的樂趣
    • 觸發函數位於:https://<APP_NAME>.azurewebsites.net/api/RenderPdf?url=https://www.google.com
    • 注意:首次觸發函數時,由於初始化原因,可能會運行緩慢或失敗,但之後應該能夠穩定運行。

常見問題解答

如何在 Java 中使用 Azure Functions 创建 PDF 生成器?

您可以通過 Docker 部署 IronPDF 在 Java 中使用 Azure Functions 创建 PDF 生成器。这涉及在 Azure Function 环境中使用 IronPDF 庫来處理 PDF 生成任务。

為什么在 Azure Functions 上需要 Docker 部署 IronPDF?

在 Azure Functions 上需要 Docker 部署 IronPDF 是因為它需要在運行時执行二進制文件,而这在 Zip 部署方法中不受支持。

向 Maven 項目添加 IronPDF 依赖項的步骤是什么?

要向 Maven 項目添加 IronPDF 依赖項,请在 `pom.xml` 文件中包含 IronPDF 和 `ironpdf-engine-linux-x64` 庫。确保您使用的版本号是最新的,以便兼容。

RenderPdf 函數在 Azure Function 中的工作原理是什么?

Azure Function 中的 RenderPdf 函數從 HTTP 请求中读取 URL,使用 IronPDF 的 `PdfDocument.renderUrlAsPdf` 方法将 URL 渲染為 PDF,并将 PDF 作為附件返回在响應中。

IronPDF 在 Dockerfile 中需要哪些 Linux 軟件包?

IronPDF 的 Dockerfile 應該包含像 `libgdiplus`、`libxkbcommon-x11-0`、`libc6` 和 `libgtk2.0-0` 等 Linux 軟件包,以确保在基于 Debian 的映像中正常運行。

第一次触發 PDF 生成函數時應該有什么预期?

第一次触發 PDF 生成函數時,可能会因初始化過程而变慢或失败。後续执行應更為一致。

如何為 Azure Function 部署 Docker 映像?

要為 Azure Function 部署 Docker 映像,请使用 `mvn clean package` 构建項目,创建 Docker 映像,将其推送到 Docker 注册表,并更新 Azure Function 以使用此新映像。

触發 PDF 生成函數的正确 URL 格式是什么?

要触發 PDF 生成函數,请使用 URL 格式:`https://.azurewebsites.net/api/RenderPdf?url=`。

在哪里可以找到使用自定义 Docker 映像設置 Azure Function 的资源?

要使用自定义 Docker 映像設置 Azure Function,您可以参考 Microsoft 官方指南,了解如何使用自定义映像在 Linux 上创建 Azure Function。

Curtis Chau
技術作家

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

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

準備好開始了嗎?
版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明?
執行範例 觀看您的 HTML 變成 PDF。