Embed Images with DataURIs in C# & VB PDF Rendering
When working with HTML strings and documents, it is often useful not to depend on a directory of assets. To work around this issue, we use the data URI scheme.
The data URI scheme is a method used in web development to embed data directly into HTML or CSS code, eliminating the need for separate files. Data URIs allow images, files, and even typefaces to be injected directly into an HTML document as a string.
Get started with IronPDF
Start using IronPDF in your project today with a free trial.
How to Embed Images with Data URI Scheme
- Download IronPDF from NuGet
- Read the image byte using the ReadAllBytes method
- Use the ToBase64String method to convert bytes to base64
- Include the base64 information in the img tag
- Render the HTML to PDF
Basic Image Embedding Example
The following example shows the rendering of an image into an HTML document without an asset file:
: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");
We can also serve an entire HTML String or PDF document as a Byte Array using IronPDF's ASP.NET MVC Integration.