How to Use Base URLs in PDF Generation with C#

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.

Quickstart: Implement Base URLs in IronPDF

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.

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


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.

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.

: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");
$vbLabelText   $csharpLabel

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

  • 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");
$vbLabelText   $csharpLabel
<!-- Correct image references for MVC -->
<img src="../image/Sample.jpg"/>
<img src="../image/Sample.png"/>
<!-- Correct image references for MVC -->
<img src="../image/Sample.jpg"/>
<img src="../image/Sample.png"/>
HTML

For ASP.NET Core MVC specific implementations, refer to our CSHTML to PDF (MVC Core) guide.

Which File Path Formats Should I Avoid?

Warning

File Path Formats That Do Not Work

These formats work in Chrome browser but point to wrong directories in MVC apps. They 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

These formats work with MVC apps but fail with IronPDF file paths:

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

What Are Common Troubleshooting Tips for Asset Loading?

When assets fail to load, consider these troubleshooting steps:

  1. Verify absolute paths: Use absolute file paths during development to confirm accessibility
  2. Check file permissions: Ensure the application has read access to asset directories
  3. Test with remote URLs: Use fully qualified URLs to isolate path issues
  4. 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);
// 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);
$vbLabelText   $csharpLabel

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:

: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
};
$vbLabelText   $csharpLabel

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);
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);
$vbLabelText   $csharpLabel

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.

: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");
$vbLabelText   $csharpLabel

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 ChromePdfRenderOptions for Additional Stylesheets to specify an additional stylesheet used only for .NET PDF rendering if desired. 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");
$vbLabelText   $csharpLabel

Please noteThe ChromePdfRenderOptions.CustomCssUrl property currently only functions when rendering from HTML strings to PDFs using the RenderHtmlAsPdf method.

When 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");
// 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");
$vbLabelText   $csharpLabel

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. For working with various image formats, see our images guide.

  1. First obtain the binary data of the image by reading the file or receiving it through a network request.
  2. Use the Convert.ToBase64String method in Microsoft .NET to convert binary data to base64.
  3. 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.
: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");
$vbLabelText   $csharpLabel

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 of 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 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'>";
$vbLabelText   $csharpLabel

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 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");
}
$vbLabelText   $csharpLabel

For 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

How do I ensure CSS and JavaScript assets load correctly when converting HTML to PDF?

IronPDF allows you to specify a BaseUrlOrPath parameter during HTML to PDF conversion. This parameter can be a web URL or local file path that serves as the base reference for all relative asset paths in your HTML, ensuring CSS, JavaScript, and images load properly.

What is the BaseUrlOrPath parameter used for?

The BaseUrlOrPath parameter in IronPDF specifies the base URL from which all assets (CSS, JavaScript, images) load relative to during HTML to PDF conversion. It can be set to either a web URL starting with 'http' for remote assets or a local file path for disk-based assets.

How can I render a PDF with assets in just one line of code?

You can use IronPDF's ChromePdfRenderer to render HTML with assets in one line: `new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("", @"C:\site\assets\").SaveAs("with-assets.pdf");`. This sets the BaseUrlOrPath to ensure all assets are properly loaded.

How do I configure image paths in MVC applications for PDF generation?

In MVC applications using IronPDF, set the baseUrlOrPath to your wwwroot subdirectory (e.g., @"wwwroot/image") and configure the HTML src attribute with the relative path (e.g., "../image/Sample.jpg"). This ensures images display correctly both on the website and in the generated PDF.

Can I use both local and remote assets when converting HTML to PDF?

Yes, IronPDF supports both local and remote assets. For remote assets, set BaseUrlOrPath to a web URL starting with 'http'. For local assets, use a file path on your disk. This flexibility allows you to reference assets from various sources during PDF generation.

What happens if I don't set the BaseUrlOrPath parameter?

Without setting the BaseUrlOrPath parameter in IronPDF, relative asset paths in your HTML won't resolve correctly, resulting in missing CSS styles, JavaScript functionality, and images in your generated PDF. Always specify this parameter when your HTML contains relative asset references.

Curtis Chau
Technical Writer

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.

...

Read More
Ready to Get Started?
Nuget Downloads 16,901,161 | Version: 2025.12 just released