如何使用 C# 在 Azure 上使用 IronPDF 实现 HTML转PDF
IronPDF 可在 Azure 平台(包括 MVC 网站和 Azure 函数)上生成、处理和读取 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 项目快速运行。
最小工作流程(5 个步骤)
- 安装 C# 库在 Azure 中生成 PDF
- 选择 Azure Basic B1 或更高的托管层
- 发布时取消选中 `Run from package file` 选项
- 按照推荐的配置说明进行操作
- 使用代码示例在 Azure 上创建 PDF 生成器
如何使用教程
如何设置我的项目?
我应该安装哪个 IronPDF 软件包?
第一步是使用 NuGet 安装 IronPDF:
- 在基于 Windows 的 Azure Functions 上,请使用
IronPdf包 -适用于 Windows 的NuGet IronPDF包 - 在基于 Linux 的 Azure Functions 上,请使用
IronPdf.Linux包 -适用于 Linux 的NuGet IronPDF包
Install-Package IronPdf
或者,通过使用 Azure 的 IronPDF 直接下载包 链接手动安装 .dll。
有关更多高级安装选项,请查看我们全面的 NuGet Packages 指南。
我需要配置哪些 Azure 选项?
我应该选择哪个 Azure 托管层级?
Azure Basic B1 是满足渲染需求所需的最低托管级别。 如果您正在创建一个高吞吐量系统,这可能需要升级。 B1 层为 Chrome PDF 渲染引擎提供足够的资源,该引擎为 IronPDF 的 HTML 到 PDF 转换提供动力。
为什么要取消选中 "从软件包文件运行"?
发布 Azure Functions 应用程序时,请确保未选中 Run from package file。 此选项可创建只读部署,防止 IronPDF 在执行过程中提取必要的运行时依赖关系。
如何为 .NET 6 进行配置?
微软最近从 .NET 6+ 中移除了成像库,破坏了许多遗留的 API。因此,有必要配置您的项目以仍然允许这些遗留的 API 调用。
- 在 Linux 系统上,设置
Installation.LinuxAndDockerDependenciesAutoConfig=true;以确保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 字体访问以及控制性能的一种方法是在 Docker 容器中使用 IronPDF 应用和函数。 这种方法可以更好地控制运行环境,消除许多特定平台的限制。
我们有一个全面的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";
// 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
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
关于在您的 Azure Functions 中管理许可证,请参阅我们的 Using License Keys 文档。
已知问题有哪些?
为什么共享托管计划无法渲染 SVG 字体?
一个限制是Azure 托管平台概述不支持服务器加载 SVG 字体,例如 Google 字体,在其更便宜的共享 web-app 层。 这是由于安全限制阻止访问 Windows GDI+ 图形对象。
我们建议使用IronPDF 的 Windows 或 Linux Docker 容器指南,或在需要最佳字体渲染的地方使用 Azure 上的 VPS。
为什么 Azure 免费层托管速度慢?
Azure 免费和共享层以及消耗计划不适合 PDF 渲染。 我们推荐 Azure B1 托管/高级计划,这是我们自己使用的。 对于任何计算机来说,处理 HTML to PDF 的过程都是一项相当大的"工作",类似于在您自己的计算机上打开并渲染网页。它使用了真正的浏览器引擎,因此我们需要相应地进行配置,并预期渲染时间与同等性能的台式机类似。
如何在本地调试 Azure 函数?
关于本地开发和测试,请参阅我们的在本地机器上调试 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 函数安装哪个软件包?
对于基于 Windows 的 Azure Functions,请从 NuGet 安装 IronPDF 软件包。该软件包已针对 Windows 环境进行了优化,可使用 Chrome 渲染引擎提供完整的 PDF 生成功能。
如何在 Azure Functions 中将 HTML 转换为 PDF?
使用 IronPDF 的 ChromePdfRenderer,只需一行代码即可将 HTML 转换为 PDF。只需创建一个新实例,并调用 RenderHtmlAsPdf() 来渲染 HTML 内容,然后保存生成的 PDF 文件即可。
如果我没有选择正确的应用程序服务计划会发生什么情况?
如果未选择 App 服务计划的计划类型,可能会导致 IronPDF 无法渲染 PDF 文档。正确配置 Azure 托管环境对于 PDF 呈现引擎正常运行至关重要。
为什么发布时必须取消选中 "从软件包文件运行"?
发布您的 Azure Functions 应用程序时,必须取消选中 "从包文件运行",以确保 IronPDF 可以在 Azure 环境中正确访问和使用其渲染组件和依赖项。
能否使用基于 Linux 的 Azure 函数生成 PDF?
是的,对于基于 Linux 的 Azure 函数,请使用 NuGet 中的 IronPDF.Linux 软件包。该软件包专门针对 Linux 环境进行了优化,同时提供相同的 PDF 生成功能。
如果我需要更高的 PDF 生成吞吐量怎么办?
对于高吞吐量系统,您可能需要升级到 B1 层以上。IronPDF 可根据您的 Azure 资源进行扩展,使您能够通过选择更高性能层来处理增加的 PDF 生成需求。

