如何在Azure上設置IronPDF for Java Copy for LLMsCopy for LLMs Copy page as Markdown for LLMs
# 如何在Azure上設置IronPDF for Java
本指南涵蓋了在Azure Functions容器內部署[IronPDF for Java](https://ironpdf.com/java/),並從無伺服器的HTTP端點按需生成PDF的所有步驟。 由於IronPDF搭載了一個原生的Chromium渲染引擎,因此必須打包為Docker映像 - Azure Functions上的標準Zip部屬方法無法在運行時執行IronPDF所依賴的二進位文件。按照本指南進行,一個工作中的Azure Function會接受作為查詢參數的URL並返回完全渲染的PDF作為可下載文件。
此方法使用[Microsoft推薦的自定義容器工作流程](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-function-linux-custom-image)適用於基於Linux的Azure Functions。 一個Maven專案提供了功能程式碼和依賴管理。 Docker建構容器映像,然後將其推送到註冊表,並由Azure Function App引用。一旦部署,冷啟動時間是主要的性能考慮——隨後的調用速度快且一致。
在開始之前,請確保[Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli)、Docker Desktop、Maven 3.8+ 和 JDK 11 或 JDK 17 已安裝在本地。 還需要一個活躍的Azure訂閱,並有權建立Functions App和儲存帳戶。
*as-heading:2(快速入門:在Azure Functions上部署IronPDF for Java)*
下面的程式碼顯示了完整的`RenderPdf` Azure Function。 它接受`url` 查詢參數並返回一個PDF位元組流。 在完成接下來各部分的Maven依賴設置後,將其新增到`Function.java`。
```java
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/RenderPdf.java
import com.microsoft.azure.functions.*;
import com.ironsoftware.ironpdf.PdfDocument;
import java.util.Optional;
public class Function {
/**
* HTTP-triggered Azure Function: accepts a URL, renders it as a PDF,
* and returns the PDF bytes as a downloadable attachment.
*/
@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("RenderPdf function triggered.");
// Read the target URL from the query string
final String url = request.getQueryParameters().get("url");
if (url == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Provide a 'url' query parameter.")
.build();
}
try {
context.getLogger().info("Rendering URL as PDF: " + url);
// IronPDF renders the full page including JavaScript
PdfDocument pdf = PdfDocument.renderUrlAsPdf(url);
byte[] pdfBytes = pdf.getBinaryData();
return request.createResponseBuilder(HttpStatus.OK)
.body(pdfBytes)
.header("Content-Disposition", "attachment; filename=output.pdf")
.header("Content-Type", "application/pdf")
.build();
} catch (Exception ex) {
context.getLogger().severe("PDF rendering failed: " + ex.getMessage());
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body("PDF rendering failed. Check function logs for details.")
.build();
}
}
}
```
!!!--LIBRARY_START_TRIAL_BLOCK--!!!
*as-heading:2(目錄)*
- [需要哪些先決條件?](#prerequisites)
- [如何建立Azure Function專案?](#set-up-project)
- [如何將IronPDF依賴新增到Maven專案中?](#add-ironpdf-dependencies)
- [如何編寫RenderPdf功能?](#write-renderpdf-function)
- [如何配置IronPDF的Dockerfile?](#configure-dockerfile)
- [如何構建並發布Docker映像?](#build-push-docker)
- [如何將功能部署到Azure?](#deploy-to-azure)
- [如何觸發並測試功能?](#trigger-and-test)
- [接下來的步驟是什麼?](#next-steps)
!!!--LIBRARY_NUGET_INSTALL_BLOCK--!!!
## 需要哪些先決條件?
在開始之前,確認所有必需的工具已安裝並且Azure訂閱是活躍的。跳過這些檢查往往會導致部屬過程中途的構建失敗。
**需要的本地工具**:
- [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli)(版本2.40或更新版本)
- 啟用了Linux容器的[Docker Desktop](https://www.docker.com/products/docker-desktop/)
- Maven 3.8或更高版本
- JDK 11或JDK 17(JDK 17是推薦的LTS版本)
- [Azure Functions Core Tools](https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local) v4
**需要的Azure資源**:
- 一個活躍的Azure訂閱
- 建立資源組、儲存帳戶和Functions App計劃的權限
- 一個Docker Hub帳戶(或Azure容器註冊表)以託管構建的映像
[[n:(IronPDF for Java在任何Docker容器運行時都需要`ironpdf-engine-linux-x64` 工件。 Azure Functions上的標準Zip部屬無法執行IronPDF的原生二進位文件 - Docker是唯一支持的部屬方法。)]]
在繼續到下一部分之前,運行`az login` 進行Azure CLI身份驗證。
## 如何建立Azure Function專案?
Microsoft為[使用自定義映像在Linux上建立Function](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-function-linux-custom-image)的指南涵蓋了完整的腳手架過程。 按照這些步驟進行,並在提示選擇編程語言時選擇**Java**。
通過指南中的步驟,直到腳手架專案構建完成並使用Azure Functions核心工具本地運行占位符功能。 使用以下指令驗證:
```bash
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/local-run.sh
mvn clean package
func start
```
一旦占位符對本地HTTP請求做出回應,專案結構即正確並已準備好進行IronPDF整合。 關鍵文件是`Dockerfile`(容器定義)。
[[i:(Azure Functions Maven模版生成`host.json` 和 `local.settings.json` 與 `pom.xml` 一起。 `local.settings.json` 文件儲存本地開發的環境變數 - 預設情況下,它未納入版本控制且不應提交。)]]
## 如何將IronPDF依賴新增到Maven專案中?
IronPDF for Java是通過Maven Central發佈的。 需要兩個工件:提供Java API的核心`ironpdf` 程式庫,以及`ironpdf-engine-linux-x64`,它包含針對Linux x86-64編譯的原生Chromium引擎。引擎工件是使Docker部屬成為必需的原因 - 它攜帶必須在運行時執行的二進位文件。
打開`pom.xml` 並在`<dependencies>` 區塊中新增以下內容。 用[Maven Central](https://central.sonatype.com/artifact/com.ironsoftware/ironpdf)上可用的當前版本替換`LATEST_VERSION`:
```xml
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/pom.xml
<dependencies>
<!-- IronPDF Java API -->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>LATEST_VERSION</version>
</dependency>
<!--
Linux x64 engine — required for Docker/Azure Functions.
This artifact bundles the native Chromium renderer for Linux.
-->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf-engine-linux-x64</artifactId>
<version>LATEST_VERSION</version>
</dependency>
</dependencies>
```
兩個工件必須使用相同的版本號。 `ironpdf` 和 `ironpdf-engine-linux-x64` 之間的版本不匹配會在功能首次嘗試渲染PDF時引發運行時異常。
更新`pom.xml` 後,運行`mvn dependency:resolve` 以驗證Maven可以從Central下載兩個工件,然後再投入時間構建Docker映像。
[[t:(查看[IronPDF for Java發佈說明](https://ironpdf.com/java/product-updates/changelog/)以獲取最新穩定版本。 使用最新發佈版可確保與最新Chromium渲染引擎的相容性,並避免已知的錯誤。)]]
## 如何編寫RenderPdf功能?
`RenderPdf` 是一個HTTP觸發的Azure Function,它接受`Content-Disposition: attachment` 標頭的二進位響應返回。 此標頭告訴瀏覽器(或HTTP客戶端)下載PDF而不是內聯顯示。
完整的功能程式碼在上面的快速入門中提供。 將其放置到`src/main/java/com/example/Function.java` 中,替換或擴展Maven模版生成的占位符。
```java
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/RenderPdf-annotated.java
import com.microsoft.azure.functions.*;
import com.ironsoftware.ironpdf.PdfDocument;
import java.util.Optional;
public class Function {
@FunctionName("RenderPdf")
public HttpResponseMessage renderPdf(
@HttpTrigger(
name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
// Log each invocation for Azure Monitor / Application Insights
context.getLogger().info("RenderPdf triggered.");
final String url = request.getQueryParameters().get("url");
// Return 400 if no URL was supplied
if (url == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Provide a 'url' query parameter.")
.build();
}
try {
// renderUrlAsPdf launches Chromium, loads the page, and captures it as PDF
PdfDocument pdf = PdfDocument.renderUrlAsPdf(url);
// getBinaryData returns the raw PDF bytes ready for transmission
byte[] pdfBytes = pdf.getBinaryData();
return request.createResponseBuilder(HttpStatus.OK)
.body(pdfBytes)
.header("Content-Disposition", "attachment; filename=output.pdf")
.header("Content-Type", "application/pdf")
.build();
} catch (Exception ex) {
context.getLogger().severe("Rendering error: " + ex.getMessage());
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body("PDF rendering failed.")
.build();
}
}
}
```
`PdfDocument.renderUrlAsPdf(url)` 在容器內啟動一個無頭的Chromium實例,完全載入目標URL(包括JavaScript),並將渲染的輸出捕獲為PDF。 這會產生與使用者在瀏覽器中看到的視覺上完全一致的輸出,使其適合捕獲現代Web應用、儀表板和報告頁面。
[[n:(功能觸發中的`authLevel = AuthorizationLevel.ANONYMOUS` 設定使端點公開存取。 對於生產部屬,將其更改為`FUNCTION` 或 `ADMIN`,並在請求標頭中傳遞功能密鑰。)]]
## 如何配置IronPDF的Dockerfile?
IronPDF的Chromium引擎依賴於一組不包含在基礎Azure Functions映像中的共享Linux程式庫。 基礎映像`mcr.microsoft.com/azure-functions/java:4-java17-build` 是基於Debian 11建構,因此必須使用`apt` 安裝軟體包。
必須將以下`RUN` 命令新增到Azure Functions Maven模版生成的`Dockerfile`中。 將它們放置在`FROM` 指令之後和新增應用JAR的`COPY` 步驟之前:
```dockerfile
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/Dockerfile
FROM mcr.microsoft.com/azure-functions/java:4-java17-build AS installer-env
# Install system dependencies required by IronPDF's Chromium renderer
RUN apt-get update && apt-get 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 \
&& apt-get install -y xvfb libva-dev libgdiplus \
&& rm -rf /var/lib/apt/lists/*
# Copy the built function JAR
COPY --from=installer-env /home/site/wwwroot /home/site/wwwroot
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
AzureFunctionsJobHost__Logging__Console__IsEnabled=true
```
`libgdiplus` 程式包提供GDI+相容性以進行圖形渲染。 `libnss3` 和 `libatk-bridge2.0-0` 是由Chromium的沙盒和無障礙層所需的。 `xvfb` 提供了一個虛擬幀緩衝區,即使在某些Debian配置的無頭模式下,Chromium也需要。 `rm -rf /var/lib/apt/lists/*` 步驟在`RUN` 區塊的最後刪除包管理器快取,保持最終映像大小盡可能小。
[[i:(如果Azure Functions基礎映像版本更改或使用不同的Linux發行版作為基礎,需要的軟體包可能會有所不同。 請參閱[IronPDF Linux安裝指南](/get-started/linux/)以獲取跨Debian、Ubuntu、CentOS和Alpine的完整依賴矩陣。)]]
## 如何構建並發布Docker映像?
隨著Maven專案構建完成並更新Dockerfile, 容器映像可以被組裝並上傳到Docker註冊表。 當Functions App被建立或更新時,Azure Functions會拉取此映像。
**第一步 - 構建並打包Maven專案**:
```bash
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/build.sh
# Compile the Java code and package it as a JAR
mvn clean package
```
Maven編譯功能程式碼,解析所有依賴(包括IronPDF的兩個工件),並在`target/` 目錄中生成可部署JAR。 在繼續之前修正所有編譯錯誤。
**第二步 - 構建Docker映像**:
```bash
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/docker-build.sh
# Replace <DOCKER_ID> with your Docker Hub username or ACR login server
docker build --tag <DOCKER_ID>/ironpdf-azure-functions:v1.0.0 .
```
構建過程中安裝Dockerfile中列出的Linux包,複製JAR,並將所有層組成最終映像。 首次構建可能需要幾分鐘,因為包下載和層快取需要時間建立。 使用相同基礎映像的後續構建顯著更快。
**第三步 - 將映像推送到Docker Hub**:
```bash
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/docker-push.sh
# Authenticate if not already logged in
docker login
# Push the image to the registry
docker push <DOCKER_ID>/ironpdf-azure-functions:v1.0.0
```
[[t:(Azure Container Registry (ACR) 是私有Docker Hub的替代選項。 ACR直接整合Azure Active Directory,是生產工作負載中重視映像隱私的推薦選擇。)]]
## 如何將功能部署到Azure?
映像在註冊表中後,可以建立(或更新)Azure Functions App來引用它。 `az functionapp create` 命令配置Functions App,將其連結到一個儲存帳戶,並在單一步驟中設置容器映像。
**第一步 - 建立或更新Functions App**:
```bash
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/az-deploy.sh
az functionapp create \
--name <APP_NAME> \
--storage-account <STORAGE_NAME> \
--resource-group AzureFunctionsContainers-rg \
--plan myPremiumPlan \
--deployment-container-image-name <DOCKER_ID>/ironpdf-azure-functions:v1.0.0
```
用`<APP_NAME>` 替換為Functions App的全球唯一名稱,用`<STORAGE_NAME>` 替換為現有的Azure Storage帳戶名稱,`<DOCKER_ID>` 替換為上一步中使用的Docker Hub使用者名或ACR登錄伺服器。
`--plan myPremiumPlan` 標識選擇了一個高級託管方案。 IronPDF的Chromium引擎在渲染期間消耗大量記憶體; 消耗方案1.5 GB的記憶體上限通常是不夠的。 高級方案至少提供3.5 GB,且支援預熱實例以消除冷啟動延遲。
**第二步 - 驗證部署**:
```bash
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/az-verify.sh
# Check that the function app is running and the container has been pulled
az functionapp show \
--name <APP_NAME> \
--resource-group AzureFunctionsContainers-rg \
--query "state"
```
當容器成功啟動時,命令返回`"Running"`。 如果返回`"Starting"` 或報錯,請檢查Azure門戶中Functions App下的Log Stream以查看容器拉取或啟動錯誤。
[[w:(消耗(無伺服器)計劃不建議在Azure Functions上使用IronPDF。 使用Chromium進行PDF渲染需要超過消耗計劃所分配的記憶體。 使用高級或專用(App Service)方案以避免記憶體不足錯誤。)]]
## 如何觸發並測試功能?
一旦Functions App報告`Running` 狀態,`RenderPdf` 端點即可準備接受請求。 端點URL遵循根據Functions App名稱和`@FunctionName` 標註中定義的函式名稱命名的可預測模式。
**使用瀏覽器或curl進行測試**:
```bash
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/test-request.sh
# Replace <APP_NAME> with the Function App name
curl -o output.pdf \
"https://<APP_NAME>.azurewebsites.net/api/RenderPdf?url=https://www.example.com"
```
成功的響應將保存一個名為`output.pdf` 的PDF文件到當前目錄。 curl中的`-o` 標識將二進位響應主體寫入文件而不是列印到終端。
在瀏覽器中測試時,導航至:
`https://<APP_NAME>.azurewebsites.net/api/RenderPdf?url=https://www.example.com`
瀏覽器將提示下載PDF。 打開它以驗證頁面是否正確渲染。
[[n:(冷啟動後的第一次請求可能需要20–60秒,因為Azure會拉取容器映像並且IronPDF初始化Chromium。 在同一容器生命周期內的後續請求速度快得多。 高級方案的預熱實例功能通過持續運行至少一個實例來消除冷啟動。)]]
**檢查錯誤日誌**:導航到Azure門戶,打開Functions App,並在 **監控** 下選擇 **日誌流**。 來自`context.getLogger()` 呼叫的日誌條目會在此處實時顯示,這使得診斷渲染失敗變得簡單明瞭。
## 接下來的步驟是什麼?
本指南演示了如何將IronPDF for Java部屬在Azure Functions Docker容器中,編寫HTTP觸發功能以將URL渲染為PDF,配置包含所需Linux依賴的Dockerfile,並測試在線端點。 相同的模式擴展到更高級的用例,僅需進行最小的更改。
**擴展功能**:
- 使用`PdfDocument.renderHtmlAsPdf(htmlString)` 直接渲染HTML字串而不是URL
- 使用[IronPDF完整的Java PDF API](https://ironpdf.com/java/object-reference/api/)應用水印,合併多個PDF或新增數位簽名
- 讀取請求標頭或POST主體以傳遞自定HTML內容或渲染選項
**提高生產就緒性**:
- 切換`authLevel` 至`FUNCTION`並定期旋轉功能密鑰
- 使用[Azure Key Vault](https://learn.microsoft.com/en-us/azure/key-vault/general/overview)儲存在應用程式設置中引用的所有密鑰
- 配置[應用程式洞察](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview)以全面觀察呈現延遲和失敗率
- 設置[Docker映像更新Webhook](https://learn.microsoft.com/en-us/azure/container-registry/container-registry-tutorial-deploy-update),使Azure在推送新映像版本時自動重新部署
**探索更多IronPDF for Java指南**:
- [IronPDF for Java:Linux安裝指南](/get-started/linux/)
- [在Java中從HTML生成PDF](/java/tutorials/html-to-pdf/)
- [IronPDF for Java:Docker部屬指南](/java/get-started/use-ironpdfengine/)
- [IronPDF Java完整API參考](https://ironpdf.com/java/object-reference/api/)
[開始免費的IronPDF試用](#trial-license),在評估期內存取所有渲染和操作功能而不帶水印。 準備好部署到生產環境時,[查看IronPDF授權選擇](#licensing)以找到適合項目規模的方案。
Ask ChatGPT about this page
Ask Gemini about this page
Ask Perplexity about this page
本指南涵蓋了在Azure Functions容器內部署IronPDF for Java ,並從無伺服器的HTTP端點按需生成PDF的所有步驟。 由於IronPDF搭載了一個原生的Chromium渲染引擎,因此必須打包為Docker映像 - Azure Functions上的標準Zip部屬方法無法在運行時執行IronPDF所依賴的二進位文件。按照本指南進行,一個工作中的Azure Function會接受作為查詢參數的URL並返回完全渲染的PDF作為可下載文件。
此方法使用Microsoft推薦的自定義容器工作流程 適用於基於Linux的Azure Functions。 一個Maven專案提供了功能程式碼和依賴管理。 Docker建構容器映像,然後將其推送到註冊表,並由Azure Function App引用。一旦部署,冷啟動時間是主要的性能考慮——隨後的調用速度快且一致。
在開始之前,請確保Azure CLI 、Docker Desktop、Maven 3.8+ 和 JDK 11 或 JDK 17 已安裝在本地。 還需要一個活躍的Azure訂閱,並有權建立Functions App和儲存帳戶。
下面的程式碼顯示了完整的RenderPdf Azure Function。 它接受url 查詢參數並返回一個PDF位元組流。 在完成接下來各部分的Maven依賴設置後,將其新增到Function.java。
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/RenderPdf.java
import com . microsoft . azure . functions . * ;
import com . ironsoftware . ironpdf . PdfDocument ;
import java . util . Optional ;
public class Function {
/**
* HTTP-triggered Azure Function: accepts a URL, renders it as a PDF,
* and returns the PDF bytes as a downloadable attachment.
*/
@ 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( "RenderPdf function triggered." );
// Read the target URL from the query string
final String url = request.getQueryParameters().get( "url" );
if (url == null ) {
return request.createResponseBuilder( HttpStatus . BAD_REQUEST )
.body( "Provide a 'url' query parameter." )
.build();
}
try {
context.getLogger().info( "Rendering URL as PDF: " + url);
// IronPDF renders the full page including JavaScript
PdfDocument pdf = PdfDocument .renderUrlAsPdf(url);
byte [] pdfBytes = pdf.getBinaryData();
return request.createResponseBuilder( HttpStatus . OK )
.body(pdfBytes)
.header( "Content-Disposition" , "attachment; filename=output.pdf" )
.header( "Content-Type" , "application/pdf" )
.build();
} catch ( Exception ex) {
context.getLogger().severe( "PDF rendering failed: " + ex.getMessage());
return request.createResponseBuilder( HttpStatus . INTERNAL_SERVER_ERROR )
.body( "PDF rendering failed. Check function logs for details." )
.build();
}
}
}
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/RenderPdf.java
import com.microsoft.azure.functions.*;
import com.ironsoftware.ironpdf.PdfDocument;
import java.util.Optional;
public class Function {
/**
* HTTP-triggered Azure Function: accepts a URL, renders it as a PDF,
* and returns the PDF bytes as a downloadable attachment.
*/
@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("RenderPdf function triggered.");
// Read the target URL from the query string
final String url = request.getQueryParameters().get("url");
if (url == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Provide a 'url' query parameter.")
.build();
}
try {
context.getLogger().info("Rendering URL as PDF: " + url);
// IronPDF renders the full page including JavaScript
PdfDocument pdf = PdfDocument.renderUrlAsPdf(url);
byte[] pdfBytes = pdf.getBinaryData();
return request.createResponseBuilder(HttpStatus.OK)
.body(pdfBytes)
.header("Content-Disposition", "attachment; filename=output.pdf")
.header("Content-Type", "application/pdf")
.build();
} catch (Exception ex) {
context.getLogger().severe("PDF rendering failed: " + ex.getMessage());
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body("PDF rendering failed. Check function logs for details.")
.build();
}
}
}
Java
Start using IronPDF in your project today with a free trial.
需要哪些先決條件?
在開始之前,確認所有必需的工具已安裝並且Azure訂閱是活躍的。跳過這些檢查往往會導致部屬過程中途的構建失敗。
需要的本地工具 :
需要的Azure資源 :
一個活躍的Azure訂閱
建立資源組、儲存帳戶和Functions App計劃的權限
一個Docker Hub帳戶(或Azure容器註冊表)以託管構建的映像
IronPDF for Java在任何Docker容器運行時都需要ironpdf-engine-linux-x64 工件。 Azure Functions上的標準Zip部屬無法執行IronPDF的原生二進位文件 - Docker是唯一支持的部屬方法。
在繼續到下一部分之前,運行az login 進行Azure CLI身份驗證。
如何建立Azure Function專案?
Microsoft為使用自定義映像在Linux上建立Function 的指南涵蓋了完整的腳手架過程。 按照這些步驟進行,並在提示選擇編程語言時選擇Java 。
通過指南中的步驟,直到腳手架專案構建完成並使用Azure Functions核心工具本地運行占位符功能。 使用以下指令驗證:
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/local-run.sh
mvn clean package
func start
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/local-run.sh
mvn clean package
func start
SHELL
一旦占位符對本地HTTP請求做出回應,專案結構即正確並已準備好進行IronPDF整合。 關鍵文件是Dockerfile(容器定義)。
Azure Functions Maven模版生成host.json 和 local.settings.json 與 pom.xml 一起。 local.settings.json 文件儲存本地開發的環境變數 - 預設情況下,它未納入版本控制且不應提交。
如何將IronPDF依賴新增到Maven專案中?
IronPDF for Java是通過Maven Central發佈的。 需要兩個工件:提供Java API的核心ironpdf 程式庫,以及ironpdf-engine-linux-x64,它包含針對Linux x86-64編譯的原生Chromium引擎。引擎工件是使Docker部屬成為必需的原因 - 它攜帶必須在運行時執行的二進位文件。
打開pom.xml 並在<dependencies> 區塊中新增以下內容。 用Maven Central 上可用的當前版本替換LATEST_VERSION:
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/pom.xml
<dependencies>
<!-- IronPDF Java API -->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>LATEST_VERSION</version>
</dependency>
<!--
Linux x64 engine — required for Docker/Azure Functions.
This artifact bundles the native Chromium renderer for Linux.
-->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf-engine-linux-x64</artifactId>
<version>LATEST_VERSION</version>
</dependency>
</dependencies>
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/pom.xml
<dependencies>
<!-- IronPDF Java API -->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>LATEST_VERSION</version>
</dependency>
<!--
Linux x64 engine — required for Docker/Azure Functions.
This artifact bundles the native Chromium renderer for Linux.
-->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf-engine-linux-x64</artifactId>
<version>LATEST_VERSION</version>
</dependency>
</dependencies>
XML
兩個工件必須使用相同的版本號。 ironpdf 和 ironpdf-engine-linux-x64 之間的版本不匹配會在功能首次嘗試渲染PDF時引發運行時異常。
更新pom.xml 後,運行mvn dependency:resolve 以驗證Maven可以從Central下載兩個工件,然後再投入時間構建Docker映像。
查看IronPDF for Java發佈說明 以獲取最新穩定版本。 使用最新發佈版可確保與最新Chromium渲染引擎的相容性,並避免已知的錯誤。
如何編寫RenderPdf功能?
RenderPdf 是一個HTTP觸發的Azure Function,它接受Content-Disposition: attachment 標頭的二進位響應返回。 此標頭告訴瀏覽器(或HTTP客戶端)下載PDF而不是內聯顯示。
完整的功能程式碼在上面的快速入門中提供。 將其放置到src/main/java/com/example/Function.java 中,替換或擴展Maven模版生成的占位符。
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/RenderPdf-annotated.java
import com . microsoft . azure . functions . * ;
import com . ironsoftware . ironpdf . PdfDocument ;
import java . util . Optional ;
public class Function {
@ FunctionName ( "RenderPdf" )
public HttpResponseMessage renderPdf(
@ HttpTrigger (
name = "req" ,
methods = { HttpMethod . GET , HttpMethod . POST },
authLevel = AuthorizationLevel . ANONYMOUS )
HttpRequestMessage < Optional < String >> request,
final ExecutionContext context) {
// Log each invocation for Azure Monitor / Application Insights
context.getLogger().info( "RenderPdf triggered." );
final String url = request.getQueryParameters().get( "url" );
// Return 400 if no URL was supplied
if (url == null ) {
return request.createResponseBuilder( HttpStatus . BAD_REQUEST )
.body( "Provide a 'url' query parameter." )
.build();
}
try {
// renderUrlAsPdf launches Chromium, loads the page, and captures it as PDF
PdfDocument pdf = PdfDocument .renderUrlAsPdf(url);
// getBinaryData returns the raw PDF bytes ready for transmission
byte [] pdfBytes = pdf.getBinaryData();
return request.createResponseBuilder( HttpStatus . OK )
.body(pdfBytes)
.header( "Content-Disposition" , "attachment; filename=output.pdf" )
.header( "Content-Type" , "application/pdf" )
.build();
} catch ( Exception ex) {
context.getLogger().severe( "Rendering error: " + ex.getMessage());
return request.createResponseBuilder( HttpStatus . INTERNAL_SERVER_ERROR )
.body( "PDF rendering failed." )
.build();
}
}
}
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/RenderPdf-annotated.java
import com.microsoft.azure.functions.*;
import com.ironsoftware.ironpdf.PdfDocument;
import java.util.Optional;
public class Function {
@FunctionName("RenderPdf")
public HttpResponseMessage renderPdf(
@HttpTrigger(
name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
// Log each invocation for Azure Monitor / Application Insights
context.getLogger().info("RenderPdf triggered.");
final String url = request.getQueryParameters().get("url");
// Return 400 if no URL was supplied
if (url == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Provide a 'url' query parameter.")
.build();
}
try {
// renderUrlAsPdf launches Chromium, loads the page, and captures it as PDF
PdfDocument pdf = PdfDocument.renderUrlAsPdf(url);
// getBinaryData returns the raw PDF bytes ready for transmission
byte[] pdfBytes = pdf.getBinaryData();
return request.createResponseBuilder(HttpStatus.OK)
.body(pdfBytes)
.header("Content-Disposition", "attachment; filename=output.pdf")
.header("Content-Type", "application/pdf")
.build();
} catch (Exception ex) {
context.getLogger().severe("Rendering error: " + ex.getMessage());
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body("PDF rendering failed.")
.build();
}
}
}
Java
PdfDocument.renderUrlAsPdf(url) 在容器內啟動一個無頭的Chromium實例,完全載入目標URL(包括JavaScript),並將渲染的輸出捕獲為PDF。 這會產生與使用者在瀏覽器中看到的視覺上完全一致的輸出,使其適合捕獲現代Web應用、儀表板和報告頁面。
功能觸發中的authLevel = AuthorizationLevel.ANONYMOUS 設定使端點公開存取。 對於生產部屬,將其更改為FUNCTION 或 ADMIN,並在請求標頭中傳遞功能密鑰。
如何配置IronPDF的Dockerfile?
IronPDF的Chromium引擎依賴於一組不包含在基礎Azure Functions映像中的共享Linux程式庫。 基礎映像mcr.microsoft.com/azure-functions/java:4-java17-build 是基於Debian 11建構,因此必須使用apt 安裝軟體包。
必須將以下RUN 命令新增到Azure Functions Maven模版生成的Dockerfile中。 將它們放置在FROM 指令之後和新增應用JAR的COPY 步驟之前:
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/Dockerfile
FROM mcr.microsoft.com/azure-functions/java:4-java17-build AS installer-env
# Install system dependencies required by IronPDF's Chromium renderer
RUN apt-get update && apt-get 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 \
&& apt-get install -y xvfb libva-dev libgdiplus \
&& rm -rf /var/lib/apt/lists/*
# Copy the built function JAR
COPY --from=installer-env /home/site/wwwroot /home/site/wwwroot
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
AzureFunctionsJobHost__Logging__Console__IsEnabled=true
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/Dockerfile
FROM mcr.microsoft.com/azure-functions/java:4-java17-build AS installer-env
# Install system dependencies required by IronPDF's Chromium renderer
RUN apt-get update && apt-get 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 \
&& apt-get install -y xvfb libva-dev libgdiplus \
&& rm -rf /var/lib/apt/lists/*
# Copy the built function JAR
COPY --from=installer-env /home/site/wwwroot /home/site/wwwroot
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
AzureFunctionsJobHost__Logging__Console__IsEnabled=true
Text
libgdiplus 程式包提供GDI+相容性以進行圖形渲染。 libnss3 和 libatk-bridge2.0-0 是由Chromium的沙盒和無障礙層所需的。 xvfb 提供了一個虛擬幀緩衝區,即使在某些Debian配置的無頭模式下,Chromium也需要。 rm -rf /var/lib/apt/lists/* 步驟在RUN 區塊的最後刪除包管理器快取,保持最終映像大小盡可能小。
如果Azure Functions基礎映像版本更改或使用不同的Linux發行版作為基礎,需要的軟體包可能會有所不同。 請參閱IronPDF Linux安裝指南 以獲取跨Debian、Ubuntu、CentOS和Alpine的完整依賴矩陣。
如何構建並發布Docker映像?
隨著Maven專案構建完成並更新Dockerfile, 容器映像可以被組裝並上傳到Docker註冊表。 當Functions App被建立或更新時,Azure Functions會拉取此映像。
第一步 - 構建並打包Maven專案 :
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/build.sh
# Compile the Java code and package it as a JAR
mvn clean package
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/build.sh
# Compile the Java code and package it as a JAR
mvn clean package
SHELL
Maven編譯功能程式碼,解析所有依賴(包括IronPDF的兩個工件),並在target/ 目錄中生成可部署JAR。 在繼續之前修正所有編譯錯誤。
第二步 - 構建Docker映像 :
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/docker-build.sh
# Replace <DOCKER_ID> with your Docker Hub username or ACR login server
docker build --tag <DOCKER_ID>/ironpdf-azure-functions:v1.0.0 .
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/docker-build.sh
# Replace <DOCKER_ID> with your Docker Hub username or ACR login server
docker build --tag <DOCKER_ID>/ironpdf-azure-functions:v1.0.0 .
SHELL
構建過程中安裝Dockerfile中列出的Linux包,複製JAR,並將所有層組成最終映像。 首次構建可能需要幾分鐘,因為包下載和層快取需要時間建立。 使用相同基礎映像的後續構建顯著更快。
第三步 - 將映像推送到Docker Hub :
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/docker-push.sh
# Authenticate if not already logged in
docker login
# Push the image to the registry
docker push <DOCKER_ID>/ironpdf-azure-functions:v1.0.0
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/docker-push.sh
# Authenticate if not already logged in
docker login
# Push the image to the registry
docker push <DOCKER_ID>/ironpdf-azure-functions:v1.0.0
SHELL
Azure Container Registry (ACR) 是私有Docker Hub的替代選項。 ACR直接整合Azure Active Directory,是生產工作負載中重視映像隱私的推薦選擇。
如何將功能部署到Azure?
映像在註冊表中後,可以建立(或更新)Azure Functions App來引用它。 az functionapp create 命令配置Functions App,將其連結到一個儲存帳戶,並在單一步驟中設置容器映像。
第一步 - 建立或更新Functions App :
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/az-deploy.sh
az functionapp create \
--name <APP_NAME> \
--storage-account <STORAGE_NAME> \
--resource-group AzureFunctionsContainers-rg \
--plan myPremiumPlan \
--deployment-container-image-name <DOCKER_ID>/ironpdf-azure-functions:v1.0.0
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/az-deploy.sh
az functionapp create \
--name <APP_NAME> \
--storage-account <STORAGE_NAME> \
--resource-group AzureFunctionsContainers-rg \
--plan myPremiumPlan \
--deployment-container-image-name <DOCKER_ID>/ironpdf-azure-functions:v1.0.0
SHELL
用<APP_NAME> 替換為Functions App的全球唯一名稱,用<STORAGE_NAME> 替換為現有的Azure Storage帳戶名稱,<DOCKER_ID> 替換為上一步中使用的Docker Hub使用者名或ACR登錄伺服器。
--plan myPremiumPlan 標識選擇了一個高級託管方案。 IronPDF的Chromium引擎在渲染期間消耗大量記憶體; 消耗方案1.5 GB的記憶體上限通常是不夠的。 高級方案至少提供3.5 GB,且支援預熱實例以消除冷啟動延遲。
第二步 - 驗證部署 :
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/az-verify.sh
# Check that the function app is running and the container has been pulled
az functionapp show \
--name <APP_NAME> \
--resource-group AzureFunctionsContainers-rg \
--query "state"
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/az-verify.sh
# Check that the function app is running and the container has been pulled
az functionapp show \
--name <APP_NAME> \
--resource-group AzureFunctionsContainers-rg \
--query "state"
SHELL
當容器成功啟動時,命令返回"Running"。 如果返回"Starting" 或報錯,請檢查Azure門戶中Functions App下的Log Stream以查看容器拉取或啟動錯誤。
消耗(無伺服器)計劃不建議在Azure Functions上使用IronPDF。 使用Chromium進行PDF渲染需要超過消耗計劃所分配的記憶體。 使用高級或專用(App Service)方案以避免記憶體不足錯誤。
如何觸發並測試功能?
一旦Functions App報告Running 狀態,RenderPdf 端點即可準備接受請求。 端點URL遵循根據Functions App名稱和@FunctionName 標註中定義的函式名稱命名的可預測模式。
使用瀏覽器或curl進行測試 :
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/test-request.sh
# Replace <APP_NAME> with the Function App name
curl -o output.pdf \
"https://<APP_NAME>.azurewebsites.net/api/RenderPdf?url=https://www.example.com"
//:path=/static-assets/pdf/content-code-examples/tutorials/azure/test-request.sh
# Replace <APP_NAME> with the Function App name
curl -o output.pdf \
"https://<APP_NAME>.azurewebsites.net/api/RenderPdf?url=https://www.example.com"
SHELL
成功的響應將保存一個名為output.pdf 的PDF文件到當前目錄。 curl中的-o 標識將二進位響應主體寫入文件而不是列印到終端。
在瀏覽器中測試時,導航至:
https://<APP_NAME>.azurewebsites.net/api/RenderPdf?url=https://www.example.com
瀏覽器將提示下載PDF。 打開它以驗證頁面是否正確渲染。
冷啟動後的第一次請求可能需要20–60秒,因為Azure會拉取容器映像並且IronPDF初始化Chromium。 在同一容器生命周期內的後續請求速度快得多。 高級方案的預熱實例功能通過持續運行至少一個實例來消除冷啟動。
檢查錯誤日誌 :導航到Azure門戶,打開Functions App,並在 監控 下選擇 日誌流 。 來自context.getLogger() 呼叫的日誌條目會在此處實時顯示,這使得診斷渲染失敗變得簡單明瞭。
接下來的步驟是什麼?
本指南演示了如何將IronPDF for Java部屬在Azure Functions Docker容器中,編寫HTTP觸發功能以將URL渲染為PDF,配置包含所需Linux依賴的Dockerfile,並測試在線端點。 相同的模式擴展到更高級的用例,僅需進行最小的更改。
擴展功能 :
使用PdfDocument.renderHtmlAsPdf(htmlString) 直接渲染HTML字串而不是URL
使用IronPDF完整的Java PDF API 應用水印,合併多個PDF或新增數位簽名
讀取請求標頭或POST主體以傳遞自定HTML內容或渲染選項
提高生產就緒性 :
探索更多IronPDF for Java指南 :
開始免費的IronPDF試用 ,在評估期內存取所有渲染和操作功能而不帶水印。 準備好部署到生產環境時,查看IronPDF授權選擇 以找到適合項目規模的方案。
常見問題 IronPDF 附帶一個本地 Chromium 渲染引擎,必須在運行時執行二進制文件。Azure Functions Zip 部署無法運行本地二進制文件,因此 Docker 集裝箱映像是唯一支持的部署路徑。
需要在 pom.xml 中的兩個工件:com.ironsoftware:ironpdf 用於 Java API 和 com.ironsoftware:ironpdf-engine-linux-x64 用於本地下層 Chromium 引擎。兩者必須共享相同的版本號。
The Dockerfile must install 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, xvfb, and libva-dev.
RenderPdf 函式是一個 HTTP 觸發的 Azure Function。它讀取 url 查詢參數,將其傳遞給 PdfDocument.renderUrlAsPdf,並返回帶有 Content-Disposition: attachment 標頭的 PDF 字節,使呼叫者獲得一個可下載的 PDF 文件。
建議使用高級計劃。IronPDF 的 Chromium 引擎需要大量記憶體,通常超過消耗計劃的 1.5 GB 上限。高級計劃至少提供 3.5 GB 並支持預熱實例以消除冷啟動延遲。
冷啟動後的第一次請求可能需要 20–60 秒,因為 Azure 必須提取容器映像,而且 IronPDF 必須初始化其 Chromium 引擎。在同一容器生命周期內的後續請求速度要快得多。高級計劃的預熱實例功能可以消除此延遲。
通過更新標籤重建並推送新映像,然後使用新的 --deployment-container-image-name 值再次運行 az functionapp create,或者在 Azure 入口網站的 Function App 部署中心中更新容器設置。
可以。將 PdfDocument.renderUrlAsPdf(url) 替換為 PdfDocument.renderHtmlAsPdf(htmlString) 以直接渲染 HTML 字串。函式結構和響應處理保持不變。
該函式會檢查 url 參數是否為 null,並在嘗試任何 PDF 渲染之前返回描述性消息的 HTTP 400 錯誤請求響應。
技術作家
Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。
...
閱讀更多