Cómo renderizar imágenes almacenadas en Azure Blob Storage en C# | IronPDF

Rendering PDFs Containing Images Stored in Azure Blob Storage

This article was translated from English: Does it need improvement?
Translated
View the article in English

Azure Blob Storage is a cloud-based storage service provided by Microsoft Azure. It's designed to store large amounts of unstructured data, such as text or binary data, that can be accessed via HTTP or HTTPS.

Some developers would like to use images stored in Azure Blob Storage. This presents an issue because the image data is stored as binary rather than as a file, which could easily be referenced by HTML. The workaround is to convert images to a base64 string and add them to an img tag.

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.

    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");
  3. Deploy to test on your live environment

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


Convert Azure Blob to HTML

Assuming you have already set up an Azure Storage account and have a container with blobs, you also need to handle authentication and connection to your Azure Storage in the C# project. Afterward, you can use the DownloadToStreamAsync method to download the image as a stream. The stream information can then be converted to Base64 and embedded in the img tag of HTML. Finally, the imageTag variable can be merged into an HTML document.

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
$vbLabelText   $csharpLabel

Convert HTML to PDF

Continuing from the imageTag, it can then be converted to PDF by using the RenderHtmlAsPdf method of ChromePdfRenderer.

Below is a simple example of how you might call RenderHtmlAsPdf:

: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")
$vbLabelText   $csharpLabel

Make sure to adjust the "htmlContent" variable to include your actual HTML content where the imageTag is used.

Preguntas Frecuentes

¿Cómo puedo renderizar un PDF con imágenes desde Azure Blob Storage?

Para renderizar un PDF con imágenes desde Azure Blob Storage, puedes usar IronPDF para convertir los datos de la imagen a una cadena base64, incrustarla en una etiqueta img en HTML y luego renderizar el HTML como PDF usando el método `RenderHtmlAsPdf`.

¿Qué pasos se necesitan para convertir una imagen de Azure Blob Storage a una cadena base64?

Primero, descarga el blob de la imagen usando el método `DownloadToStreamAsync`. Luego, convierte el flujo de la imagen a un array de bytes y usa `Convert.ToBase64String` para transformarlo en una cadena base64.

¿Cómo incluyo imágenes de Azure Blob Storage en un documento HTML?

Descarga la imagen como un flujo desde Azure Blob Storage, conviértela a una cadena base64 e incrústala en una etiqueta img HTML. Esto te permite incluir la imagen directamente en el documento HTML.

¿Cuál es el papel de Azure Blob Storage en el manejo de imágenes para PDFs?

Azure Blob Storage se utiliza para almacenar datos de imagen no estructurados. Convertir estos datos a base64 permite incrustarlo en HTML, facilitando su inclusión en PDFs usando IronPDF.

¿Cómo puedo convertir contenido HTML con imágenes incrustadas en un PDF en C#?

Puedes convertir contenido HTML, incluyendo imágenes base64 incrustadas, en un PDF usando el método `RenderHtmlAsPdf` de IronPDF. Este método procesa el HTML y lo renderiza como un documento PDF.

¿Necesito autenticarme para acceder a blobs de Azure Blob Storage?

Sí, la autenticación es necesaria para establecer una conexión a tu cuenta de Azure Storage en tu proyecto de C# para acceder y gestionar blobs de forma segura.

¿Cuál es la importancia de convertir imágenes a base64 para la renderización de PDFs?

Convertir imágenes a base64 permite incrustar datos de imagen binaria directamente en documentos HTML como URLs de datos, que pueden ser renderizados con precisión en PDFs usando IronPDF.

¿Cómo puedo empezar a usar IronPDF para renderizar PDFs?

Puedes descargar IronPDF desde el gestor de paquetes NuGet. Una vez instalado, puedes usar sus métodos para renderizar contenido HTML, incluidas imágenes, en documentos PDF.

¿IronPDF es totalmente compatible con las aplicaciones .NET 10 al renderizar imágenes desde Azure Blob Storage?

Sí. IronPDF es totalmente compatible con .NET 10, lo que permite la renderización de HTML a PDF (incluyendo imágenes, CSS, JavaScript, etc.) en proyectos .NET 10, como web, escritorio o servicios en la nube. Puedes usar el mismo flujo de trabajo de descarga de blobs e incrustación en base64 en una aplicación .NET 10 sin modificaciones.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado