How to Embed Images with Data URIs in C# | IronPDF

Embed Images with DataURIs in C# & VB PDF Rendering

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 seamless 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 allow 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.

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.StaticRenderHtmlAsPdf("<img src='data:image/png;base64,...' />").SaveAs("output.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 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:

:path=/static-assets/pdf/content-code-examples/how-to/datauris-image.cs
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");
$vbLabelText   $csharpLabel

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

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

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 robust PDF solutions.

Frequently Asked Questions

What are DataURIs and why use them for PDF generation?

DataURIs are a scheme that embeds data directly into HTML or CSS code as base64-encoded strings, eliminating the need for separate image files. IronPDF fully supports DataURIs, making them ideal for cloud environments, distributed systems, or when you need self-contained PDFs without external file dependencies.

How do I convert an image to a DataURI format for PDF embedding?

With IronPDF, converting an image to DataURI involves three steps: First, read the image bytes using System.IO.File.ReadAllBytes(). Second, convert the bytes to base64 using Convert.ToBase64String(). Finally, embed the base64 string in an HTML img tag with the format 'data:image/png;base64,[base64string]'.

What image formats are supported when embedding images as DataURIs?

IronPDF supports embedding various image formats as DataURIs including PNG, JPEG, GIF, and SVG. This flexibility allows you to work with different image types while maintaining full control over the PDF generation workflow.

Can I embed multiple images using DataURIs in a single PDF?

Yes, IronPDF allows you to embed multiple images using DataURIs in a single PDF document. Simply convert each image to its base64 representation and include them in your HTML markup before rendering with IronPDF's ChromePdfRenderer.

Is there a performance impact when using DataURIs instead of file references?

While DataURIs increase the HTML string size due to base64 encoding, IronPDF handles the conversion efficiently. The trade-off is worthwhile when you need self-contained PDFs without external dependencies, especially in cloud or distributed environments.

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 17,012,929 | Version: 2025.12 just released