如何在Azure中使用.NET生成HTML到PDF

在Azure Function上如何使用C#將HTML轉換為PDF與IronPDF

This article was translated from English: Does it need improvement?
Translated
View the article in English

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專案。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 複製並運行這段程式碼片段。

    var pdf = new IronPdf.ChromePdfRenderer()
        .RenderHtmlAsPdf("<h1>Hello Azure!</h1>")
        .SaveAs("output-azure.pdf");
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPDF,透過免費試用

    arrow pointer

如何操作教程

我如何設置我的項目?

應該安裝哪個IronPDF套件?

第一步是使用NuGet安裝IronPDF:

Install-Package IronPdf

或者,通過使用IronPDF直接下載套件的Azure連結手動安裝.dll。

更多高級安裝選項,請查看我們的NuGet 套件指南

我需要配置哪些Azure選項?

應該選擇哪個Azure託管級別?

Azure Basic B1 是渲染所需的最低託管級別。 如果您正在建立一個高吞吐量系統,可能需要升級。 B1級別為支持IronPDF的HTML到PDF轉換的Chrome PDF渲染引擎提供了足夠的資源。

警告未能選擇應用服務計劃作為計劃型別可能會導致IronPDF無法渲染PDF文件。

Azure Function App建立表單,其中計劃型別下拉選單高亮顯示應用服務計劃選項

為什麼我要取消勾選"從軟體包文件運行"?

發佈Azure Functions應用程式時,確保Run from package file 未被選取。 此選項會建立一個只讀部署,防止IronPDF在執行期間提取必要的運行時依賴項。

Azure Functions發佈對話框顯示未勾選的"從軟體包文件運行(推薦)"選項

如何為.NET 6配置?

Microsoft最近從.NET 6+中移除了成像程式庫,破壞了許多舊版API。因此,必須配置您的專案以允許這些舊版API調用。

  1. 在Linux上,設置libgdiplus
  2. 將以下內容新增到您的.NET 6專案的.csproj文件中:
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    XML
  3. 在您的專案中建立一個名為runtimeconfig.template.json的文件,並填充以下內容:

    {
      "configProperties": {
        "System.Drawing.EnableUnixSupport": true
      }
    }
  4. 最後,在您的程式開頭新增以下行以啟用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
$vbLabelText   $csharpLabel

高級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
$vbLabelText   $csharpLabel

關於在Azure Functions中管理許可證,請參考我們的使用許可證金鑰文件

Icon Quote related to 高級HTML字串渲染範例

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic related to 高級HTML字串渲染範例

Milan Jovanovic

Microsoft MVP

查看案例研究
Icon Quote related to 高級HTML字串渲染範例

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle related to 高級HTML字串渲染範例

Brent Matzelle

首席技術官,OPYN

查看案例研究
Icon Quote related to 高級HTML字串渲染範例

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones related to 高級HTML字串渲染範例

David Jones

首席軟體工程師,Agorus Build

查看案例研究

有哪些已知問題?

為什麼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建立工程支援請求指南

生產環境的最佳實踐

  1. 始終使用適當的託管級別 - B1 或更高,以獲得可靠的性能
  2. 適當配置日誌 - 使用Azure應用程式分析進行生產監控
  3. 優雅地處理例外 - 為瞬時故障實現重試邏輯
  4. 優化HTML內容 - 盡量減少外部資源的使用,並在可能時使用base64編碼的圖片
  5. 徹底測試 - 在Azure部署之前先在本地驗證PDF生成
  6. 監控資源使用情況 - 追踪記憶體和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生成需求。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 20,088,359 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想快速獲得證明嗎? PM > Install-Package IronPdf
執行範例 看您的HTML變成PDF。