如何在 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
    • 注意:首次觸發函數時,由於初始化原因,可能會運行緩慢或失敗,但之後應該能夠穩定運行。

常見問題解答

如何使用 Azure 函式在 Java 中建立 PDF 產生器?

您可以透過 Docker 部署 IronPDF for Java,使用 Azure Functions 在 Java 中建立 PDF 產生器。這需要在 Azure Function 環境中使用 IronPDF 函式庫來處理 PDF 生成任務。

IronPDF on Azure Functions 為何需要 Docker 部署?

IronPdf on Azure Functions 必須使用 Docker 部署,因為它需要在運行時執行二進位檔案,而 Zip 部署方法並不支援這一點。

在 Maven 專案中加入 IronPDF 相依性的步驟為何?

若要在 Maven 專案中加入 IronPDF 的相依性,請在 `pom.xml` 檔案中包含 IronPDF 和 `ironpdf-engine-linux-x64` 函式庫。確保您使用的是最新的版本號,以維持相容性。

Azure 函式中的 RenderPdf 函式如何運作?

Azure 函式中的 RenderPdf 函式會從 HTTP 請求讀取 URL,使用 IronPDF 的 `PdfDocument.renderUrlAsPdf` 方法將 URL 呈現為 PDF,並在回應中以附件形式傳回 PDF。

IronPdf.Linux 的 Dockerfile 需要哪些 Linux 套件?

IronPdf 的 Dockerfile 應該包含 Linux 套件,例如 `libgdiplus`、`libxkbcommon-x11-0`、`libc6` 和 `libgtk2.0-0`,以確保 Debian 系統映像中的正常功能。

第一次觸發 PDF 產生功能時,我應該期待什麼?

第一次觸發 PDF 產生函式時,可能會因為初始化過程而變慢或失敗。之後的執行應該會更穩定。

如何為 Azure 功能部署 Docker 映像檔?

若要為 Azure Function 部署 Docker 映像檔,請使用「mvn clean package」建立專案,建立 Docker 映像檔,將其推送至 Docker 註冊表,並更新 Azure Function 以使用此新映像檔。

在 Azure 中觸發 PDF 生成功能的正確 URL 格式是什麼?

若要觸發 PDF 生成功能,請使用 URL 格式:`https://.azurewebsites.net/api/RenderPdf?url=`。

在哪裡可以找到使用自訂 Docker 映像檔設定 Azure 功能的資源?

關於使用自訂 Docker 映像設定 Azure Function,您可以參考 Microsoft Official Guide for Creating an Azure Function on Linux Using a Custom Image。

Curtis Chau
技術作家

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

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

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