IRONSOFTWAREHOME

Embed Images with DataURIs in C# & VB PDF Rendering

Curtis Chau
Curtis Chau
Updated: August 2, 2026

Embed images directly into PDF documents using DataURIs in C# and VB.NET with IronPDF, eliminating external file dependencies by converting image bytes to base64 strings and including them inline within HTML markup for smooth PDF rendering.

When working with HTML strings and documents, avoiding dependencies on asset directories is often essential. The data URI scheme provides an effective solution.

The data URI scheme embeds data directly into HTML or CSS code, eliminating the need for separate files. DataURIs allows images, files, and typefaces to be injected directly into an HTML document as a string.

Quickstart: Embed Images in PDFs Using DataURIs

Transform HTML content into PDF documents by embedding images using DataURIs with IronPDF. This guide demonstrates how to render PDFs with embedded images using simple, efficient code. IronPDF converts HTML to PDF while maintaining image integrity. Here's a straightforward example showing how to embed an image directly into your PDF document using DataURI with minimal code.

  1. 1Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2Copy and run this code snippet.

    IronPdf.ChromePdfRenderer.StaticRenderHtmlAsPdf("<img src='data:image/png;base64,...' />").SaveAs("output.pdf");
    C#
  3. 3Deploy to test on your live environment

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

How Do I Embed Images Using DataURIs in PDFs?

Embedding images using DataURIs includes images directly within HTML markup without referencing external files. This approach works well when generating PDFs in cloud environments, distributed systems, or when ensuring all resources are self-contained. IronPDF's HTML to PDF conversion fully supports DataURIs, enabling professional PDF creation with embedded images.

The process involves three steps: reading the image data, converting it to base64 format, and embedding it within an HTML img tag. This method works with various image formats including PNG, JPEG, GIF, and SVG, providing flexibility in PDF generation workflows. The technique remains consistent whether working with Azure Blob Storage images or local files.

Basic Image Embedding Example

This complete example demonstrates how to embed an image into a PDF using DataURIs:

using IronPdf;
using System;

// Read byte from image file
var pngBinaryData = System.IO.File.ReadAllBytes("My_image.png");

// Convert bytes to base64
var ImgDataURI = @"data:image/png;base64," + Convert.ToBase64String(pngBinaryData);

// Import base64 to img tag
var ImgHtml = $"<img src='{ImgDataURI}'>";

ChromePdfRenderer Renderer = new ChromePdfRenderer();

// Render the HTML string
var pdf = Renderer.RenderHtmlAsPdf(ImgHtml);

pdf.SaveAs("datauri_example.pdf");

VB.NET developers can achieve the same functionality using IronPDF's VB.NET PDF library:

Imports IronPdf
Imports System

' Read byte from image file
Dim pngBinaryData As Byte() = System.IO.File.ReadAllBytes("My_image.png")

' Convert bytes to base64
Dim ImgDataURI As String = "data:image/png;base64," & Convert.ToBase64String(pngBinaryData)

' Import base64 to img tag
Dim ImgHtml As String = $"<img src='{ImgDataURI}'>"

Dim Renderer As New ChromePdfRenderer()

' Render the HTML string
Dim pdf = Renderer.RenderHtmlAsPdf(ImgHtml)

pdf.SaveAs("datauri_example.pdf")
VB .NET

Why Should I Use DataURIs Instead of File References?

DataURIs offers several advantages over traditional file references when generating PDFs. First, they eliminate dependencies on external files, making PDF generation more reliable and portable. This is crucial in cloud environments like Azure or AWS Lambda where file system access may be limited or performance-sensitive.

Second, DataURIs ensures PDFs are completely self-contained. When sharing or distributing generated PDFs, broken image links or missing resources aren't a concern. This makes DataURIs ideal for generating reports, invoices, or documents requiring archival or email distribution.

Third, DataURIs can improve performance in certain scenarios. Since image data is embedded directly in HTML, no additional HTTP requests or file system operations occur during rendering. This leads to faster PDF generation, especially when handling multiple small images.

What Image Formats Are Supported?

IronPDF supports all major image formats through DataURIs, providing flexibility in PDF generation workflows:

  • PNG: Ideal for images with transparency or graphics with sharp edges. Use data:image/png;base64,
  • JPEG: Best for photographs and complex images with many colors. Use data:image/jpeg;base64,
  • GIF: Suitable for simple animations or images with limited colors. Use data:image/gif;base64,
  • SVG: Perfect for scalable vector graphics. Use data:image/svg+xml;base64,
  • WebP: Modern format with excellent compression. Use data:image/webp;base64,

The following example shows how to handle different image formats:

using IronPdf;
using System;
using System.IO;

public class MultiFormatImageEmbedding
{
    public static void EmbedVariousImageFormats()
    {
        var renderer = new ChromePdfRenderer();
        
        // Function to create DataURI from image file
        string CreateDataUri(string filePath, string mimeType)
        {
            var imageBytes = File.ReadAllBytes(filePath);
            return $"data:{mimeType};base64,{Convert.ToBase64String(imageBytes)}";
        }
        
        // Create HTML with multiple image formats
        var html = $@"
        <html>
        <body>
            <h1>Multi-Format Image Test</h1>
            <img src='{CreateDataUri("logo.png", "image/png")}' alt='PNG Logo' />
            <img src='{CreateDataUri("photo.jpg", "image/jpeg")}' alt='JPEG Photo' />
            <img src='{CreateDataUri("icon.svg", "image/svg+xml")}' alt='SVG Icon' />
        </body>
        </html>";
        
        var pdf = renderer.RenderHtmlAsPdf(html);
        pdf.SaveAs("multi_format_images.pdf");
    }
}

For advanced image handling, including adding images to existing PDFs, IronPDF provides comprehensive support.

How Does Base64 Encoding Affect File Size?

Base64 encoding increases data size by approximately 33%. Base64 represents binary data using only 64 ASCII characters, requiring 4 characters to represent every 3 bytes of original data. While this increases overall size, the impact on PDF generation is often minimal compared to the benefits of self-contained documents.

Optimize file sizes when using DataURIs by following these practices:

  1. Compress images before encoding: Use tools or libraries to optimize image files before converting to base64
  2. Choose appropriate formats: Use JPEG for photos, PNG for graphics with transparency
  3. Resize images appropriately: Don't embed images larger than necessary for PDF output
  4. Consider PDF compression: Use IronPDF's compression features after generation

This example demonstrates image optimization before embedding:

using IronPdf;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public class OptimizedImageEmbedding
{
    public static void EmbedOptimizedImage(string imagePath, int maxWidth = 800)
    {
        // Load and resize image if necessary
        using (var originalImage = Image.FromFile(imagePath))
        {
            var resizedImage = originalImage;
            
            if (originalImage.Width > maxWidth)
            {
                var ratio = (double)maxWidth / originalImage.Width;
                var newHeight = (int)(originalImage.Height * ratio);
                resizedImage = new Bitmap(originalImage, maxWidth, newHeight);
            }
            
            // Convert to optimized JPEG
            using (var ms = new MemoryStream())
            {
                var encoder = ImageCodecInfo.GetImageEncoders()
                    .First(c => c.FormatID == ImageFormat.Jpeg.Guid);
                var encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = new EncoderParameter(
                    System.Drawing.Imaging.Encoder.Quality, 85L);
                
                resizedImage.Save(ms, encoder, encoderParams);
                var imageBytes = ms.ToArray();
                
                // Create DataURI
                var dataUri = $"data:image/jpeg;base64,{Convert.ToBase64String(imageBytes)}";
                
                // Generate PDF
                var html = $@"
                <html>
                <body>
                    <h1>Optimized Image Example</h1>
                    <img src='{dataUri}' style='max-width: 100%;' />
                </body>
                </html>";
                
                var renderer = new ChromePdfRenderer();
                var pdf = renderer.RenderHtmlAsPdf(html);
                pdf.SaveAs("optimized_image.pdf");
            }
            
            if (resizedImage != originalImage)
                resizedImage.Dispose();
        }
    }
}

My favorite library of this kind is IronPDF. It allows for fast and efficient manipulation of PDF files. It also has many valuable features, like exporting to PDF/A format and digitally signing PDF documents.

Milan Jovanovic

Microsoft MVP

View case study

IronOCR means we can save $40,000 annually from manual processing, while enhancing productivity and freeing up resources for high-impact tasks. I would highly recommend it.

Brent Matzelle

Chief Technology Officer, OPYN

View case study

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.

David Jones

Lead Software Engineer, Agorus Build

View case study

Advanced Techniques and Best Practices

When working with DataURIs in production environments, implement caching mechanisms to avoid repeatedly encoding the same images. This is particularly important when generating multiple PDFs with shared resources. Leverage IronPDF's async capabilities for better performance when processing multiple images.

For complex documents with many images, use a hybrid approach where critical images are embedded as DataURIs while larger, optional images are referenced externally. This balances self-contained documents with reasonable file sizes.

You can also serve an entire HTML String or PDF document as a Byte Array using IronPDF's ASP.NET MVC Integration. This technique works well when building web applications that generate and serve PDFs dynamically.

For advanced PDF manipulation techniques, including watermarking, digital signatures, and form creation, IronPDF provides comprehensive documentation and examples to build reliable PDF solutions.


Use using IronPdf directive to include the IronPdf namespace in your C# or VB.NET projects.

AddBookmarkAtEnd method is used to append new bookmarks to the PDF outline.

Frequently Asked Questions

What is a DataURI and why is it useful in PDF creation?

A DataURI embeds data directly within HTML or CSS as a string, eliminating the need for separate files. This technique is useful in PDF creation as it enables images to be included directly in PDFs without external file dependencies, improving portability and reliability in cloud or distributed environments.

How can I embed an image in a PDF using DataURIs in C#?

You can embed images in PDFs using DataURIs by converting image bytes to a base64 string and including them within an HTML img tag that IronPDF will then render as part of the PDF. This process involves reading the image data, converting it to base64, and embedding it within HTML.

Does IronPDF support multiple image formats for DataURIs?

Yes, IronPDF supports multiple image formats including PNG, JPEG, GIF, SVG, and WebP when using DataURIs. This flexibility allows for proper image embedding based on the type of content, such as using PNG for transparency or JPEG for photos.

Why should I use DataURIs instead of traditional file paths in PDFs?

Using DataURIs eliminates file dependencies, ensuring your PDFs are self-contained and reliable without broken links. It improves portability, particularly in environments with limited file system access, and can enhance performance as it removes the need for additional HTTP requests during rendering.

How does base64 encoding impact the file size of PDFs?

Base64 encoding increases data size by approximately 33%. Although this can inflate file size, the advantage of having a self-contained PDF often outweighs the increase in size. You can mitigate size impacts by compressing images before encoding and using format-appropriate images.

What are the steps to convert an image to a DataURI for embedding?

To convert an image to a DataURI, read the image bytes using a method like ReadAllBytes, convert these bytes to a base64 string with ToBase64String, then form a DataURI by prepending the mime type, such as 'data:image/png;base64,'. Use this as the src in an HTML img tag within your PDF rendering code.

How can I optimize images when using DataURIs in PDFs?

Optimize images by compressing them before encoding to base64, choosing the appropriate image format, and resizing images to reduce unnecessary file size. Additionally, IronPDF's PDF compression features can help manage file sizes after generation.

Can I handle multiple image formats in a single PDF using DataURIs with IronPDF?

Yes, you can handle multiple image formats by creating DataURIs for each format and including them within an HTML document. IronPDF can render this HTML into a PDF, preserving each image format such as PNG, JPEG, and SVG within the same document.

What are the advantages of using IronPDF for embedding images with DataURIs?

IronPDF simplifies the process of embedding images with DataURIs by offering smooth conversion of HTML with inline images to PDFs. It supports reliable PDF generation, including advanced features like compression and dynamic content processing suitable for professional use.

How can I improve performance when generating PDFs with multiple images?

Improve performance by caching encoded DataURI images, using async capabilities, and considering a hybrid approach where critical images are embedded while larger images are referenced externally. This keeps PDFs efficient without compromising on essential embedded content.

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 21,105,021Version:2026.9just released

Get your FREE

30-day Trial Key instantly.

bullet_checkedNo credit card or account creation required
bullet_testTest in production
without watermarks
bullet_calendar30 days fully
functional product
bullet_support24/5 technical
support during trial
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

OR
bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999