How to Use Base URLs & Asset Encoding
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?
How to Use HTML with CSS and Images
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;
// This code uses IronPdf to render an HTML string as a PDF file, including local assets like images.
// Instantiate a ChromePdfRenderer to render HTML content.
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Specify the base URL where images and other assets are located.
// This should be a local or online path where your resources are stored.
string baseUrl = @"C:\site\assets\";
// Define an HTML string. This example includes an image that will be sourced from the base URL.
string html = "<img src='icons/iron.png'>";
// Render the HTML string to a PDF document.
// The base URL helps locate resources like images referenced in the HTML.
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, baseUrl);
// Save the rendered PDF document to a file on the local system.
// Ensure the directory for the output file is writable.
pdf.SaveAs("html-with-assets.pdf");
Imports IronPdf
' This code uses IronPdf to render an HTML string as a PDF file, including local assets like images.
' Instantiate a ChromePdfRenderer to render HTML content.
Private renderer As New ChromePdfRenderer()
' Specify the base URL where images and other assets are located.
' This should be a local or online path where your resources are stored.
Private baseUrl As String = "C:\site\assets\"
' Define an HTML string. This example includes an image that will be sourced from the base URL.
Private html As String = "<img src='icons/iron.png'>"
' Render the HTML string to a PDF document.
' The base URL helps locate resources like images referenced in the HTML.
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, baseUrl)
' Save the rendered PDF document to a file on the local system.
' Ensure the directory for the output file is writable.
pdf.SaveAs("html-with-assets.pdf")
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
// This code snippet demonstrates how to render HTML content into a PDF document
// using the ChromePdfRenderer class from a suitable library (ensure you have the correct library installed).
// This assumes you have a library that provides a class like ChromePdfRenderer.
// One such library is IronPdf, but this is just for demonstrative purposes.,
// Make sure to adjust the using directives and library references accordingly.
using IronPdf; // Example: using a library that supports HTML to PDF rendering
// Instantiate the ChromePdfRenderer
// The ChromePdfRenderer class is used here for rendering purposes. Make sure that the library
// being used is properly referenced and installed in your project.
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Sample HTML content to render into a PDF
string htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
// Render HTML to PDF
// The RenderHtmlAsPdf method takes two arguments:
// 1. The HTML content to be rendered.
// 2. The base path for resources, such as images. Adjust this path to point to where resources might exist,
// necessary for rendering if your HTML references local images or other assets.
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent, @"wwwroot/image");
// It's common to save or further use the generated PDF document. For example:
// Save the generated PDF document to a file
string outputPath = @"output.pdf";
pdf.SaveAs(outputPath);
// Ensure appropriate error handling (try-catch) and resource management as per your project standards
' This code snippet demonstrates how to render HTML content into a PDF document
' using the ChromePdfRenderer class from a suitable library (ensure you have the correct library installed).
' This assumes you have a library that provides a class like ChromePdfRenderer.
' One such library is IronPdf, but this is just for demonstrative purposes.,
' Make sure to adjust the using directives and library references accordingly.
Imports IronPdf ' Example: using a library that supports HTML to PDF rendering
' Instantiate the ChromePdfRenderer
' The ChromePdfRenderer class is used here for rendering purposes. Make sure that the library
' being used is properly referenced and installed in your project.
Private renderer As New ChromePdfRenderer()
' Sample HTML content to render into a PDF
Private htmlContent As String = "<html><body><h1>Hello, World!</h1></body></html>"
' Render HTML to PDF
' The RenderHtmlAsPdf method takes two arguments:
' 1. The HTML content to be rendered.
' 2. The base path for resources, such as images. Adjust this path to point to where resources might exist,
' necessary for rendering if your HTML references local images or other assets.
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent, "wwwroot/image")
' It's common to save or further use the generated PDF document. For example:
' Save the generated PDF document to a file
Private outputPath As String = "output.pdf"
pdf.SaveAs(outputPath)
' Ensure appropriate error handling (try-catch) and resource management as per your project standards
<img src="../image/Sample.jpg"/>
<img src="../image/Sample.png"/>
<img src="../image/Sample.jpg"/>
<img src="../image/Sample.png"/>
Before proceeding
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"/>
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 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 directives for necessary namespaces
using IronPdf;
using System;
// Instantiate the ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Configure the rendering options for the PDF header
// Here we specifically want to set some properties for the header
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
// Set the maximum height of the header in points
MaxHeight = 20,
// Provide the HTML content for the header
// This can include text and images, here we add an image
HtmlFragment = "<img src='logo.png' alt='Logo'>",
// Specify the base URL for resolving relative paths in the HTML fragment
// This is important if the HTML references any local resources like images
BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
};
// Note: Further code to render a document or handle exceptions would be needed
// to fully demonstrate using this renderer to create a PDF. Here, we are just
// setting up the header configuration.
' using directives for necessary namespaces
Imports IronPdf
Imports System
' Instantiate the ChromePdfRenderer
Private renderer As New ChromePdfRenderer()
' Configure the rendering options for the PDF header
' Here we specifically want to set some properties for the header
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.MaxHeight = 20,
.HtmlFragment = "<img src='logo.png' alt='Logo'>",
.BaseUrl = (New Uri("C:\assets\images\")).AbsoluteUri
}
' Note: Further code to render a document or handle exceptions would be needed
' to fully demonstrate using this renderer to create a PDF. Here, we are just
' setting up the header configuration.
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
// Import the IronPdf library to use its PDF rendering capabilities
using IronPdf;
// Instantiate a ChromePdfRenderer object which allows conversion of HTML to PDF
var renderer = new ChromePdfRenderer();
// Render a PDF from the specified HTML file.
// The method RenderHtmlFileAsPdf converts an HTML file to a PDF document.
PdfDocument pdf = renderer.RenderHtmlFileAsPdf("C:\\Assets\\TestInvoice1.html");
// Save the rendered PDF document to the specified path.
// The SaveAs method saves the PDF to the given filename, in this case, "Invoice.pdf" in the current directory.
pdf.SaveAs("Invoice.pdf");
' Import the IronPdf library to use its PDF rendering capabilities
Imports IronPdf
' Instantiate a ChromePdfRenderer object which allows conversion of HTML to PDF
Private renderer = New ChromePdfRenderer()
' Render a PDF from the specified HTML file.
' The method RenderHtmlFileAsPdf converts an HTML file to a PDF document.
Private pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("C:\Assets\TestInvoice1.html")
' Save the rendered PDF document to the specified path.
' The SaveAs method saves the PDF to the given filename, in this case, "Invoice.pdf" in the current directory.
pdf.SaveAs("Invoice.pdf")
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;
// This code uses the IronPDF library to render HTML content as a PDF document,
// with an additional CSS file for styling purposes.
// Instantiate a ChromePdfRenderer object that will manage the rendering process.
var renderer = new ChromePdfRenderer();
// Set the path to a custom CSS file that will be used to style the HTML content.
// Ensure that the CSS file path is correct relative to the application's execution directory.
renderer.RenderingOptions.CustomCssUrl = "./style.css";
// Render an HTML string into a PDF document.
// The HTML content is styled using the custom CSS specified earlier.
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
// Save the rendered PDF document to a specified file on the disk.
// This writes the PDF to a file named "tryCss.pdf" in the current working directory.
pdf.SaveAs("tryCss.pdf");
Imports IronPdf
' This code uses the IronPDF library to render HTML content as a PDF document,
' with an additional CSS file for styling purposes.
' Instantiate a ChromePdfRenderer object that will manage the rendering process.
Private renderer = New ChromePdfRenderer()
' Set the path to a custom CSS file that will be used to style the HTML content.
' Ensure that the CSS file path is correct relative to the application's execution directory.
renderer.RenderingOptions.CustomCssUrl = "./style.css"
' Render an HTML string into a PDF document.
' The HTML content is styled using the custom CSS specified earlier.
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
' Save the rendered PDF document to a specified file on the disk.
' This writes the PDF to a file named "tryCss.pdf" in the current working directory.
pdf.SaveAs("tryCss.pdf")
Please note
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:
- First obtain the binary data of the image either by reading the image file or receiving it through a network request.
- Use the
Convert.ToBase64String
method in Microsoft .NET to convert the binary data to base64. - 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;
// Create a ChromePdfRenderer instance to render HTML to PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
try
{
// Import image file binary data
byte[] binaryData = File.ReadAllBytes("ironpdf-logo-text-dotnet.svg");
// Convert the binary data to a base64 encoded string
string imgDataUri = Convert.ToBase64String(binaryData);
// Embed the base64 encoded image in an HTML img tag
string html = $"<img src='data:image/svg+xml;base64,{imgDataUri}'>";
// Use the renderer to convert the HTML to a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
// Save the generated PDF document to the specified path
pdf.SaveAs("embedImageBase64.pdf");
Console.WriteLine("PDF has been successfully created and saved.");
}
catch (FileNotFoundException ex)
{
// Handle specific case when the image file could not be found
Console.WriteLine("The specified image file was not found: " + ex.Message);
}
catch (Exception ex)
{
// Handle any other exceptions that may occur during execution
Console.WriteLine("An error occurred: " + ex.Message);
}
Imports IronPdf
Imports System
Imports System.IO
' Create a ChromePdfRenderer instance to render HTML to PDF
Private renderer As New ChromePdfRenderer()
Try
' Import image file binary data
Dim binaryData() As Byte = File.ReadAllBytes("ironpdf-logo-text-dotnet.svg")
' Convert the binary data to a base64 encoded string
Dim imgDataUri As String = Convert.ToBase64String(binaryData)
' Embed the base64 encoded image in an HTML img tag
Dim html As String = $"<img src='data:image/svg+xml;base64,{imgDataUri}'>"
' Use the renderer to convert the HTML to a PDF document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
' Save the generated PDF document to the specified path
pdf.SaveAs("embedImageBase64.pdf")
Console.WriteLine("PDF has been successfully created and saved.")
Catch ex As FileNotFoundException
' Handle specific case when the image file could not be found
Console.WriteLine("The specified image file was not found: " & ex.Message)
Catch ex As Exception
' Handle any other exceptions that may occur during execution
Console.WriteLine("An error occurred: " & ex.Message)
End Try
Frequently Asked Questions
What is IronPDF used for in .NET projects?
IronPDF is a tool used for generating PDF documents in .NET projects, commonly for rendering HTML to PDF.
How can CSS stylesheets and images be used in HTML to PDF conversion with IronPDF?
You can use the BaseUrlOrPath parameter to load CSS stylesheets and images during HTML to PDF conversion. This parameter specifies the base URL or local path from which all assets will be loaded.
What is the purpose of the BaseUrlOrPath parameter in IronPDF?
The BaseUrlOrPath parameter is used to specify the base URL or file path from which assets like CSS, JavaScript files, and images will be loaded during the HTML to PDF conversion process.
How do you configure image paths in an MVC application using IronPDF?
In an MVC application, you configure the file path by setting the baseUrlOrPath to the directory containing the images and adjusting the src attribute in your HTML to match the relative path to these images.
How do you render HTML headers and footers with images using IronPDF?
To render HTML headers and footers with images, you must set a separate BaseURL for the headers and footers, as they are treated as standalone HTML documents.
Can local HTML files with assets be rendered to PDF using IronPDF?
Yes, local HTML files can be rendered to PDF using IronPDF. The assets such as CSS, JS, and images will be assumed to be local to the HTML file's directory.
What is image asset encoding and how is it done in IronPDF?
Image asset encoding involves converting image data to a base64 string and embedding it directly into the HTML. This is done to prevent issues with images not being found during the PDF rendering process.
How can additional stylesheets be included in PDF rendering with IronPDF?
Additional stylesheets can be included using the CustomCssUrl property in ChromePdfRenderOptions, which allows specifying an external stylesheet for .NET PDF rendering.
What happens if incorrect image paths are used in IronPDF?
Incorrect image paths may result in images not being displayed in the rendered PDF. It is important to ensure that the BaseUrlOrPath and src attributes are configured correctly.