使用 C# 圖片轉PDF:Azure Blob 儲存影像渲染
若要在 C# 中使用 Azure Blob 儲存影像渲染 PDF,請將 blob 資料作為二進位資料檢索,將其轉換為 base64 字串,將其嵌入 HTML img 標籤中,然後使用 IronPDF 的 ChromePdfRenderer 將 HTML 轉換為 PDF。
Azure Blob 儲存體是由微軟 Azure 提供的雲端為基礎的儲存服務。 它儲存大量非結構化數據,例如文字或二進位數據,可透過 HTTP 或 HTTPS 存取。 在 C# 中處理 PDF 時, IronPDF提供了強大的功能來處理各種影像格式和來源,包括儲存在 Azure Blob Storage 等雲端服務中的影像格式和來源。
若要使用儲存在 Azure Blob 儲存體中的映像,必須處理二進位資料格式,而不是直接引用檔案。 解決方法是將映像轉換為 base64 字串,並將其嵌入到 img 標籤中。 這種方法與IronPDF 的 HTML 轉 PDF 轉換功能無縫配合,保持影像品質和格式。
快速入門:使用 Azure Blob 儲存影像渲染 PDF
-
使用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 儲存體帳戶,然後在 C# 專案中處理驗證和連線。 將 Azure.Storage.Blobs NuGet套件與IronPDF一起使用。 對於複雜的身份驗證場景,請探索IronPDF 的 HTTP 請求標頭功能,以實現安全的 blob 存取。
使用 DownloadToStreamAsync 方法將映像下載為串流。 將串流資料轉換為 Base64 編碼,並將其嵌入 HTML img 標籤中。 將 imageTag 變數合併到您的 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 儲存體支援多種影像格式, 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?
使用ChromePdfRenderer的 RenderHtmlAsPdf 方法將 imageTag 轉換為 PDF。 IronPDF 的 Chrome 渲染引擎在轉換過程中會保持影像品質和位置。 為獲得最佳效果,請配置渲染選項以控制 PDF 輸出品質。
以下是如何撥打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")
調整 "htmlContent" 變量,以包含您的實際 HTML 內容,並包含 imageTag。
完整工作範例
以下是一個將 Azure Blob 儲存體檢索與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 儲存體時,請確保已進行正確的驗證。 為了增強安全性,在存取受保護的資源時,請實作自訂 HTTP 標頭。 考慮對包含 Azure Blob 影像的敏感文件實施PDF 密碼保護。
常見問題排除
如果遇到 Blob 儲存整合問題,請參閱IronPDF 的 Azure 故障排除指南,以取得常見問題的解決方案。 對於影像相關的具體問題,影像渲染文件提供了處理各種情況的詳細指導。
常見問題解答
如何使用 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 存取。

