如何在 Azure 上使用 .NET 运行 HTML 至 PDF?

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

是的。 IronPDF可用于在Azure上生成、操作和读取PDF文档。 IronPDF已在多个Azure平台上进行了彻底测试,包括MVC网站、Azure Functions等等。

Azure Functions 在 Docker 上

如果您在 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托管平台概述不支持在其较便宜的共享web应用程序层中加载SVG字体(例如Google字体)的服务器。 因为出于安全原因,这些共享主机平台不允许访问 Windows GDI+ 图形对象。

我们建议使用 Windows 或 Linux Docker 容器指南来使用 IronPDF,或者在 Azure 上使用 VPS 来解决需要最佳字体渲染的问题。

Azure 免费层托管速度慢

Azure 免费和共享层,以及消费计划,不适合用于 PDF 渲染。 我们推荐使用Azure B1托管/高级计划,这也是我们自己使用的方案。 HTML to PDF 的过程对于任何计算机来说都是重要的“工作”——类似于在您自己的机器上打开和渲染网页。使用的是一个真实的浏览器引擎,因此我们需要相应地进行配置,并期望渲染时间与相似性能的桌面机器相当。

创建工程支持请求工单

要创建请求票,请参阅如何为IronPDF提交工程支持请求指南。

查克尼特·宾
软件工程师
Chaknith 负责 IronXL 和 IronBarcode 的工作。他在 C# 和 .NET 方面拥有深厚的专业知识,帮助改进软件并支持客户。他从用户互动中获得的洞察力,有助于提升产品、文档和整体体验。