如何在 Azure 函數中使用 C# 和IronPDF實現 HTML轉PDF
IronPDF可在 Azure 平台(包括 MVC 網站和 Azure Functions)上產生、操作和讀取 PDF 文件。 本指南展示如何在 Azure Functions 中實現 HTML 到 PDF 的轉換,並針對生產環境進行適當的配置和最佳化。
如果您在 Docker 容器中執行 Azure Functions,請參考此 Azure Docker Linux 教學課程。
快速入門:使用 Azure 上的IronPDF將 HTML 轉換為 PDF
使用IronPDF在 Azure 應用程式中開始將 HTML 轉換為 PDF。 本快速指南示範如何使用 IronPDF 的 API 方法將 URL 渲染為 PDF 文件。 此範例展示了IronPDF在將 PDF 功能整合到 Azure 解決方案方面的簡易性。 依照範例操作,即可開始產生 PDF 檔案而不會遺失格式,並快速啟動您的 Azure 專案。
最簡工作流程(5個步驟)
- 安裝 C# 庫以在 Azure 中產生 PDF 文件
- 選擇 Azure 基本 B1 託管層或更高版本
- 發佈時取消勾選`Run from package file`選項
- 請按照建議的配置說明進行操作
- 使用程式碼範例,透過 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 檔案。
如需了解更多進階安裝選項,請查看我們全面的NuGet套件指南。
我需要配置哪些 Azure 選項?
我應該選擇哪個 Azure 託管層級?
Azure Basic B1是滿足渲染需求所需的最低託管等級。 如果您正在建置高吞吐量系統,則可能需要對其進行升級。 B1 層為 IronPDF 的 HTML 到 PDF 轉換所支援的Chrome 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 } } - 最後,在程式開頭新增以下程式碼行,以啟用 Unix 對 System.Drawing 的支援:
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應用程式和函數。 這種方法可以更好地控制運行時環境,並消除許多特定於平台的限制。
我們有針對 Linux 和 Windows 實例的IronPDF Azure Docker 全面教程,建議您閱讀。
Azure 函數程式碼是什麼樣的?
此範例會自動將日誌條目輸出至內建的 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 字串渲染範例
對於涉及自訂 HTML 和 CSS 樣式的更複雜場景,您可以使用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+ 圖形物件的存取。
我們建議使用適用於IronPDF的 Windows 或 Linux Docker 容器指南,或使用 Azure 上的 VPS 來解決需要最佳字體渲染的問題。
為什麼 Azure 免費方案託管速度慢?
Azure 免費層和共用層以及按需付費方案不適合 PDF 渲染。 我們推薦 Azure B1 主機/進階套餐,這也是我們自己使用的套餐。 對於任何計算機來說,處理 HTML to PDF 的過程都是一項相當大的"工作",類似於在您自己的計算機上打開並渲染網頁。它使用了真正的瀏覽器引擎,因此我們需要相應地進行配置,並預期渲染時間與同等效能的桌上型電腦類似。
如何在本機上偵錯 Azure Functions?
對於本機開發和測試,請參閱我們的 《在本機電腦上偵錯 Azure Functions 專案》指南。 這有助於您在部署到 Azure 之前識別和解決問題。
我可以在哪裡找到 Azure 日誌?
在排查 PDF 產生問題時,Azure 日誌非常寶貴。 請查看我們的Azure 日誌檔案指南,以了解有關存取和解釋IronPDF操作特定日誌的說明。
如何建立工程支援請求?
若要建立請求單,請參閱IronPDF工程支援請求指南。
生產最佳實踐
1.請務必使用適當的託管等級(B1 或更高)以確保效能可靠
2.正確設定日誌記錄- 使用 Azure Application Insights 進行生產環境監控
3.妥善處理異常-針對暫時性故障實現重試邏輯
4.優化 HTML 內容-盡可能減少外部資源的使用,並盡可能使用 base64 編碼的圖片。
5.全面測試- 在 Azure 部署之前,先在本機上驗證 PDF 產生功能。
6.監控資源使用情況-追蹤記憶體和 CPU 消耗情況,以便進行適當的資源調配。
常見問題解答
生成 PDF 所需的最低 Azure 主機層級是什麼?
IronPDF 需要 Azure Basic B1 層作為滿足 PDF 渲染需求的最低託管層級。B1 層級可為 Chrome PDF 渲染引擎提供足夠的資源,該引擎為 IronPDF 的 HTML 至 PDF 轉換功能提供動力。
基於 Windows 的 Azure Functions 應該安裝哪個套件?
對於基於 Windows 的 Azure 函式,請從 NuGet 安裝 IronPDF 套件。此套件已針對 Windows 環境進行最佳化,並利用 Chrome 渲染引擎提供完整的 PDF 生成功能。
如何在 Azure Functions 中將 HTML 轉換為 PDF?
使用 IronPDF 的 ChromePdfRenderer,只需一行代碼即可將 HTML 轉換為 PDF。只需建立一個新的實例,並使用您的 HTML 內容呼叫 RenderHtmlAsPdf(),然後儲存所產生的 PDF 檔案。
如果我沒有選擇正確的 App 服務計畫會如何?
如果未選擇 App 服務計劃的計劃類型,可能會導致 IronPDF 無法渲染 PDF 文件。Azure 主機環境的適當配置對 PDF 渲染引擎的正常運作至關重要。
為什麼出版時必須取消勾選「從套件檔案執行」?
在發佈您的 Azure Functions 應用程式時,必須取消勾選「從套件檔案執行」,以確保 IronPDF 能夠在 Azure 環境中正確存取和使用其渲染元件與相依性。
我可以使用基於 Linux 的 Azure 函式來產生 PDF 嗎?
是的,對於基於 Linux 的 Azure Functions,請使用 NuGet 的 IronPDF.Linux 套件。此套件專為 Linux 環境最佳化,同時提供相同的 PDF 生成功能。
如果我需要更高的 PDF 生成吞吐量,該怎麼辦?
對於高吞吐量系統,您可能需要升級至 B1 層以上。IronPDF 可根據您的 Azure 資源進行擴展,讓您可以透過選擇更高的效能層級來處理增加的 PDF 生成需求。

