使用 C# 透過 Azure Blob Storage 影像渲染 PDF
若要在 C# 中使用 Azure Blob Storage 中的圖片渲染 PDF,請將 Blob 資料以二進位格式擷取,轉換為 base64 字串,嵌入 HTML 的 img 標籤中,並使用 IronPDF 的 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
-
using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronPdf
PM > Install-Package IronPdf -
請複製並執行此程式碼片段。
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"); -
部署至您的生產環境進行測試
立即透過免費試用,在您的專案中開始使用 IronPDF
簡化工作流程(5 個步驟)
- 下載 IronPDF 以渲染儲存於 Azure Blob 中的影像
- 處理檢索 blob 的流程
- 使用
ToBase64String方法將位元組轉換為 Base64 - 請在
img標籤中包含 base64 資訊 - 將 HTML 轉換為 PDF
如何將 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
當處理多張圖片或不同格式時,請善用 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
如何將 HTML 轉換為 PDF?
使用 RenderHtmlAsPdf() 的 ChromePdfRenderer 方法,將 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")
請將 pdfOptions 變數調整為您的實際 HTML 內容,並使用 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
效能考量
處理大型圖像或多個二進位大塊資料時,請採用非同步與多執行緒技術來提升效能。 請加入快取機制,以避免重複下載相同的二進位資料塊。
針對生產環境(尤其是 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 存取。

