如何在 C# 中渲染儲存於 Azure Blob Storage 的圖片 | IronPDF

在C#中使用Azure Blob Storage的圖片來渲染PDF

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

要在C#中使用Azure Blob Storage的圖片渲染PDF,需先將Blob資料作為二進位檔案取回,轉換為base64字串,嵌入HTML的ChromePdfRenderer將HTML轉換為PDF。

Azure Blob Storage是由Microsoft Azure提供的基於雲端的儲存服務。 它儲存大量非結構化資料,如文字或二進位資料,可通過HTTP或HTTPS存取。 當在C#中處理PDF時,IronPDF提供強大的能力來處理各種圖片格式和來源,包括儲存在像Azure Blob Storage這樣的雲服務中的圖片。

要使用儲存在Azure Blob Storage中的圖片,您必須處理二進位資料格式,而不是直接的文件引用。 解決方案是將圖像轉換為base64字串並嵌入到img標籤中。 這種方法與IronPDF的HTML轉PDF轉換功能完美融合,保持圖片質量和格式。

快速開始:使用Azure Blob Storage圖像渲染PDF

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 複製並運行這段程式碼片段。

    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. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPDF,透過免費試用

    arrow pointer


如何將Azure Blob圖像轉換為HTML?

設置包含Blob的Azure Storage帳戶,然後在您的C#專案中進行身份驗證和連接。 在使用IronPDF的同時使用Azure.Storage.Blobs NuGet套件。 對於複雜的身份驗證場景,探索IronPDF的HTTP請求頭功能以獲取安全的Blob存取。

使用DownloadAsync方法作為流下載圖像。 將流資料轉換為Base64並嵌入HTML img標籤中。 將htmlContent變數合併到您的HTML文件中。 此技術適用於建立具有動態載入雲儲存圖像的報表或文件。

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

當處理多個圖片或不同格式時,利用IronPDF支持的各種圖片型別包括JPG、PNG、SVG和GIF。 base64編碼方法在這些格式中普遍適用。

處理不同的圖片格式

Azure Blob Storage支持多種圖片格式,當正確編碼時,IronPDF可以處理所有格式。 這是一個可以動態確定MIME型別的增強範例:

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

如何將HTML轉換為PDF?

使用htmlContent轉換為PDF。 IronPDF的Chrome渲染引擎在轉換過程中保持圖片質量和定位。 為獲得最佳效果,配置渲染選項以控制PDF輸出質量。

以下是如何呼叫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")
$vbLabelText   $csharpLabel

調整bodyHtml

完整的工作範例

這是一個結合Azure Blob Storage提取與IronPDF渲染的完整範例,包括錯誤處理和優化:

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

性能考量

當處理大型圖像或多個Blob時,實施非同步和多執行緒技術以提高效能。 新增快取機制以避免重複下載相同的Blob。

對於生產環境,尤其是Azure部署,檢閱IronPDF的Azure部署指南以獲取最佳實踐和配置建議。 對於記憶體密集型操作,使用IronPDF的記憶體流功能來優化資源使用。

安全和身份驗證

在存取Azure Blob Storage時確保正確的身份驗證。 為增強安全性,在存取受保護的資源時實現自訂HTTP標頭。 考慮為包含Azure Blob圖像的敏感文件實施PDF密碼保護

常見問題排解

如果遇到Blob儲存整合問題,請參考IronPDF的Azure排錯指南以獲取常見問題的解決方案。 針對特定影像問題,影像渲染文件提供處理各種情境的詳細指導。

DownloadToStreamAsync imageTag imageTag RenderHtmlAsPdf RenderHtmlAsPdf "htmlContent" imageTag

常見問題

如何將儲存於 Azure Blob Storage 中的圖片生成 PDF 檔案?

若要使用 Azure Blob Storage 中的圖片生成 PDF,請將 Blob 資料以二進位格式擷取,轉換為 base64 字串,嵌入 HTML img 標籤中,並使用 IronPDF 的 ChromePdfRenderer 將 HTML 轉換為 PDF。此方法能與 IronPDF 的 HTML 轉 PDF 功能無縫整合,同時維持圖片品質。

將 Azure Blob 影像渲染為 PDF 的最快方法是什麼?

最快速的方法是使用 IronPDF 並採用單行式做法:透過 BlobContainerClient 取得 blob,使用 Convert.ToBase64String() 將其轉換為 base64,嵌入 img 標籤中,並透過 IronPDF 的 ChromePdfRenderer().RenderHtmlAsPdf() 方法進行渲染。

為何無法在 PDF 中直接引用 Azure Blob Storage 影像檔案?

Azure Blob Storage 需要處理二進位資料格式,而非直接的檔案參照。解決方案是將圖片轉換為 base64 字串並嵌入 img 標籤中,IronPDF 隨後可透過其 HTML 轉 PDF 轉換功能進行處理。

若要在 PDF 中處理 Azure Blob 影像,我需要哪些 NuGet 套件?

您需要 Azure.Storage.Blobs NuGet 套件來執行 Blob 儲存操作,並搭配 IronPDF 進行 PDF 渲染。IronPDF 提供 ChromePdfRenderer,用於將內嵌 base64 圖片的 HTML 轉換為 PDF 文件。

在產生 PDF 時,該如何處理受保護的 Azure Blob 存取認證?

請在您的 C# 專案中設定 Azure Storage 帳戶,並完成適當的驗證與連線設定。若遇到複雜的驗證情境,您可以探索 IronPDF 的 HTTP 請求標頭功能,以便在渲染 PDF 時處理受保護的 Blob 存取。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 19,936,792 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想快速獲得證明嗎? PM > Install-Package IronPdf
執行範例 看您的HTML變成PDF。