Cómo generar HTML a PDF con .NET en Azure

How to Run HTML to PDF with .NET on Azure?

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

Yes. IronPDF can be used to generate, manipulate, and read PDF documents on Azure. IronPDF has been thoroughly tested on multiple Azure platforms including MVC websites, Azure Functions, and many more.

If you are running Azure Functions within a Docker Container please refer to this Azure Docker Linux Tutorial instead.

Quickstart: HTML to PDF Conversion with IronPDF on Azure

Start converting HTML to PDF in your Azure applications effortlessly using IronPDF. This quick guide demonstrates how to render a URL as a PDF document using IronPDF's efficient API methods. Perfect for developers looking to integrate PDF capabilities into their Azure solutions, this example showcases the simplicity and speed of IronPDF, ensuring your PDF generation tasks are seamless and time-efficient. Follow the example to start generating PDFs without losing formatting and get your Azure project up and running in no time.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    var pdf = new IronPdf.ChromePdfRenderer()
        .RenderHtmlAsPdf("<h1>Hello Azure!</h1>")
        .SaveAs("output‑azure.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

How to Tutorial

Setting up Your Project

Installing IronPDF to Get Started

First step is to install IronPDF using NuGet:

Install-Package IronPdf

Alternatively, manually install the .dll by using the IronPDF direct download package for Azure link.

Select Correct Azure Options

Choosing the correct hosting level Azure Tier

Azure Basic B1 is the minimum hosting level required for our end users' rendering needs. If you are creating a high throughput system, this may need to be upgraded.

AdvertenciaFailure to select a Plan Type of App service plan may result in IronPdf failing to render PDF documents.

Choosing the correct hosting level Azure Tier

The "Run from package file" Checkbox

When publishing your Azure Functions application, make sure Run from package file is NOT selected.

Uncheck Run from package file option

Configuration for .NET 6

Microsoft recently removed imaging libraries from .NET 6+, breaking many legacy APIs. As such, it is necessary to configure your project to still allow these legacy API calls.

  1. On Linux, set Installation.LinuxAndDockerDependenciesAutoConfig=true; to ensure libgdiplus is installed on the machine
  2. Add the following to the .csproj file for your .NET 6 project:
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    XML
  3. Create a file in your project called runtimeconfig.template.json and populate it with the following:
{
  "configProperties": {
    "System.Drawing.EnableUnixSupport": true
  }
}
  1. Finally, add the following line to the beginning of your program to enable Unix support for 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

Using Docker on Azure

One way to gain control, SVG font access, and the ability to control performance on Azure is to use IronPDF applications and Functions from within Docker Containers.

We have a comprehensive IronPDF Azure Docker tutorial for Linux and Windows instances, and it is recommended reading.

Azure Function Code Example

This example automatically outputs log entries to the built-in Azure logger (see 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

Known Issues

SVG fonts rendering is not available on shared hosting plans

One limitation is that the Azure hosting platform overview does not support servers loading SVG fonts, such as Google Fonts, in their cheaper shared web-app tiers. This is due to security restrictions preventing access to Windows GDI+ graphics objects.

We recommend using a Windows or Linux Docker Container guide for IronPDF or perhaps a VPS on Azure to navigate this issue where the best font rendering is required.

Azure free tier hosting is slow

Azure free and shared tiers, and the consumption plan, are not suitable for PDF rendering. We recommend Azure B1 hosting/Premium plan, which is what we use ourselves. The process of HTML to PDF is significant 'work' for any computer - similar to opening and rendering a web page on your own machine. A real browser engine is used, hence we need to provision accordingly and expect similar render times to a desktop machine of similar power.

Creating an Engineering Support Request Ticket

In order to create a request ticket refer to the How to Make an Engineering Support Request for IronPDF guide.

Preguntas Frecuentes

¿Cómo puedo convertir HTML a PDF en C# en Azure?

Puedes usar IronPDF para convertir HTML a PDF dentro de tus aplicaciones Azure utilizando el método RenderHtmlAsPdf. Esto te permite mantener el formato de tu contenido HTML en el PDF generado.

¿Cuáles son las mejores prácticas para implementar generación de PDF en Azure Functions?

Al implementar generación de PDF en Azure Functions usando IronPDF, asegúrate de instalar la biblioteca a través de NuGet y evita seleccionar la opción 'Ejecutar desde archivo de paquete' durante la publicación. Esto ayuda a prevenir problemas comunes de implementación.

¿Puedo usar IronPDF con .NET 6 en Azure?

Sí, puedes usar IronPDF con .NET 6 en Azure. Añade <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> a tu archivo .csproj y crea un archivo runtimeconfig.template.json con 'System.Drawing.EnableUnixSupport' configurado a true.

¿Qué nivel de hosting se recomienda para un rendimiento óptimo de renderizado de PDF en Azure?

Para un rendimiento óptimo de renderizado de PDF en Azure usando IronPDF, se recomienda usar al menos el nivel de hosting Azure Basic B1 o actualizar a un nivel más alto para sistemas de alta capacidad.

¿Existen limitaciones al usar IronPDF en los planes de alojamiento compartido de Azure?

Sí, la renderización de fuentes SVG no está disponible en los planes de alojamiento compartido más económicos de Azure. Para una mejor renderización de fuentes y rendimiento, utiliza contenedores Docker de Windows o Linux o un VPS en Azure.

¿Cómo puedo mejorar el rendimiento de renderizado de PDF en el nivel gratuito de Azure?

Para mejorar el rendimiento de renderizado de PDF más allá de las limitaciones del nivel gratuito de Azure, considera actualizar al nivel de hosting Azure Basic B1 o superior. Esto alivia los cuellos de botella de rendimiento asociados al nivel gratuito.

¿Cuáles son los problemas conocidos al usar IronPDF en Azure?

Los problemas conocidos incluyen limitaciones con la renderización de fuentes SVG en planes de alojamiento compartido y preocupaciones de rendimiento en el nivel gratuito de alojamiento de Azure. Usar contenedores Docker puede ayudar a mitigar estos problemas.

¿Cómo puedo utilizar Docker para ejecutar Azure Functions para la generación de PDF?

Puedes implementar Azure Functions dentro de contenedores Docker para obtener mejor rendimiento y control al generar PDFs usando IronPDF. Consulta el tutorial de Azure Docker Linux para más detalles.

¿Cómo busco soporte técnico para IronPDF en Azure?

Para solicitar soporte técnico para IronPDF en Azure, puedes seguir la guía 'Cómo hacer una solicitud de soporte de ingeniería para IronPDF' disponible en el sitio web de IronPDF.

¿Es posible acceder a fuentes SVG al usar Docker en Azure?

Sí, usar Docker en Azure permite acceder a fuentes SVG, lo que mejora el rendimiento y la calidad de los PDFs generados con IronPDF.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado