IRONSOFTWAREHOME

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

Curtis Chau
Curtis Chau
Updated: 2026年4月24日

要在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. 1Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. 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");
    C#
  3. 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
}

當處理多個圖片或不同格式時,利用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)}\"/>";
}

如何將HTML轉換為PDF?

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

以下是如何呼叫SaveAs()

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");

調整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"
        };
    }
}

性能考量

當處理大型圖像或多個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 存取。

How does base64 encoding aid in using images from Azure Blob Storage with IronPDF?

Base64 encoding allows binary data to be converted into a text format. Images from Azure Blob Storage are encoded into base64, embedded in HTML, and rendered by IronPDF into a PDF.

What methods does IronPDF offer for image insertion within PDFs?

IronPDF provides features to embed images by rendering HTML content containing base64-encoded image data, supporting dynamic and versatile PDF document creation.

How can I enhance performance when generating PDFs with large Azure Blob Storage images using IronPDF?

Implement async processes and caching strategies to handle large images more efficiently. IronPDF supports techniques to reduce redundant downloads and optimize rendering time.

Is it possible to secure documents with Azure Blob images using IronPDF?

Yes, IronPDF allows setting PDF password protection for documents that include sensitive images retrieved from Azure Blob Storage, enhancing security and compliance.

What steps should be followed if encountering issues with Azure Blob and IronPDF?

Consult IronPDF's troubleshooting guides for blob storage integration issues. Common solutions involve verifying connection strings, blob path accuracy, and proper authentication.

Curtis Chau
技術作家

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

...
閱讀更多

準備開始了嗎?

Nuget Downloads 20,878,335版本:2026.9剛剛發布

立即獲取免費

立即獲取 30天試用金鑰

bullet_checked無需信用卡或註冊帳號
bullet_test在生產
環境中進行測試,且不顯示浮水印
bullet_calendar30 天全
功能產品
bullet_support試用期間提供 24/5 技術
支援
立即獲取您的免費30天試用密鑰
不需要信用卡或建立賬戶
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.9

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999

有問題嗎?聯絡我們的開發團隊。

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立