Cómo usar direcciones URL base en la generación de PDFs con C#

How to Use Base URLs & Asset Encoding

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

IronPDF is a useful tool for generating PDF documents in .NET projects.

A common use of this library is “HTML to PDF” rendering - where HTML is used as the design language for rendering a PDF document. A logical question is: how can we use CSS stylesheets and Image files in our HTML to PDF Conversion?

Quickstart: Implement Base URLs in IronPDF

Get started with IronPDF by easily implementing base URLs for seamless asset loading during HTML to PDF conversion in .NET C#. This example demonstrates how to set the BaseUrlOrPath to ensure all CSS, JavaScript, and images are properly referenced, simplifying the process of generating robust PDF documents. Perfect for developers eager to enhance their PDF rendering with minimal setup.

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().RenderHtmlAsPdf("<img src='icons/logo.png'>", @"C:\site\assets\").SaveAs("with‑assets.pdf");
  3. Deploy to test on your live environment

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


Rendering a PDF from HTML String with Image and CSS Assets

When working with HTML String to PDF conversion, it's important to set a BaseUrlOrPath parameter for assets such as CSS, JavaScript files, and images. The BaseUrlOrPath specifies the base URL from which all assets will be loaded relative to.

This can be a web URL starting with 'http' to load remote assets or a local file path to access assets on your disk. Setting the BaseUrlOrPath correctly ensures that the assets are loaded correctly during the conversion process.

:path=/static-assets/pdf/content-code-examples/how-to/base-urls-baseurl.cs
using IronPdf;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

string baseUrl = @"C:\site\assets\";
string html = "<img src='icons/iron.png'>";

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

// Export PDF
pdf.SaveAs("html-with-assets.pdf");
Imports IronPdf

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private baseUrl As String = "C:\site\assets\"
Private html As String = "<img src='icons/iron.png'>"

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

' Export PDF
pdf.SaveAs("html-with-assets.pdf")
$vbLabelText   $csharpLabel

MVC application

In an MVC application, specifying the file path of an image can be challenging. To ensure that the image can be found by IronPDF and displayed correctly on the website, the baseUrl of IronPDF and src="" attribute on HTML string need to be configured correctly.

With the file hierarchy shown below set

  • baseUrlOrPath to @"wwwroot/image"
  • src attribute to "../image/Sample.jpg"
wwwroot
└── image
    ├── Sample.jpg
    └── Sample.png

For example:

:path=/static-assets/pdf/content-code-examples/how-to/base-mvc.cs
// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("html.Result", @"wwwroot/image");
' Instantiate ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()

' Render HTML to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("html.Result", "wwwroot/image")
$vbLabelText   $csharpLabel
<img src="../image/Sample.jpg"/>
<img src="../image/Sample.png"/>
<img src="../image/Sample.jpg"/>
<img src="../image/Sample.png"/>
HTML

Advertencia

File Path Formats That Do Not Work

The following formats work well when viewing on Chrome browser, but point to the wrong folder directory when used in an MVC app. These formats still work with IronPDF if baseUrlOrPath is provided in the RenderHtmlAsPdf method:

<img src="image/footer.png"/>  
<img src="./image/footer.png"/>  
<img src="image/footer.png"/>  
<img src="./image/footer.png"/>  
HTML

On the other hand, these formats work well with MVC app, but when it comes to file path, these formats do not work well in IronPDF:

<img src="/image/footer.png"/>  
<img src="~/image/footer.png"/>
<img src="/image/footer.png"/>  
<img src="~/image/footer.png"/>
HTML

HTML Headers and Footers with Images and Assets

When we render HTML headers and footers to a new or existing PDF, they are treated as standalone HTML documents and do not inherit the BaseURL from the PDF itself.

We should set a BaseURL from which assets may be loaded:

:path=/static-assets/pdf/content-code-examples/how-to/base-header-footer.cs
using IronPdf;
using System;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Add header
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    MaxHeight = 20,
    HtmlFragment = "<img src='logo.png'>",
    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
};
Imports IronPdf
Imports System

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

' Add header
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
	.MaxHeight = 20,
	.HtmlFragment = "<img src='logo.png'>",
	.BaseUrl = (New Uri("C:\assets\images\")).AbsoluteUri
}
$vbLabelText   $csharpLabel

HTML File to PDF with CSS, JS and Image Assets

When rendering an HTML file to PDF, all assets will be assumed local to that file.

:path=/static-assets/pdf/content-code-examples/how-to/base-html-file.cs
using IronPdf;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render HTML file to PDF
PdfDocument pdf = renderer.RenderHtmlFileAsPdf("C:\\Assets\\TestInvoice1.html");

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

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

' Render HTML file to PDF
Private pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("C:\Assets\TestInvoice1.html")

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

In the above example, all JS, CSS and image files will be loaded from the C:\Assets folder on the disk - the same directory that the HTML file is located.

For convenience, you may use CustomCssUrl in ChromePdfRenderOptions for Additional Stylesheets to specify an additional stylesheet that is only used for .NET PDF rendering if you so desire. For example:

:path=/static-assets/pdf/content-code-examples/how-to/base-html-file-baseurl.cs
using IronPdf;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set additional CSS url
renderer.RenderingOptions.CustomCssUrl = "./style.css";

// Render HTML file to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

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

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

' Set additional CSS url
renderer.RenderingOptions.CustomCssUrl = "./style.css"

' Render HTML file to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

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

Por favor notaThe ChromePdfRenderOptions.CustomCssUrl property is currently only functional when rendering from an HTML string to a PDF document using the RenderHtmlAsPdf method.

Image Asset Encoding

Image assets can be encoded directly into the HTML file or string, which can help avoid some of the frustrating issues of images not being found. To do this we can utilize the use of base64:

  1. First obtain the binary data of the image either by reading the image file or receiving it through a network request.
  2. Use the Convert.ToBase64String method in Microsoft .NET to convert the binary data to base64.
  3. Construct the image tag in HTML using "data:image/svg+xml;base64," before the base64 data. You may have noticed that the image type is being specified before the base64 data. Visit the MDN Web Docs on Image Types and Formats for more information on image format types.
:path=/static-assets/pdf/content-code-examples/how-to/add-images-to-pdfs-base64-image.cs
using IronPdf;
using System;
using System.IO;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Import image file binary data
byte[] binaryData = File.ReadAllBytes("ironpdf-logo-text-dotnet.svg");

// Convert the binary data to base 64
string imgDataUri = Convert.ToBase64String(binaryData);

// Embed in HTML
string html = $"<img src='data:image/svg+xml;base64,{imgDataUri}'>";

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

// Export the PDF
pdf.SaveAs("embedImageBase64.pdf");
Imports IronPdf
Imports System
Imports System.IO

Private renderer As New ChromePdfRenderer()

' Import image file binary data
Private binaryData() As Byte = File.ReadAllBytes("ironpdf-logo-text-dotnet.svg")

' Convert the binary data to base 64
Private imgDataUri As String = Convert.ToBase64String(binaryData)

' Embed in HTML
Private html As String = $"<img src='data:image/svg+xml;base64,{imgDataUri}'>"

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

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

Preguntas Frecuentes

¿Cuál es la importancia de usar URL base en la conversión de HTML a PDF?

Las URL base son cruciales en la conversión de HTML a PDF ya que aseguran que todos los activos relacionados como hojas de estilo CSS, archivos JavaScript e imágenes se carguen correctamente. En IronPDF, el parámetro BaseUrlOrPath se puede establecer en una URL web o una ruta de archivo local para facilitar este proceso.

¿Cómo puedes manejar la carga de activos en una aplicación MVC para la generación de PDFs?

En una aplicación MVC usando IronPDF, puedes manejar la carga de activos configurando el parámetro BaseUrlOrPath para apuntar al directorio que contiene tus activos. De esta forma, tu HTML hará referencia correcta a las rutas de CSS e imágenes relativas a esta ruta base.

¿Qué es la codificación de activos y por qué se usa en la generación de PDFs?

La codificación de activos implica convertir datos de imagen en una cadena base64 e incrustarla dentro del HTML. Esta técnica, usada con IronPDF, asegura que las imágenes no falten durante el proceso de renderizado del PDF, especialmente cuando los activos no son directamente accesibles desde una URL o ruta de archivo.

¿Cómo puedes incluir hojas de estilo adicionales durante el renderizado de PDF en .NET?

Puedes incluir hojas de estilo adicionales durante el renderizado de PDF en .NET usando ChromePdfRenderOptions de IronPDF. Al configurar la propiedad CustomCssUrl, puedes especificar hojas de estilo externas para ser usadas en el proceso de renderizado.

¿Cuáles son algunos pasos comunes para solucionar problemas de imágenes faltantes en PDFs?

Los pasos comunes para solucionar problemas de imágenes faltantes en PDFs incluyen verificar la corrección de BaseUrlOrPath y los atributos src en tu HTML. Asegurarte de que estas rutas sean exactas al usar IronPDF resolverá la mayoría de los problemas relacionados con imágenes faltantes.

¿Cómo pueden renderizarse los encabezados y pies de página HTML con imágenes en PDFs?

Los encabezados y pies de página HTML pueden renderizarse con imágenes en PDFs al establecer una BaseURL separada para cada uno. Usando IronPDF, los encabezados y pies de página se tratan como documentos HTML independientes, por lo que es importante asegurarse de que sus rutas base estén correctamente establecidas para la carga de activos.

¿Puedes convertir archivos HTML locales con activos a PDF?

Sí, puedes convertir archivos HTML locales con activos a PDF usando IronPDF. Al asegurarte de que BaseUrlOrPath esté configurado en el directorio del archivo HTML, IronPDF cargará correctamente todos los activos asociados como CSS e imágenes.

¿IronPDF es totalmente compatible con .NET 10 cuando se utilizan URL base para cargar activos?

Sí. IronPDF está diseñado para ser totalmente compatible con .NET 10. Admite el uso de BaseUrlOrPath (ya sean rutas de archivos locales o URL web) para la carga de recursos en la conversión de HTML a PDF sin necesidad de soluciones personalizadas adicionales. Puede usar URL base con confianza en proyectos .NET 10 con IronPDF, igual que en versiones anteriores.

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