如何在 Azure 上使用 .NET 將 HTML 轉換為 PDF?

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

是的。 IronPDF 可用於在 Azure 上生成、操作和讀取 PDF 文件。 IronPDF 已在包括 MVC 網站、Azure Functions 等多個 Azure 平台上進行了全面測試。

在 Docker 上的 Azure 函數

如果您在 Docker 容器中運行 Azure Functions,請改為參考這個 Azure Docker Linux 教程


如何操作教程

設置您的專案

安裝 IronPDF 以開始使用

首先要透過 NuGet 安裝 IronPDF:

Install-Package IronPdf

或者,通過使用IronPDF 直接下載包針對 Azure連結手動安裝 .dll。

選擇正確的Azure選項

選擇正確的託管等級 Azure 分層

Azure 基本 B1 是我們終端用戶渲染需求所需的最低託管層級。 如果您正在創建一個高吞吐量系統,可能需要對其進行升級。

在繼續之前
未選擇應用服務計劃類型可能會導致IronPdf無法呈現PDF文件。

選擇正確的託管等級 Azure 分層

"從套件檔案運行"復選框

在發佈您的 Azure Functions 應用程式時,請確保選擇 從套件檔案運行

取消勾選從包文件運行選項

配置 .NET 6

Microsoft 最近從 .NET 6+ 中移除了成像庫,導致許多舊版 API 失效。因此,有必要配置您的項目以便仍能使用這些舊版 API。

  1. 在 Linux 上,設置 Installation.LinuxAndDockerDependenciesAutoConfig=true; 以確保機器上安裝了 libgdiplus

  2. 將以下內容添加到您的 .NET 6 專案的 .csproj 檔中:<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>

  3. 在專案中建立一個名為runtimeconfig.template.json的文件,並填入以下內容:
{
      "configProperties": {
         "System.Drawing.EnableUnixSupport": true
      }
}
{
      "configProperties": {
         "System.Drawing.EnableUnixSupport": true
      }
}
If True Then
	  "configProperties":
	  If True Then
		 "System.Drawing.EnableUnixSupport": True
	  End If
End If
$vbLabelText   $csharpLabel
  1. 最後,將以下行添加到程式的開頭:System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);

使用 Docker 在 Azure 上

使用 IronPDF 應用程序和功能,並在 Docker 容器內部署,是一種獲得控制權、SVG 字型訪問和控制 Azure 性能的方法。

我們提供了詳盡的IronPDF Azure Docker 教程,適用於 Linux 和 Windows 實例,推薦閱讀。

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";
    // Enable log
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.Custom;
    IronPdf.Logging.Logger.CustomLogger = log;

    IronPdf.Logging.Logger.EnableDebugging = false;
    // Configure IronPdf
    Installation.LinuxAndDockerDependenciesAutoConfig = false;
    Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
    try
    {
        log.LogInformation("About to render pdf...");
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        // Render PDF
        var pdf = renderer.RenderUrlAsPdf("https://www.google.com/");
        log.LogInformation("finished rendering pdf...");
        return new FileContentResult(pdf.BinaryData, "application/pdf") { FileDownloadName = "google.pdf" };
    }
    catch (Exception e)
    {
        log.LogError(e, "Error while rendering pdf", e);
    }

    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";
    // Enable log
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.Custom;
    IronPdf.Logging.Logger.CustomLogger = log;

    IronPdf.Logging.Logger.EnableDebugging = false;
    // Configure IronPdf
    Installation.LinuxAndDockerDependenciesAutoConfig = false;
    Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
    try
    {
        log.LogInformation("About to render pdf...");
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        // Render PDF
        var pdf = renderer.RenderUrlAsPdf("https://www.google.com/");
        log.LogInformation("finished rendering pdf...");
        return new FileContentResult(pdf.BinaryData, "application/pdf") { FileDownloadName = "google.pdf" };
    }
    catch (Exception e)
    {
        log.LogError(e, "Error while rendering pdf", e);
    }

    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"
	' Enable log
	IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.Custom
	IronPdf.Logging.Logger.CustomLogger = log

	IronPdf.Logging.Logger.EnableDebugging = False
	' Configure IronPdf
	Installation.LinuxAndDockerDependenciesAutoConfig = False
	Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
	Try
		log.LogInformation("About to render pdf...")
		Dim renderer As New ChromePdfRenderer()
		' Render PDF
		Dim pdf = renderer.RenderUrlAsPdf("https://www.google.com/")
		log.LogInformation("finished rendering pdf...")
		Return New FileContentResult(pdf.BinaryData, "application/pdf") With {.FileDownloadName = "google.pdf"}
	Catch e As Exception
		log.LogError(e, "Error while rendering pdf", e)
	End Try

	Return New OkObjectResult("OK")
End Function
$vbLabelText   $csharpLabel

已知問題

SVG 字體渲染在共享主機計劃上無法使用。

我們發現的一個限制是,Azure hosting platform overview 不支持在其較便宜的共享網絡應用程式層級中載入 SVG 字體的伺服器,例如 Google 字體。 這是因為出於安全考量,這些共享主機平台無法訪問 Windows GDI+ 圖形物件。

我們建議使用Windows 或 Linux Docker 容器指南以使用 IronPDF,或者可能在 Azure 上使用 VPS 來解決此問題,其中需要最佳的字體渲染。

Azure 免費層主機速度慢

Azure 的免費和共享層級,以及消費計劃,不適合用於 PDF 渲染。 我們推薦使用 Azure B1 主機/高級方案,這也是我們自己使用的。 將HTML 轉換為 PDF的過程對任何電腦來說都是一項重大「工作」——類似於在自己的機器上打開和渲染網頁。使用了真正的瀏覽器引擎,因此我們需要相應地進行配置,並期望與類似性能的桌面機器相似的渲染時間。

創建工程支援請求票证

如需建立請求票,請參考IronPDF 工程支持請求指南

查克尼思·賓
軟體工程師
Chaknith 致力於 IronXL 和 IronBarcode。他在 C# 和 .NET 方面擁有豐富的專業知識,協助改進軟體並支持客戶。他從用戶互動中獲得的洞察力有助於提高產品、文檔和整體體驗。