How to Use Base URLs & Asset Encoding in C# .NET 10
Base URLs in IronPDF allow CSS, JavaScript, and image assets to be properly loaded during HTML to PDF conversion by specifying the BaseUrlOrPath parameter, which can be a web URL or local file path for relative asset resolution.
Get started with IronPDF by 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 PDF generation with minimal setup.
-
1Install IronPDF with NuGet Package Manager
-
2Copy and run this code snippet.
new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<img src='icons/logo.png'>", @"C:\site\assets\").SaveAs("with-assets.pdf");C# -
3Deploy to test on your live environment
Start using IronPDF in your project today with a free trial
Minimal Workflow (5 steps)
- Download IronPDF for HTML to CSS to Image Support
- Specify BaseUrlOrPath parameter for external images in HTML
- Configure correct src in MVC for web and PDF display
- Specify custom headers and footers using the BaseUrl property
- Check the output PDF
Convert.ToBase64String
How Do I Render PDFs from HTML Strings with Image and CSS Assets?
When converting HTML strings to PDF, set a BaseUrlOrPath parameter for assets such as CSS, JavaScript files, and images. The BaseUrlOrPath specifies the base URL from which all assets load relative to. CustomCssUrl
This can be a web URL starting with 'http' to load remote assets or a local file path to access assets on disk. Setting the BaseUrlOrPath correctly ensures assets load properly during conversion. For more details on HTML to PDF conversion, check our comprehensive HTML to PDF tutorial.
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");Dim renderer As New ChromePdfRenderer()
Dim baseUrl As String = "C:\site\assets\"
Dim html As String = "<img src='icons/iron.png'>"
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, baseUrl)
pdf.SaveAs("html-with-assets.pdf")For complex scenarios involving external assets, explore our guide on managing fonts or adding images to PDFs.
How Do I Configure Base URLs in MVC Applications?
In MVC applications, specifying image file paths requires careful configuration. To ensure IronPDF finds images and displays them correctly on the website, configure the baseUrl and HTML src="" attribute properly.
With the file hierarchy shown below set
baseUrlOrPathto @"wwwroot/image"srcattribute to "../image/Sample.jpg"
wwwroot
└── image
├── Sample.jpg
└── Sample.png
For example:
// 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")<!-- Correct image references for MVC -->
<img src="../image/Sample.jpg"/>
<img src="../image/Sample.png"/>
For ASP.NET Core MVC specific implementations, refer to our CSHTML to PDF (MVC Core) guide.
Which File Path Formats Should I Avoid?
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"/>
What Are Common Troubleshooting Tips for Asset Loading?
When assets fail to load, consider these troubleshooting steps:
- Verify absolute paths: Use absolute file paths during development to confirm accessibility
- Check file permissions: Ensure the application has read access to asset directories
- Test with remote URLs: Use fully qualified URLs to isolate path issues
- Enable logging: Use IronPDF's custom logging to debug asset loading
// Example: Debug asset loading with absolute paths
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Enable debug logging
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(500); // Give assets time to load
// Use absolute path for testing
string absoluteBasePath = Path.GetFullPath(@"C:\MyProject\wwwroot\assets");
string html = @"
<html>
<head>
<link rel='stylesheet' href='styles/main.css'>
</head>
<body>
<img src='images/logo.png' />
<script src='scripts/app.js'></script>
</body>
</html>";
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, absoluteBasePath);Imports System.IO
' Example: Debug asset loading with absolute paths
Dim renderer As New ChromePdfRenderer()
' Enable debug logging
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.WaitFor.RenderDelay(500) ' Give assets time to load
' Use absolute path for testing
Dim absoluteBasePath As String = Path.GetFullPath("C:\MyProject\wwwroot\assets")
Dim html As String = "
<html>
<head>
<link rel='stylesheet' href='styles/main.css'>
</head>
<body>
<img src='images/logo.png' />
<script src='scripts/app.js'></script>
</body>
</html>"
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, absoluteBasePath)How Do I Add HTML Headers and Footers with Images?
When rendering HTML headers and footers to new or existing PDFs, they're treated as standalone HTML documents and don't inherit the BaseURL from the PDF. For comprehensive header and footer options, see our headers and footers guide.
Set a BaseURL from which assets may load: ChromePdfRenderOptions
Why Don't Headers Inherit Base URLs from the Main Document?
Headers and footers render as separate HTML documents for performance and isolation. This design allows:
- Independent styling without affecting main content
- Consistent rendering across all pages
- Better memory management for large documents
- Flexibility to use different asset sources
How Do I Set Different Base URLs for Headers vs Content?
Specify different base URLs for headers, footers, and main content to organize assets effectively:
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Main content base URL
string contentBaseUrl = @"C:\website\public\";
// Header specific assets
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
HtmlFragment = "<img src='header-logo.png'><link rel='stylesheet' href='header.css'>",
BaseUrl = new Uri(@"C:\website\headers\").AbsoluteUri
};
// Footer specific assets
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
HtmlFragment = "<div class='footer'>© 2024 Company</div><link rel='stylesheet' href='footer.css'>",
BaseUrl = new Uri(@"C:\website\footers\").AbsoluteUri
};
// Render main content with its own base URL
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Main Content</h1>", contentBaseUrl);Dim renderer As New ChromePdfRenderer()
' Main content base URL
Dim contentBaseUrl As String = "C:\website\public\"
' Header specific assets
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
.HtmlFragment = "<img src='header-logo.png'><link rel='stylesheet' href='header.css'>",
.BaseUrl = New Uri("C:\website\headers\").AbsoluteUri
}
' Footer specific assets
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
.HtmlFragment = "<div class='footer'>© 2024 Company</div><link rel='stylesheet' href='footer.css'>",
.BaseUrl = New Uri("C:\website\footers\").AbsoluteUri
}
' Render main content with its own base URL
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Main Content</h1>", contentBaseUrl)The IronSuite play a crucial role in our operations. These are tools that increase efficiencies across the business including creating floor plans and improving inventory management.
How Do I Convert HTML Files to PDF with Local Assets?
When rendering HTML files to PDF, all assets are assumed local to that file. Learn more about converting HTML files in our HTML File to PDF guide.
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")In the above example, all JS, CSS and image files load from the C:\Assets folder on disk - the same directory as the HTML file.
For convenience, use CustomCssUrl in HtmlToPdf for Additional Stylesheets to specify an additional stylesheet used only for .NET PDF rendering if desired. For example:
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")CustomCssUrl
ChromePdfRenderOptions.CustomCssUrl property currently only functions when rendering from HTML strings to PDFs using the RenderHtmlAsPdf methodWhen Should I Use CustomCssUrl for Additional Styling?
CustomCssUrl is ideal for:
- Print-specific styles: Hide navigation menus or interactive elements
- PDF layout optimization: Adjust margins and page breaks for print
- Conditional formatting: Apply styles only when generating PDFs
- A/B testing: Test different PDF layouts without modifying source HTML
How Do I Handle Relative Asset Paths in HTML Files?
When working with HTML files containing relative paths, ensure your file structure supports the references:
// Example HTML file structure
/*
C:\Projects\Reports\
├── invoice.html
├── css\
│ └── styles.css
├── js\
│ └── calculations.js
└── images\
└── logo.png
*/
// HTML content with relative paths
string htmlContent = @"
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='css/styles.css'>
<script src='js/calculations.js'></script>
</head>
<body>
<img src='images/logo.png' alt='Company Logo'>
<h1>Invoice #12345</h1>
</body>
</html>";
// Save HTML and render
File.WriteAllText(@"C:\Projects\Reports\invoice.html", htmlContent);
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlFileAsPdf(@"C:\Projects\Reports\invoice.html");
pdf.SaveAs("invoice-output.pdf");Imports System.IO
Imports IronPdf
' Example HTML file structure
'
' C:\Projects\Reports\
' ├── invoice.html
' ├── css\
' │ └── styles.css
' ├── js\
' │ └── calculations.js
' └── images\
' └── logo.png
'
' HTML content with relative paths
Dim htmlContent As String = "
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='css/styles.css'>
<script src='js/calculations.js'></script>
</head>
<body>
<img src='images/logo.png' alt='Company Logo'>
<h1>Invoice #12345</h1>
</body>
</html>"
' Save HTML and render
File.WriteAllText("C:\Projects\Reports\invoice.html", htmlContent)
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("C:\Projects\Reports\invoice.html")
pdf.SaveAs("invoice-output.pdf")How Do I Encode Images Directly in HTML Using Base64?
Image assets can be encoded directly into HTML files or strings, avoiding issues with missing images. Use base64 encoding for this approach. Use base64 encoding for this approach. Use base64 encoding for this approach:
- First obtain the binary data of the image by reading the file or receiving it through a network request.
- Use the
Convert.ToBase64Stringmethod in Microsoft .NET to convert binary data to base64. - Construct the image tag in HTML using "data:image/svg+xml;base64," before the base64 data. Note that the image type is specified before the base64 data. Visit the MDN Web Docs on Image Types and Formats for more information on image format types.
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")Why Would I Choose Base64 Encoding Over File References?
Base64 encoding offers several advantages:
- Self-contained HTML: No external dependencies, simplifying distribution
- Cross-platform compatibility: Works regardless of file system differences
- Security: No file system access required, reducing security risks
- Reliability: Eliminates missing asset errors in production
- Version control: Images are part in HTML, simplifying versioning
However, consider these trade-offs:
- Increased HTML size: Base64 encoding increases size by approximately 33%
- No caching: Embedded images can't be cached separately
- Memory usage: Entire image must load in memory
What Image Formats Work Best with Base64 Encoding?
Different image formats have varying efficiency when base64 encoded:
// Example: Encoding different image formats
public string EncodeImageWithMimeType(string imagePath)
{
byte[] imageBytes = File.ReadAllBytes(imagePath);
string base64 = Convert.ToBase64String(imageBytes);
// Determine MIME type based on extension
string extension = Path.GetExtension(imagePath).ToLower();
string mimeType = extension switch
{
".png" => "image/png", // Best for graphics with transparency
".jpg" or ".jpeg" => "image/jpeg", // Best for photographs
".gif" => "image/gif", // Best for simple animations
".svg" => "image/svg+xml", // Best for scalable graphics
".webp" => "image/webp", // Best overall compression
_ => "image/png" // Default fallback
};
return $"data:{mimeType};base64,{base64}";
}
// Usage
string encodedImage = EncodeImageWithMimeType("logo.png");
string html = $"<img src='{encodedImage}' alt='Company Logo'>";' Example: Encoding different image formats
Public Function EncodeImageWithMimeType(imagePath As String) As String
Dim imageBytes As Byte() = File.ReadAllBytes(imagePath)
Dim base64 As String = Convert.ToBase64String(imageBytes)
' Determine MIME type based on extension
Dim extension As String = Path.GetExtension(imagePath).ToLower()
Dim mimeType As String = If(extension, {
".png", "image/png", ' Best for graphics with transparency
".jpg", "image/jpeg", ' Best for photographs
".jpeg", "image/jpeg", ' Best for photographs
".gif", "image/gif", ' Best for simple animations
".svg", "image/svg+xml", ' Best for scalable graphics
".webp", "image/webp" ' Best overall compression
}, "image/png") ' Default fallback
Return $"data:{mimeType};base64,{base64}"
End Function
' Usage
Dim encodedImage As String = EncodeImageWithMimeType("logo.png")
Dim html As String = $"<img src='{encodedImage}' alt='Company Logo'>"How Does Base64 Encoding Impact PDF File Size?
Base64 encoding affects PDF size in predictable ways:
// Comparison example
public void CompareFileSizes()
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Method 1: External image reference
string htmlExternal = "<img src='large-photo.jpg'>";
PdfDocument pdfExternal = renderer.RenderHtmlAsPdf(htmlExternal, @"C:\images\");
// Method 2: Base64 encoded image
byte[] imageBytes = File.ReadAllBytes(@"C:\images\large-photo.jpg");
string base64Image = Convert.ToBase64String(imageBytes);
string htmlBase64 = $"<img src='data:image/jpeg;base64,{base64Image}'>";
PdfDocument pdfBase64 = renderer.RenderHtmlAsPdf(htmlBase64);
// Compare sizes
Console.WriteLine($"Original image: {imageBytes.Length / 1024} KB");
Console.WriteLine($"PDF with external image: {pdfExternal.BinaryData.Length / 1024} KB");
Console.WriteLine($"PDF with base64 image: {pdfBase64.BinaryData.Length / 1024} KB");
}' Comparison example
Public Sub CompareFileSizes()
Dim renderer As New ChromePdfRenderer()
' Method 1: External image reference
Dim htmlExternal As String = "<img src='large-photo.jpg'>"
Dim pdfExternal As PdfDocument = renderer.RenderHtmlAsPdf(htmlExternal, "C:\images\")
' Method 2: Base64 encoded image
Dim imageBytes As Byte() = File.ReadAllBytes("C:\images\large-photo.jpg")
Dim base64Image As String = Convert.ToBase64String(imageBytes)
Dim htmlBase64 As String = $"<img src='data:image/jpeg;base64,{base64Image}'>"
Dim pdfBase64 As PdfDocument = renderer.RenderHtmlAsPdf(htmlBase64)
' Compare sizes
Console.WriteLine($"Original image: {imageBytes.Length \ 1024} KB")
Console.WriteLine($"PDF with external image: {pdfExternal.BinaryData.Length \ 1024} KB")
Console.WriteLine($"PDF with base64 image: {pdfBase64.BinaryData.Length \ 1024} KB")
End SubFor optimal results:
- Use base64 for small icons and logos (< 50KB)
- Use external references for large images and photographs
- Consider compression before encoding
- Use appropriate image formats for content type
For advanced PDF optimization techniques, explore our PDF compression guide.
Frequently Asked Questions
What is the purpose of using Base URLs in IronPDF?
Base URLs in IronPDF are used to specify the location of CSS, JavaScript, and image assets during HTML to PDF conversion, ensuring these assets are properly loaded by providing a `BaseUrlOrPath` parameter.
How can I implement base URLs in a basic scenario using IronPDF?
You can implement base URLs by setting the `BaseUrlOrPath` parameter in IronPDF's HTML to PDF generation code. This enables seamless asset loading and ensures all CSS, JavaScript, and images are correctly referenced during the conversion process.
Why might my image assets not be loading correctly in my PDF?
If image assets are not loading correctly, ensure absolute paths are used, check file permissions, test with remote URLs, and enable logging for debugging. IronPDF also provides custom options like `BaseUrlOrPath` to accurately reference asset locations.
How do I set different base URLs for PDF headers and main content in IronPDF?
In IronPDF, you can configure different base URLs for headers, footers, and main content by using the `HtmlHeaderFooter` class to set distinct `BaseUrl` properties for each section.
What should I be aware of when using `CustomCssUrl` in IronPDF?
`CustomCssUrl` is used when rendering HTML strings to PDFs. It allows you to specify additional stylesheets for better PDF rendering and is ideal for print-specific styles, PDF layout optimization, and conditional formatting.
When should I use Base64 encoding for images in IronPDF?
Base64 encoding is useful for embedding images directly into HTML content to avoid external dependency issues, enhance compatibility across platforms, and increase reliability in production environments without accessing the file system.
How does Base64 encoding affect the size of my PDFs?
Base64 encoding increases HTML and subsequently PDF size due to data being represented in a larger format. Use it for smaller images, while larger assets should use external references to optimize PDF size.
What are the benefits of using Base64 encoding in IronPDF?
Base64 encoding benefits include creating self-contained HTML, ensuring cross-platform compatibility, reducing security risks by eliminating file system access, and preventing missing asset errors in live environments.
How do I handle relative asset paths in HTML files for PDF conversion in IronPDF?
Ensure your file structure supports the relative paths in your HTML file, and use `RenderHtmlFileAsPdf` from IronPDF to convert HTML files to PDFs while correctly loading CSS and JavaScript resources.
Why don't headers and footers in IronPDF inherit Base URLs from the main document?
Headers and footers in IronPDF do not inherit Base URLs from the main document to maintain styling independence, ensure consistent rendering, and allow flexible asset organization for optimal PDF creation.

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.