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

如何在 Azure 函數中使用 C# 和IronPDF實現 HTML轉PDF

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

使用IronPDF在 Azure 應用程式中開始將 HTML 轉換為 PDF。 本快速指南示範如何使用 IronPDF 的 API 方法將 URL 渲染為 PDF 文件。 此範例展示了IronPDF在將 PDF 功能整合到 Azure 解決方案方面的簡易性。 依照範例操作,即可開始產生 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 函數應用程式建立表單,其中

為什麼要取消勾選"從程式包檔案執行"?

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

Azure Functions 發佈對話方塊顯示未選取的

如何配置.NET 6?

微軟最近從.NET 6 及更高版本中移除了映像處理庫,導致許多舊版 API 無法正常運作。因此,您需要配置專案以允許呼叫這些舊版 API。

  1. 在 Linux 系統上,設定 Installation.LinuxAndDockerDependenciesAutoConfig=true; 以確保 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?

要在 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
$vbLabelText   $csharpLabel

進階 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
$vbLabelText   $csharpLabel

有關管理 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 生成需求。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 18,332,619 | 版本: 2026.4 剛剛發布
Still Scrolling Icon

還在捲動嗎?

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