How to Embed Images with DataURIs in C# & VB PDF Rendering?

When working with HTML strings and documents it is often useful to not depend on a directory of assets. To work around this issue we use DataURIs: https://en.wikipedia.org/wiki/Data_URI_scheme

DataURIs allow images, files and even typefaces to be injected directly into a html document as a string.

Basic Image Embedding Example

The following example shows the rendering of an image into a HTML document without an asset file:


IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();

var pngBinaryData =  File.ReadAllBytes("My_image.png");

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

var ImgHtml = String.Format("<img src='{0}'>", ImgDataURI);

var pdfdoc = Renderer.RenderHtmlAsPdf(ImgHtml);

pdfdoc.SaveAs("datauri_example.pdf")
Dim Renderer As IronPdf.HtmlToPdf = New IronPdf.HtmlToPdf
Dim pngBinaryData As var = File.ReadAllBytes("My_image.png")
Dim ImgDataURI As Var = ("data:image/png;base64," + Convert.ToBase64String(pngBinaryData))
Dim ImgHtml As var = String.Format("<img src='{0}'>", ImgDataURI)
Dim pdfdoc As var = Renderer.RenderHtmlAsPdf(ImgHtml)
pdfdoc.SaveAs("datauri_example.pdf")
VB   C#

System.Drawing.Image Embedding into HTML

IronPDF has a very useful method to embed a System.Drawing.Image to a HTML document which may then be rendered as a PDF.

https://ironpdf.com/c%23-pdf-documentation/html/M_IronPdf_Util_ImageToDataUri.htm

string ImgDataURI =  IronPdf.Util.ImageToDataUri(MyImage);

var ImgHtml = String.Format("<img src='{0}'>", ImgDataURI);

var pdfdoc = Renderer.RenderHtmlAsPdf(ImgHtml);

pdfdoc.SaveAs("datauri_example2.pdf")
Dim ImgDataURI As String = IronPdf.Util.ImageToDataUri(MyImage)
Dim ImgHtml As var = String.Format("<img src='{0}'>", ImgDataURI)
Dim pdfdoc As var = Renderer.RenderHtmlAsPdf(ImgHtml)
pdfdoc.SaveAs("datauri_example2.pdf")
VB   C#

We can also serve an entire HTML String or PDF document as a Byte Array to IronPDF.