如何在 Azure Function 上使用 IronPDF 透過 C# 將 HTML 轉換為 PDF
IronPDF 可在 Azure 平台上(包括 MVC 網站和 Azure Functions)生成、處理及讀取 PDF 文件。 本指南說明如何在 Azure Functions 中實作 HTML 轉 PDF 功能,並針對生產環境進行適當的配置與優化。
若您是在 Docker 容器中執行 Azure Functions,請改為參閱這份 Azure Docker Linux 教學指南。
快速入門:在 Azure 上使用 IronPDF 進行 HTML 轉 PDF 轉換
立即在您的 Azure 應用程式中使用 IronPDF 將 HTML 轉換為 PDF。 本快速指南將示範如何使用 IronPDF 的 API 方法,將網址渲染為 PDF 文件。 此範例展示了 IronPDF 如何輕鬆地將 PDF 功能整合至 Azure 解決方案中。 請參照範例,開始生成不失格式的 PDF 檔案,並快速讓您的 Azure 專案上線運作。
簡化工作流程(5 個步驟)
- 安裝 C# 函式庫以在 Azure 中產生 PDF 檔案
- 請選擇 Azure Basic B1 或更高階的託管層級
- 發佈時請取消勾選"
從套件檔案執行"選項 - 請遵循建議的設定說明
- 使用程式碼範例透過 Azure 建立 PDF 產生器
操作教學
如何設定我的專案?
我應該安裝哪個 IronPDF 套件?
第一步是使用 NuGet 安裝 IronPDF:
- 在基於 Windows 的 Azure Functions 上,請使用
IronPdf套件 - 適用於 Windows 的 NuGet IronPDF 套件 - 在基於 Linux 的 Azure Functions 上,請使用
IronPdf.Linux套件 - 適用於 Linux 的 NuGet IronPDF 套件
Install-Package IronPdf
或者,您也可以透過"IronPDF 適用於 Azure 的直接下載套件"連結,手動安裝 .dll 檔案。
我需要設定哪些 Azure 選項?
我該選擇哪個 Azure 託管層級?
Azure Basic B1 是滿足渲染需求所需的最低託管層級。 若您正在建置高吞吐量系統,可能需要進行升級。 B1 級別為 Chrome PDF 渲染引擎提供了充足的資源,該引擎驅動著 IronPDF 的 HTML 轉 PDF 轉換功能。
為什麼應該取消勾選"從套件檔案執行"?
發佈您的 Azure Functions 應用程式時,請確保未選取 Run from package file。 此選項會建立一個唯讀部署,防止 IronPDF 在執行期間提取必要的執行時依賴項。
如何設定 .NET 6?
微軟近期已從 .NET 6+ 中移除影像處理函式庫,導致許多舊版 API 無法運作。因此,您必須設定專案,以確保仍能呼叫這些舊版 API。
- 在 Linux 系統上,請設定
Installation.LinuxAndDockerDependenciesAutoConfig=true;以確保libgdiplus已安裝於該機器上 - 請將以下內容新增至您的 .NET 6 專案中的
.csproj檔案中:<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles><GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>XML -
在您的專案中建立一個名為
runtimeconfig.template.json的檔案,並填入以下內容:{ "configProperties": { "System.Drawing.EnableUnixSupport": true } } - 最後,請在程式開頭加入以下這行,以啟用
System.Drawing的 Unix 支援:System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", True)$vbLabelText $csharpLabel
何時應在 Azure 上使用 Docker?
要在 Azure 上取得控制權、存取 SVG 字型以及掌控效能,其中一種方法是在 Docker 容器內使用 IronPDF 應用程式與 Functions。 此方法能提供對執行環境的更好控制,並消除許多平台特定的限制。
我們提供一份針對 Linux 和 Windows 執行個體的完整 IronPDF Azure Docker 教學指南,建議您閱讀。
Azure Function 的程式碼長什麼樣子?
此範例會自動將日誌條目輸出至內建的 Azure 日誌記錄器(參見 ILogger log)。 有關詳細的記錄設定,請參閱我們的《自訂記錄指南》。
[FunctionName("PrintPdf")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log, ExecutionContext context)
{
log.LogInformation("Entered PrintPdf API function...");
// Apply license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Configure logging
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.Custom;
IronPdf.Logging.Logger.CustomLogger = log;
IronPdf.Logging.Logger.EnableDebugging = false;
// Configure IronPdf settings
Installation.LinuxAndDockerDependenciesAutoConfig = false;
Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
try
{
log.LogInformation("About to render pdf...");
// Create a renderer and render the URL as PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.google.com/");
log.LogInformation("Finished rendering pdf...");
// Return the rendered PDF as a file download
return new FileContentResult(pdf.BinaryData, "application/pdf") { FileDownloadName = "google.pdf" };
}
catch (Exception e)
{
log.LogError(e, "Error while rendering pdf");
}
return new OkObjectResult("OK");
}
[FunctionName("PrintPdf")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log, ExecutionContext context)
{
log.LogInformation("Entered PrintPdf API function...");
// Apply license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Configure logging
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.Custom;
IronPdf.Logging.Logger.CustomLogger = log;
IronPdf.Logging.Logger.EnableDebugging = false;
// Configure IronPdf settings
Installation.LinuxAndDockerDependenciesAutoConfig = false;
Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
try
{
log.LogInformation("About to render pdf...");
// Create a renderer and render the URL as PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.google.com/");
log.LogInformation("Finished rendering pdf...");
// Return the rendered PDF as a file download
return new FileContentResult(pdf.BinaryData, "application/pdf") { FileDownloadName = "google.pdf" };
}
catch (Exception e)
{
log.LogError(e, "Error while rendering pdf");
}
return new OkObjectResult("OK");
}
<FunctionName("PrintPdf")>
Public Shared Async Function Run(<HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route := Nothing)> ByVal req As HttpRequest, ByVal log As ILogger, ByVal context As ExecutionContext) As Task(Of IActionResult)
log.LogInformation("Entered PrintPdf API function...")
' Apply license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
' Configure logging
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.Custom
IronPdf.Logging.Logger.CustomLogger = log
IronPdf.Logging.Logger.EnableDebugging = False
' Configure IronPdf settings
Installation.LinuxAndDockerDependenciesAutoConfig = False
Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
Try
log.LogInformation("About to render pdf...")
' Create a renderer and render the URL as PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.google.com/")
log.LogInformation("Finished rendering pdf...")
' Return the rendered PDF as a file download
Return New FileContentResult(pdf.BinaryData, "application/pdf") With {.FileDownloadName = "google.pdf"}
Catch e As Exception
log.LogError(e, "Error while rendering pdf")
End Try
Return New OkObjectResult("OK")
End Function
進階 HTML 字串渲染範例
若涉及包含 CSS 樣式的自訂 HTML 等較複雜的情境,您可以使用 HTML 字串轉 PDF 功能:
[FunctionName("RenderHtmlWithCss")]
public static async Task<IActionResult> RenderHtmlWithCss(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("Processing HTML to PDF request");
// Read HTML content from request body
string htmlContent = await new StreamReader(req.Body).ReadToEndAsync();
// Configure renderer with custom options
var renderer = new ChromePdfRenderer()
{
RenderingOptions = new ChromePdfRenderOptions()
{
MarginTop = 20,
MarginBottom = 20,
MarginLeft = 10,
MarginRight = 10,
CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
}
};
try
{
// Add custom CSS
string styledHtml = $@"
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 20px; }}
h1 {{ color: #2c3e50; }}
.highlight {{ background-color: #f1c40f; padding: 5px; }}
</style>
</head>
<body>
{htmlContent}
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(styledHtml);
return new FileContentResult(pdf.BinaryData, "application/pdf")
{
FileDownloadName = "styled-document.pdf"
};
}
catch (Exception ex)
{
log.LogError(ex, "Failed to render HTML to PDF");
return new BadRequestObjectResult("Error processing HTML content");
}
}
[FunctionName("RenderHtmlWithCss")]
public static async Task<IActionResult> RenderHtmlWithCss(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("Processing HTML to PDF request");
// Read HTML content from request body
string htmlContent = await new StreamReader(req.Body).ReadToEndAsync();
// Configure renderer with custom options
var renderer = new ChromePdfRenderer()
{
RenderingOptions = new ChromePdfRenderOptions()
{
MarginTop = 20,
MarginBottom = 20,
MarginLeft = 10,
MarginRight = 10,
CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
}
};
try
{
// Add custom CSS
string styledHtml = $@"
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 20px; }}
h1 {{ color: #2c3e50; }}
.highlight {{ background-color: #f1c40f; padding: 5px; }}
</style>
</head>
<body>
{htmlContent}
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(styledHtml);
return new FileContentResult(pdf.BinaryData, "application/pdf")
{
FileDownloadName = "styled-document.pdf"
};
}
catch (Exception ex)
{
log.LogError(ex, "Failed to render HTML to PDF");
return new BadRequestObjectResult("Error processing HTML content");
}
}
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Azure.WebJobs
Imports Microsoft.Azure.WebJobs.Extensions.Http
Imports Microsoft.AspNetCore.Http
Imports Microsoft.Extensions.Logging
Imports IronPdf
Public Module HtmlToPdfFunction
<FunctionName("RenderHtmlWithCss")>
Public Async Function RenderHtmlWithCss(
<HttpTrigger(AuthorizationLevel.Function, "post", Route:=Nothing)> req As HttpRequest,
log As ILogger) As Task(Of IActionResult)
log.LogInformation("Processing HTML to PDF request")
' Read HTML content from request body
Dim htmlContent As String = Await New StreamReader(req.Body).ReadToEndAsync()
' Configure renderer with custom options
Dim renderer As New ChromePdfRenderer() With {
.RenderingOptions = New ChromePdfRenderOptions() With {
.MarginTop = 20,
.MarginBottom = 20,
.MarginLeft = 10,
.MarginRight = 10,
.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print,
.PrintHtmlBackgrounds = True,
.CreatePdfFormsFromHtml = True
}
}
Try
' Add custom CSS
Dim styledHtml As String = $"
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; padding: 20px; }}
h1 {{ color: #2c3e50; }}
.highlight {{ background-color: #f1c40f; padding: 5px; }}
</style>
</head>
<body>
{htmlContent}
</body>
</html>"
Dim pdf = renderer.RenderHtmlAsPdf(styledHtml)
Return New FileContentResult(pdf.BinaryData, "application/pdf") With {
.FileDownloadName = "styled-document.pdf"
}
Catch ex As Exception
log.LogError(ex, "Failed to render HTML to PDF")
Return New BadRequestObjectResult("Error processing HTML content")
End Try
End Function
End Module
若要管理 Azure Functions 中的授權,請參閱我們的《使用授權金鑰》文件。
有哪些已知問題?
為什麼 SVG 字型在共享主機方案上無法顯示?
需注意的一點是,Azure 託管平台的概覽指出,其較低價位的共享 Web 應用程式層級不支援伺服器載入 SVG 字型(例如 Google Fonts)。 這是因為安全限制阻擋了對 Windows GDI+ 圖形物件的存取。
若需最佳字型渲染效果,建議使用 Windows 或 Linux 的 IronPDF Docker 容器指南,或考慮在 Azure 上架設 VPS 來解決此問題。
為什麼 Azure 免費方案的託管速度很慢?
Azure 的免費與共享層級,以及用量方案,均不適用於 PDF 渲染。 我們推薦 Azure B1 託管/Premium 方案,這也是我們自己使用的方案。 HTML to PDF 的處理過程對任何電腦而言都是一項重大的"工作"——類似於在您自己的電腦上開啟並渲染網頁。由於採用了真正的瀏覽器引擎,因此我們需要進行相應的資源配置,並預期其渲染時間與同等效能的桌面電腦相仿。
如何在本地端除錯 Azure Functions?
關於本地開發與測試,請參閱我們的《在本地電腦上除錯 Azure Functions 專案》指南。 這有助於您在部署至 Azure 之前識別並解決問題。
我該去哪裡查找 Azure 日誌?
在排除 PDF 生成問題時,Azure 日誌具有極高的參考價值。 請參閱我們的 Azure 日誌檔案指南,了解如何存取及解讀 IronPDF 運作相關的特定日誌。
如何建立工程支援請求?
如需建立支援請求單,請參閱《如何為 IronPDF 提交工程支援請求》指南。
生產環境的最佳實踐
- 請務必選用適當的託管方案 -
B1或更高階方案,以確保效能穩定 - 正確設定記錄功能 - 使用 Azure Application Insights 進行生產環境監控
- 優雅地處理例外狀況 - 針對暫時性失敗實作重試邏輯
- 優化 HTML 內容 - 盡可能減少外部資源,並在可行時使用 base64 編碼的圖片
- 徹底測試 - 在部署至 Azure 之前,請先在本地端驗證 PDF 生成功能
- 監控資源使用狀況 - 追蹤記憶體與 CPU 消耗量,以進行適當的擴展
常見問題
PDF 生成所需的 Azure 託管層級最低為哪一級?
IronPDF 要求至少使用 Azure Basic B1 層級,以滿足 PDF 渲染需求。B1 層級可提供充足資源,以支援驅動 IronPDF HTML 轉 PDF 轉換功能的 Chrome PDF 渲染引擎。
針對基於 Windows 的 Azure Functions,我應該安裝哪個套件?
對於基於 Windows 的 Azure Functions,請從 NuGet 安裝 IronPdf 套件。此套件針對 Windows 環境進行了優化,並透過 Chrome 渲染引擎提供完整的 PDF 生成功能。
如何在 Azure Functions 中將 HTML 轉換為 PDF?
您只需一行程式碼,即可透過 IronPDF 的 ChromePdfRenderer 將 HTML 轉換為 PDF。只需建立一個新實例,並傳入您的 HTML 內容呼叫 RenderHtmlAsPdf() 方法,接著儲存生成的 PDF 檔案即可。
如果我沒有選擇正確的 App Service 方案會怎麼樣?
若未選擇「App 服務方案」作為方案類型,可能會導致 IronPDF 無法渲染 PDF 文件。正確配置 Azure 託管環境對於 PDF 渲染引擎的正常運作至關重要。
為何發佈時必須取消勾選「從套件檔案執行」?
發佈 Azure Functions 應用程式時,必須取消勾選「從套件檔案執行」選項,以確保 IronPDF 能在 Azure 環境中正確存取並使用其渲染元件及依賴項。
我可以使用基於 Linux 的 Azure Functions 來生成 PDF 嗎?
是的,針對基於 Linux 的 Azure Functions,請使用 NuGet 中的 IronPdf.Linux 套件。此套件專為 Linux 環境進行優化,同時提供相同的 PDF 生成功能。
如果我需要更高的 PDF 生成吞吐量該怎麼辦?
對於高吞吐量系統,您可能需要升級至 B1 層級以上的方案。IronPDF 可隨您的 Azure 資源擴展,讓您透過選擇更高效能的層級來處理日益增加的 PDF 生成需求。

