在Azure Function上如何使用C#將HTML轉換為PDF與IronPDF
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方法將URL呈現為PDF文件。 此範例展示了IronPDF在Azure解決方案中整合PDF功能的簡單性。 遵循該範例開始生成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。
更多高級安裝選項,請查看我們的NuGet 套件指南。
我需要配置哪些Azure選項?
應該選擇哪個Azure託管級別?
Azure Basic B1 是渲染所需的最低託管級別。 如果您正在建立一個高吞吐量系統,可能需要升級。 B1級別為支持IronPDF的HTML到PDF轉換的Chrome PDF渲染引擎提供了足夠的資源。
為什麼我要取消勾選"從軟體包文件運行"?
發佈Azure Functions應用程式時,確保Run from package file 未被選取。 此選項會建立一個只讀部署,防止IronPDF在執行期間提取必要的運行時依賴項。
如何為.NET 6配置?
Microsoft最近從.NET 6+中移除了成像程式庫,破壞了許多舊版API。因此,必須配置您的專案以允許這些舊版API調用。
- 在Linux上,設置
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?
獲得控制、SVG字型存取以及控制Azure上性能的方式之一是在Docker容器中使用IronPDF應用程式和功能。 這種方法提供了對運行環境的更好控制,並消除了許多特定平台的限制。
我們有一個全面的IronPDF Azure Docker教程,適用於Linux和Windows實例,推薦閱讀。
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
<FunctionName("RenderHtmlWithCss")>
Public Shared 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
關於在Azure Functions中管理許可證,請參考我們的使用許可證金鑰文件。
有哪些已知問題?
為什麼SVG字體在共享託管計劃上無法呈現?
一個限制是Azure託管平台概述不支持在其更便宜的共享網頁應用程式層中載入SVG字體,如Google字體。 這是由於安全限制阻止存取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建立工程支援請求指南。
生產環境的最佳實踐
- 始終使用適當的託管級別 -
B1或更高,以獲得可靠的性能 - 適當配置日誌 - 使用Azure應用程式分析進行生產監控
- 優雅地處理例外 - 為瞬時故障實現重試邏輯
- 優化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環境進行優化,並提供全面的PDF生成功能和Chrome渲染引擎。
如何在Azure Functions中將HTML轉換為PDF?
您可以使用IronPDF的ChromePdfRenderer以單行程式碼將HTML轉換為PDF。只需建立新實例,並調用RenderHtmlAsPdf()傳入您的HTML內容,然後保存生成的PDF檔案。
如果我沒有選擇正確的App Service Plan會發生什麼情況?
未選擇App Service Plan型別可能導致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生成需求。

