Cómo configurar fuentes en PDFs C#

How to Set Fonts in PDFs

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

A webfont is a specialized font designed for use on websites. These fonts are hosted on web servers and downloaded by web browsers to ensure consistent and visually appealing text rendering on websites, regardless of the user's local font availability. Additionally, icon fonts, which use symbols and glyphs, are often used in web design to create scalable, customizable icons and maintain a visually consistent user interface through CSS manipulation.

CSS includes web fonts, enabling you to specify font files for download when your website is accessed. IronPDF supports font loading and rendering to PDF from HTML.

Quickstart: Using WebFonts in PDF Generation

Easily incorporate web and icon fonts into your PDFs using IronPDF's powerful C# library. This quick guide shows you how to render HTML content with custom fonts, ensuring consistent and visually appealing PDFs. Simply render the HTML with IronPDF and save your styled document in seconds.

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.

    new IronPdf.ChromePdfRenderer { RenderingOptions = { WaitFor = IronPdf.Rendering.WaitFor.AllFontsLoaded(2000) } }
        .RenderHtmlAsPdf("<link href=\"https://fonts.googleapis.com/css?family=Lobster\" rel=\"stylesheet\">" +
                         "<link href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css\" rel=\"stylesheet\">" +
                         "<p style=\"font‑family:'Lobster', serif; font‑size:30px;\">Hello Google Font</p>" +
                         "<i class=\"fa fa‑coffee\" style=\"font‑size:40px; color:#b00;\"></i>")
        .SaveAs("webfonts‑icons.pdf");
  3. Deploy to test on your live environment

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

Use WebFonts and Icons Example

IronPDF supports WebFonts (such as Google Fonts and the Adobe web font API) and icon fonts, such as those used by Bootstrap and FontAwesome.

Fonts often require a delay in rendering to load properly. When a font is not loaded correctly, it can lead to a blank page without any text. You can use the WaitFor.AllFontsLoaded method to wait until all fonts are loaded by assigning a maximum wait time to it. The default maximum wait time is 500ms.

Here is a small example of how to use a WebFont named Lobster in your project.

:path=/static-assets/pdf/content-code-examples/how-to/webfonts-webicons-render-webfont.cs
using IronPdf;

// HTML contains webfont
var html = @"<link href=""https://fonts.googleapis.com/css?family=Lobster"" rel=""stylesheet"">
<p style=""font-family: 'Lobster', serif; font-size:30px;"" > Hello Google Fonts</p>";

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Wait for font to load
renderer.RenderingOptions.WaitFor.AllFontsLoaded(2000);

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

// Export the PDF
pdf.SaveAs("font-test.pdf");
Imports IronPdf

' HTML contains webfont
Private html = "<link href=""https://fonts.googleapis.com/css?family=Lobster"" rel=""stylesheet"">
<p style=""font-family: 'Lobster', serif; font-size:30px;"" > Hello Google Fonts</p>"

Private renderer As New ChromePdfRenderer()

' Wait for font to load
renderer.RenderingOptions.WaitFor.AllFontsLoaded(2000)

' Render HTML to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

' Export the PDF
pdf.SaveAs("font-test.pdf")
$vbLabelText   $csharpLabel

Explore more WaitFor options, such as those for fonts, JavaScript, HTML elements, and network idle on the 'IronPDF WaitFor Class Documentation.'


Import Font File Example

To use an existing font file, apply the @font-face rule in CSS styling. It also works when using a combination of the @font-face rule and embedding base64-encoded woff files. In the following example, I will be using Pixelify Sans Font.

:path=/static-assets/pdf/content-code-examples/how-to/webfonts-webicons-custom-font.cs
using IronPdf;

// Import custom font
string html = @"<!DOCTYPE html>
<html>
<head>
<style>
@font-face {font-family: 'Pixelify';
src: url('fonts\PixelifySans-VariableFont_wght.ttf');
}
p {
    font-family: 'Pixelify';
    font-size: 70px;
}
</style>
</head>
<body>
<p>Custom font</p>
</body>
</html>";

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

// Export the PDF
pdf.SaveAs("customFont.pdf");
Imports IronPdf

' Import custom font
Private html As String = "<!DOCTYPE html>
<html>
<head>
<style>
@font-face {font-family: 'Pixelify';
src: url('fonts\PixelifySans-VariableFont_wght.ttf');
}
p {
    font-family: 'Pixelify';
    font-size: 70px;
}
</style>
</head>
<body>
<p>Custom font</p>
</body>
</html>"

Private renderer As New ChromePdfRenderer()

' Render HTML to PDF
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

' Export the PDF
pdf.SaveAs("customFont.pdf")
$vbLabelText   $csharpLabel

Limitations on Azure PDF

The Azure hosting platform does not support servers loading SVG fonts in their lower shared web app tiers. However, Azure's VPS and Web Role are not sandboxed in the same way and do support web font rendering.

Preguntas Frecuentes

¿Cómo estableces fuentes en un PDF usando una biblioteca .NET?

Puedes establecer fuentes en un PDF usando IronPDF descargando la biblioteca IronPDF, utilizando HTML para importar o solicitar fuentes, retrasando el proceso de renderización hasta que las fuentes estén cargadas, y aplicando la regla @font-face para fuentes personalizadas en CSS.

¿Cuál es el papel del método WaitFor.AllFontsLoaded en la renderización de PDFs?

El método WaitFor.AllFontsLoaded en IronPDF asegura que todas las fuentes estén completamente cargadas antes de renderizar el PDF, previniendo problemas como páginas en blanco causadas por fuentes no cargadas.

¿Puedes usar Google Fonts en una aplicación .NET para la creación de PDFs?

Sí, puedes usar Google Fonts en una aplicación .NET para la creación de PDFs con IronPDF importando las fuentes en tu HTML y especificándolas en tu CSS antes de renderizar el HTML a PDF.

¿Cómo pueden usarse icon fonts como FontAwesome en documentos PDF?

IronPDF soporta icon fonts como FontAwesome, permitiéndote incorporar íconos escalables y personalizables en tus documentos PDF al incluir la fuente de iconos en tu HTML y CSS.

¿Limitaciones de Azure para renderización de fuentes en PDFs?

En la plataforma de alojamiento de Azure, los niveles inferiores de aplicaciones web compartidas no soportan la carga de fuentes SVG, pero las VPS y Web Role de Azure sí soportan la renderización completa de fuentes web sin tales limitaciones.

¿Cómo puedo solucionar problemas si mis fuentes personalizadas no aparecen en el PDF?

Si las fuentes personalizadas no aparecen en el PDF, asegúrate de que los archivos de fuentes estén correctamente enlazados en tu HTML y aumenta el tiempo de espera usando el método WaitFor.AllFontsLoaded para permitir que las fuentes se carguen adecuadamente antes de renderizar.

¿Cuál es el proceso para utilizar la regla @font-face en CSS para la conversión a PDF?

Para utilizar la regla @font-face en CSS para la conversión a PDF, define la fuente personalizada y su origen en tu CSS, e IronPDF aplicará estos estilos al convertir HTML a PDF, permitiendo el uso de fuentes personalizadas.

¿Hay configuraciones específicas necesarias para usar WebFonts en la conversión a PDF?

Para usar WebFonts en la conversión a PDF con IronPDF, asegúrate de que las URL de las fuentes sean accesibles, incluye las fuentes en tu HTML a través de un enlace o importación, y especifícalas en tu CSS. Usa el método WaitFor.AllFontsLoaded para gestionar la carga de fuentes.

¿IronPDF admite fuentes web y de íconos cuando se dirige a .NET 10?

Sí, IronPDF es totalmente compatible con .NET 10 y admite fuentes web (como Google Fonts o Adobe Web Fonts) y fuentes de iconos como FontAwesome. La API funciona a la perfección en .NET 10, por lo que puede usar HTML/CSS para importar y renderizar fuentes personalizadas y de iconos, igual que en versiones anteriores de .NET.

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