Rendering PDFs with Azure Blob Storage Images in C#
To render PDFs with Azure Blob Storage images in C#, retrieve the blob data as binary, convert it to a base64 string, embed it in an HTML img tag, and use IronPDF's ChromePdfRenderer to convert the HTML to PDF.
Azure Blob Storage is a cloud-based storage service provided by Microsoft Azure. It stores large amounts of unstructured data, such as text or binary data, accessible via HTTP or HTTPS. When working with PDFs in C#, IronPDF provides powerful capabilities for handling various image formats and sources, including those stored in cloud services like Azure Blob Storage.
To use images stored in Azure Blob Storage, you must handle the binary data format rather than direct file references. The solution is to convert images to base64 strings and embed them in img tags. This approach works seamlessly with IronPDF's HTML to PDF conversion features, maintaining image quality and formatting.
Quickstart: Render PDFs with Azure Blob Storage Images
-
Install IronPDF with NuGet Package Manager
PM > Install-Package IronPdf -
Copy and run this code snippet.
var blobBase64 = Convert.ToBase64String(new BlobContainerClient("conn","cont").GetBlobClient("img.jpg").DownloadContent().Value.Content.ToArray()); new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf($"<img src=\"data:image/jpeg;base64,{blobBase64}\" />").SaveAs("blobImage.pdf"); -
Deploy to test on your live environment
Start using IronPDF in your project today with a free trial
Minimal Workflow (5 steps)
- Download IronPDF for rendering images stored in Azure Blob
- Handle the process of retrieving the blob
- Use the
ToBase64Stringmethod to convert bytes to base64 - Include the base64 information in the
imgtag - Render the HTML to PDF
How Do I Convert Azure Blob Images to HTML?
Set up an Azure Storage account with a container containing blobs, then handle authentication and connection in your C# project. Use the Azure.Storage.Blobs NuGet package alongside IronPDF. For complex authentication scenarios, explore IronPDF's HTTP request header capabilities for secured blob access.
Use the DownloadAsync method to download images as streams. Convert the stream data to Base64 and embed it in HTML img tags. Merge the htmlContent variable into your HTML document. This technique works well for creating reports or documents with dynamically loaded cloud storage images.
using Azure.Storage.Blobs;
using System;
using System.IO;
using System.Threading.Tasks;
public async Task ConvertBlobToHtmlAsync()
{
// Define your connection string and container name
string connectionString = "your_connection_string";
string containerName = "your_container_name";
// Initialize BlobServiceClient with the connection string
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
// Get the BlobContainerClient for the specified container
BlobContainerClient blobContainer = blobServiceClient.GetBlobContainerClient(containerName);
// Get the reference to the blob and initialize a stream
BlobClient blobClient = blobContainer.GetBlobClient("867.jpg");
using var stream = new MemoryStream();
// Download the blob data to the stream
await blobClient.DownloadToAsync(stream);
stream.Position = 0; // Reset stream position
// Convert the stream to a byte array
byte[] array = stream.ToArray();
// Convert bytes to base64
var base64 = Convert.ToBase64String(array);
// Create an img tag with the base64-encoded string
var imageTag = $"<img src=\"data:image/jpeg;base64,{base64}\"/><br/>";
// Use the imageTag in your HTML document as needed
}
using Azure.Storage.Blobs;
using System;
using System.IO;
using System.Threading.Tasks;
public async Task ConvertBlobToHtmlAsync()
{
// Define your connection string and container name
string connectionString = "your_connection_string";
string containerName = "your_container_name";
// Initialize BlobServiceClient with the connection string
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
// Get the BlobContainerClient for the specified container
BlobContainerClient blobContainer = blobServiceClient.GetBlobContainerClient(containerName);
// Get the reference to the blob and initialize a stream
BlobClient blobClient = blobContainer.GetBlobClient("867.jpg");
using var stream = new MemoryStream();
// Download the blob data to the stream
await blobClient.DownloadToAsync(stream);
stream.Position = 0; // Reset stream position
// Convert the stream to a byte array
byte[] array = stream.ToArray();
// Convert bytes to base64
var base64 = Convert.ToBase64String(array);
// Create an img tag with the base64-encoded string
var imageTag = $"<img src=\"data:image/jpeg;base64,{base64}\"/><br/>";
// Use the imageTag in your HTML document as needed
}
Imports Azure.Storage.Blobs
Imports System
Imports System.IO
Imports System.Threading.Tasks
Public Async Function ConvertBlobToHtmlAsync() As Task
' Define your connection string and container name
Dim connectionString As String = "your_connection_string"
Dim containerName As String = "your_container_name"
' Initialize BlobServiceClient with the connection string
Dim blobServiceClient As New BlobServiceClient(connectionString)
' Get the BlobContainerClient for the specified container
Dim blobContainer As BlobContainerClient = blobServiceClient.GetBlobContainerClient(containerName)
' Get the reference to the blob and initialize a stream
Dim blobClient As BlobClient = blobContainer.GetBlobClient("867.jpg")
Dim stream = New MemoryStream()
' Download the blob data to the stream
Await blobClient.DownloadToAsync(stream)
stream.Position = 0 ' Reset stream position
' Convert the stream to a byte array
Dim array() As Byte = stream.ToArray()
' Convert bytes to base64
Dim base64 = Convert.ToBase64String(array)
' Create an img tag with the base64-encoded string
Dim imageTag = $"<img src=""data:image/jpeg;base64,{base64}""/><br/>"
' Use the imageTag in your HTML document as needed
End Function
When working with multiple images or different formats, leverage IronPDF's support for various image types including JPG, PNG, SVG, and GIF. The base64 encoding method works universally across all these formats.
Working with Different Image Formats
Azure Blob Storage supports various image formats, and IronPDF handles them all when properly encoded. Here's an enhanced example that dynamically determines the MIME type:
public string GetImageMimeType(string blobName)
{
var extension = Path.GetExtension(blobName).ToLower();
return extension switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".svg" => "image/svg+xml",
".webp" => "image/webp",
_ => "image/jpeg" // default fallback
};
}
public async Task<string> CreateImageTagFromBlob(BlobClient blobClient)
{
using var stream = new MemoryStream();
await blobClient.DownloadToAsync(stream);
stream.Position = 0;
var base64 = Convert.ToBase64String(stream.ToArray());
var mimeType = GetImageMimeType(blobClient.Name);
return $"<img src=\"data:{mimeType};base64,{base64}\" alt=\"{Path.GetFileNameWithoutExtension(blobClient.Name)}\"/>";
}
public string GetImageMimeType(string blobName)
{
var extension = Path.GetExtension(blobName).ToLower();
return extension switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".svg" => "image/svg+xml",
".webp" => "image/webp",
_ => "image/jpeg" // default fallback
};
}
public async Task<string> CreateImageTagFromBlob(BlobClient blobClient)
{
using var stream = new MemoryStream();
await blobClient.DownloadToAsync(stream);
stream.Position = 0;
var base64 = Convert.ToBase64String(stream.ToArray());
var mimeType = GetImageMimeType(blobClient.Name);
return $"<img src=\"data:{mimeType};base64,{base64}\" alt=\"{Path.GetFileNameWithoutExtension(blobClient.Name)}\"/>";
}
Imports System.IO
Imports System.Threading.Tasks
Public Function GetImageMimeType(blobName As String) As String
Dim extension = Path.GetExtension(blobName).ToLower()
Select Case extension
Case ".jpg", ".jpeg"
Return "image/jpeg"
Case ".png"
Return "image/png"
Case ".gif"
Return "image/gif"
Case ".svg"
Return "image/svg+xml"
Case ".webp"
Return "image/webp"
Case Else
Return "image/jpeg" ' default fallback
End Select
End Function
Public Async Function CreateImageTagFromBlob(blobClient As BlobClient) As Task(Of String)
Using stream As New MemoryStream()
Await blobClient.DownloadToAsync(stream)
stream.Position = 0
Dim base64 = Convert.ToBase64String(stream.ToArray())
Dim mimeType = GetImageMimeType(blobClient.Name)
Return $"<img src=""data:{mimeType};base64,{base64}"" alt=""{Path.GetFileNameWithoutExtension(blobClient.Name)}""/>"
End Using
End Function
How Do I Convert the HTML to PDF?
Convert the htmlContent to PDF using the RenderHtmlAsPdf() method of ChromePdfRenderer. IronPDF's Chrome rendering engine maintains image quality and positioning during conversion. For optimal results, configure rendering options to control PDF output quality.
Here's how to call SaveAs():
:path=/static-assets/pdf/content-code-examples/how-to/images-azure-blob-storage-html-to-pdf.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf(imageTag);
// Export to a file
pdf.SaveAs("imageToPdf.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Create a PDF from a HTML string using C#
Private pdf = renderer.RenderHtmlAsPdf(imageTag)
' Export to a file
pdf.SaveAs("imageToPdf.pdf")
Adjust the pdfOptions variable to include your actual HTML content with the bodyHtml.
Complete Working Example
Here's a comprehensive example combining Azure Blob Storage retrieval with IronPDF rendering, including error handling and optimization:
using Azure.Storage.Blobs;
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
public class AzureBlobToPdfConverter
{
private readonly string _connectionString;
private readonly ChromePdfRenderer _renderer;
public AzureBlobToPdfConverter(string connectionString)
{
_connectionString = connectionString;
_renderer = new ChromePdfRenderer();
// Configure rendering options for better image quality
_renderer.RenderingOptions.ImageQuality = 100;
_renderer.RenderingOptions.DpiResolution = 300;
}
public async Task<PdfDocument> ConvertBlobImagesToPdfAsync(string containerName, List<string> blobNames)
{
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<html><body style='margin: 20px;'>");
var blobServiceClient = new BlobServiceClient(_connectionString);
var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
foreach (var blobName in blobNames)
{
try
{
var blobClient = containerClient.GetBlobClient(blobName);
var imageTag = await CreateImageTagFromBlob(blobClient);
htmlBuilder.Append(imageTag);
htmlBuilder.Append("<br/><br/>"); // Add spacing between images
}
catch (Exception ex)
{
// Log error and continue with other images
Console.WriteLine($"Error processing blob {blobName}: {ex.Message}");
}
}
htmlBuilder.Append("</body></html>");
// Convert the complete HTML to PDF
return _renderer.RenderHtmlAsPdf(htmlBuilder.ToString());
}
private async Task<string> CreateImageTagFromBlob(BlobClient blobClient)
{
using var stream = new MemoryStream();
await blobClient.DownloadToAsync(stream);
stream.Position = 0;
var base64 = Convert.ToBase64String(stream.ToArray());
var mimeType = GetImageMimeType(blobClient.Name);
return $"<img src=\"data:{mimeType};base64,{base64}\" " +
$"alt=\"{Path.GetFileNameWithoutExtension(blobClient.Name)}\" " +
$"style=\"max-width: 100%; height: auto;\"/>";
}
private string GetImageMimeType(string blobName)
{
var extension = Path.GetExtension(blobName).ToLower();
return extension switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".svg" => "image/svg+xml",
".webp" => "image/webp",
_ => "image/jpeg"
};
}
}
using Azure.Storage.Blobs;
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
public class AzureBlobToPdfConverter
{
private readonly string _connectionString;
private readonly ChromePdfRenderer _renderer;
public AzureBlobToPdfConverter(string connectionString)
{
_connectionString = connectionString;
_renderer = new ChromePdfRenderer();
// Configure rendering options for better image quality
_renderer.RenderingOptions.ImageQuality = 100;
_renderer.RenderingOptions.DpiResolution = 300;
}
public async Task<PdfDocument> ConvertBlobImagesToPdfAsync(string containerName, List<string> blobNames)
{
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<html><body style='margin: 20px;'>");
var blobServiceClient = new BlobServiceClient(_connectionString);
var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
foreach (var blobName in blobNames)
{
try
{
var blobClient = containerClient.GetBlobClient(blobName);
var imageTag = await CreateImageTagFromBlob(blobClient);
htmlBuilder.Append(imageTag);
htmlBuilder.Append("<br/><br/>"); // Add spacing between images
}
catch (Exception ex)
{
// Log error and continue with other images
Console.WriteLine($"Error processing blob {blobName}: {ex.Message}");
}
}
htmlBuilder.Append("</body></html>");
// Convert the complete HTML to PDF
return _renderer.RenderHtmlAsPdf(htmlBuilder.ToString());
}
private async Task<string> CreateImageTagFromBlob(BlobClient blobClient)
{
using var stream = new MemoryStream();
await blobClient.DownloadToAsync(stream);
stream.Position = 0;
var base64 = Convert.ToBase64String(stream.ToArray());
var mimeType = GetImageMimeType(blobClient.Name);
return $"<img src=\"data:{mimeType};base64,{base64}\" " +
$"alt=\"{Path.GetFileNameWithoutExtension(blobClient.Name)}\" " +
$"style=\"max-width: 100%; height: auto;\"/>";
}
private string GetImageMimeType(string blobName)
{
var extension = Path.GetExtension(blobName).ToLower();
return extension switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".svg" => "image/svg+xml",
".webp" => "image/webp",
_ => "image/jpeg"
};
}
}
Imports Azure.Storage.Blobs
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Text
Imports System.Threading.Tasks
Public Class AzureBlobToPdfConverter
Private ReadOnly _connectionString As String
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New(connectionString As String)
_connectionString = connectionString
_renderer = New ChromePdfRenderer()
' Configure rendering options for better image quality
_renderer.RenderingOptions.ImageQuality = 100
_renderer.RenderingOptions.DpiResolution = 300
End Sub
Public Async Function ConvertBlobImagesToPdfAsync(containerName As String, blobNames As List(Of String)) As Task(Of PdfDocument)
Dim htmlBuilder As New StringBuilder()
htmlBuilder.Append("<html><body style='margin: 20px;'>")
Dim blobServiceClient As New BlobServiceClient(_connectionString)
Dim containerClient = blobServiceClient.GetBlobContainerClient(containerName)
For Each blobName In blobNames
Try
Dim blobClient = containerClient.GetBlobClient(blobName)
Dim imageTag = Await CreateImageTagFromBlob(blobClient)
htmlBuilder.Append(imageTag)
htmlBuilder.Append("<br/><br/>") ' Add spacing between images
Catch ex As Exception
' Log error and continue with other images
Console.WriteLine($"Error processing blob {blobName}: {ex.Message}")
End Try
Next
htmlBuilder.Append("</body></html>")
' Convert the complete HTML to PDF
Return _renderer.RenderHtmlAsPdf(htmlBuilder.ToString())
End Function
Private Async Function CreateImageTagFromBlob(blobClient As BlobClient) As Task(Of String)
Using stream As New MemoryStream()
Await blobClient.DownloadToAsync(stream)
stream.Position = 0
Dim base64 = Convert.ToBase64String(stream.ToArray())
Dim mimeType = GetImageMimeType(blobClient.Name)
Return $"<img src=""data:{mimeType};base64,{base64}"" " &
$"alt=""{Path.GetFileNameWithoutExtension(blobClient.Name)}"" " &
$"style=""max-width: 100%; height: auto;""/>"
End Using
End Function
Private Function GetImageMimeType(blobName As String) As String
Dim extension = Path.GetExtension(blobName).ToLower()
Return extension Select Case extension
Case ".jpg", ".jpeg"
Return "image/jpeg"
Case ".png"
Return "image/png"
Case ".gif"
Return "image/gif"
Case ".svg"
Return "image/svg+xml"
Case ".webp"
Return "image/webp"
Case Else
Return "image/jpeg"
End Select
End Function
End Class
Performance Considerations
When working with large images or multiple blobs, implement async and multithreading techniques to improve performance. Add caching mechanisms to avoid downloading the same blobs repeatedly.
For production environments, especially Azure deployments, review IronPDF's Azure deployment guide for best practices and configuration recommendations. For memory-intensive operations, use IronPDF's memory stream capabilities to optimize resource usage.
Security and Authentication
Ensure proper authentication when accessing Azure Blob Storage. For enhanced security, implement custom HTTP headers when accessing protected resources. Consider implementing PDF password protection for sensitive documents containing Azure blob images.
Troubleshooting Common Issues
If you encounter blob storage integration issues, consult IronPDF's Azure troubleshooting guide for solutions to common problems. For image-specific issues, the image rendering documentation provides detailed guidance on handling various scenarios.
DownloadToStreamAsync
imageTag
imageTag
RenderHtmlAsPdf
RenderHtmlAsPdf
"htmlContent"
imageTag
Frequently Asked Questions
How do I generate PDFs with images stored in Azure Blob Storage?
To generate PDFs with Azure Blob Storage images, retrieve the blob data as binary, convert it to a base64 string, embed it in an HTML img tag, and use IronPDF's ChromePdfRenderer to convert the HTML to PDF. This approach works seamlessly with IronPDF's HTML to PDF conversion features while maintaining image quality.
What's the quickest way to render an Azure Blob image into a PDF?
The quickest method is using IronPDF with a one-line approach: retrieve the blob using BlobContainerClient, convert it to base64 with Convert.ToBase64String(), embed it in an img tag, and render with IronPDF's ChromePdfRenderer().RenderHtmlAsPdf() method.
Why can't I use direct file references for Azure Blob Storage images in PDFs?
Azure Blob Storage requires handling binary data format rather than direct file references. The solution is to convert images to base64 strings and embed them in img tags, which IronPDF can then process through its HTML to PDF conversion capabilities.
What NuGet packages do I need to work with Azure Blob images in PDFs?
You'll need the Azure.Storage.Blobs NuGet package for blob storage operations alongside IronPDF for PDF rendering. IronPDF provides the ChromePdfRenderer for converting HTML with embedded base64 images to PDF documents.
How do I handle authentication for secured Azure Blob access when generating PDFs?
Set up an Azure Storage account with proper authentication and connection in your C# project. For complex authentication scenarios, you can explore IronPDF's HTTP request header capabilities to handle secured blob access when rendering PDFs.

