PDF to MemoryStream C
using IronPDF 的 MemoryStream 屬性或 Stream 屬性,在 C# .NET 中將 PDF 轉換為 BinaryData,讓網頁應用程式和資料處理能在不需存取檔案系統的情況下,直接在記憶體中進行 PDF 操作。
我們可以在 C# .NET 中將 PDF 匯出至 MemoryStream,無需觸及檔案系統。 這可透過 System.IO .NET 命名空間內的 MemoryStream 物件來實現。 此方法在開發雲端應用程式、使用 Azure Blob Storage,或為優化效能而需在記憶體中處理 PDF 檔案時,特別有用。
能夠在記憶體流中處理 PDF 檔案,對於現代網路應用程式至關重要,特別是在部署至 Azure 或其他雲端平台時(這些平台可能限制檔案系統存取權限),或是當您希望避免磁碟 I/O 操作所造成的額外負擔時。 IronPDF 透過其內建的流處理方法,讓這個過程變得簡單直觀。
快速入門:將 PDF 轉換為 MemoryStream
using IronPDF 的 API,將您的 PDF 檔案轉換為 MemoryStream。 本指南協助開發人員開始載入 PDF 並將其匯出為 MemoryStream,以便整合至 .NET 應用程式中。 請參照此範例,在 C# 中實作 PDF 處理功能。
簡化工作流程(5 個步驟)
- 下載 IronPDF C# 函式庫,將
MemoryStream為 PDF/A - 將現有 PDF 載入為 PdfDocument 物件
- 根據網址或 HTML 字串/檔案渲染新的 PDF 檔案
- 使用PDF/A格式将PDF转换为流
Stream方法及 BinaryData 屬性 - 為
MemoryStream至 Web,包括 MVC 和 ASP.NET
如何將 PDF 儲存至記憶體中?
IronPdf.PdfDocument 可透過以下兩種方式之一直接儲存至記憶體中:
IronPdf.PdfDocument.Stream將 PDF 匯出為System.IO.MemoryStreamIronPdf.PdfDocument.BinaryData將 PDF 匯出為位元組陣列 (byte[])
選擇使用 Stream 或 BinaryData,取決於您的具體使用情境。 MemoryStream 非常適合用於處理基於流的 API,或當您希望維持與其他 .NET 流操作的相容性時。 BinaryData 作為位元組陣列,非常適合需要將 PDF 資料儲存於資料庫、在記憶體中快取,或透過網路傳輸的場景。
:path=/static-assets/pdf/content-code-examples/how-to/pdf-to-memory-stream-to-stream.cs
using IronPdf;
using System.IO;
var renderer = new ChromePdfRenderer();
// Convert the URL into PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Export PDF as Stream
MemoryStream pdfAsStream = pdf.Stream;
// Export PDF as Byte Array
byte[] pdfAsByte = pdf.BinaryData;
Imports IronPdf
Imports System.IO
Private renderer = New ChromePdfRenderer()
' Convert the URL into PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")
' Export PDF as Stream
Private pdfAsStream As MemoryStream = pdf.Stream
' Export PDF as Byte Array
Private pdfAsByte() As Byte = pdf.BinaryData
處理現有 PDF 檔案
當您需要從記憶體載入 PDF 檔案時,IronPDF 提供了便捷的方法來處理已存在於記憶體中的 PDF 檔案:
using IronPdf;
using System.IO;
// Load PDF from byte array
byte[] pdfBytes = File.ReadAllBytes("existing.pdf");
PdfDocument pdfFromBytes = PdfDocument.FromFile(new MemoryStream(pdfBytes));
// Or directly from a MemoryStream
MemoryStream memoryStream = new MemoryStream(pdfBytes);
PdfDocument pdfFromStream = PdfDocument.FromFile(memoryStream);
// Modify the PDF (add watermark, headers, etc.)
// Then export back to memory
byte[] modifiedPdfBytes = pdfFromStream.BinaryData;
using IronPdf;
using System.IO;
// Load PDF from byte array
byte[] pdfBytes = File.ReadAllBytes("existing.pdf");
PdfDocument pdfFromBytes = PdfDocument.FromFile(new MemoryStream(pdfBytes));
// Or directly from a MemoryStream
MemoryStream memoryStream = new MemoryStream(pdfBytes);
PdfDocument pdfFromStream = PdfDocument.FromFile(memoryStream);
// Modify the PDF (add watermark, headers, etc.)
// Then export back to memory
byte[] modifiedPdfBytes = pdfFromStream.BinaryData;
Imports IronPdf
Imports System.IO
' Load PDF from byte array
Dim pdfBytes As Byte() = File.ReadAllBytes("existing.pdf")
Dim pdfFromBytes As PdfDocument = PdfDocument.FromFile(New MemoryStream(pdfBytes))
' Or directly from a MemoryStream
Dim memoryStream As New MemoryStream(pdfBytes)
Dim pdfFromStream As PdfDocument = PdfDocument.FromFile(memoryStream)
' Modify the PDF (add watermark, headers, etc.)
' Then export back to memory
Dim modifiedPdfBytes As Byte() = pdfFromStream.BinaryData
進階記憶體流操作
對於更複雜的場景,例如從 HTML 字串建立 PDF,或將多張圖片轉換為 PDF,您可以結合多項操作,同時將所有資料保留在記憶體中:
using IronPdf;
using System.IO;
using System.Co/llections.Generic;
// Create multiple PDFs in memory
var renderer = new ChromePdfRenderer();
List<MemoryStream> pdfStreams = new List<MemoryStream>();
// Generate multiple PDFs from HTML
string[] htmlTemplates = {
"<h1>Report 1</h1><p>Content...</p>",
"<h1>Report 2</h1><p>Content...</p>"
};
foreach (var html in htmlTemplates)
{
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdfStreams.Add(pdf.Stream);
}
// Merge all PDFs in memory
PdfDocument mergedPdf = PdfDocument.Merge(pdfStreams.Select(s =>
PdfDocument.FromFile(s)).ToList());
// Get the final merged PDF as a stream
MemoryStream finalStream = mergedPdf.Stream;
using IronPdf;
using System.IO;
using System.Co/llections.Generic;
// Create multiple PDFs in memory
var renderer = new ChromePdfRenderer();
List<MemoryStream> pdfStreams = new List<MemoryStream>();
// Generate multiple PDFs from HTML
string[] htmlTemplates = {
"<h1>Report 1</h1><p>Content...</p>",
"<h1>Report 2</h1><p>Content...</p>"
};
foreach (var html in htmlTemplates)
{
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdfStreams.Add(pdf.Stream);
}
// Merge all PDFs in memory
PdfDocument mergedPdf = PdfDocument.Merge(pdfStreams.Select(s =>
PdfDocument.FromFile(s)).ToList());
// Get the final merged PDF as a stream
MemoryStream finalStream = mergedPdf.Stream;
Imports IronPdf
Imports System.IO
Imports System.Collections.Generic
' Create multiple PDFs in memory
Dim renderer As New ChromePdfRenderer()
Dim pdfStreams As New List(Of MemoryStream)()
' Generate multiple PDFs from HTML
Dim htmlTemplates As String() = {
"<h1>Report 1</h1><p>Content...</p>",
"<h1>Report 2</h1><p>Content...</p>"
}
For Each html As String In htmlTemplates
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdfStreams.Add(pdf.Stream)
Next
' Merge all PDFs in memory
Dim mergedPdf As PdfDocument = PdfDocument.Merge(pdfStreams.Select(Function(s) PdfDocument.FromFile(s)).ToList())
' Get the final merged PDF as a stream
Dim finalStream As MemoryStream = mergedPdf.Stream
如何從記憶體中將 PDF 發佈到網路上?
若要在網頁上提供或匯出 PDF 檔案,您需要將 PDF 檔案作為二進位資料傳送,而非 HTML 格式。 您可以在這份關於如何在 C# 中匯出和儲存 PDF 文件的指南中找到更多資訊。 在處理網頁應用程式時,特別是在 ASP.NET MVC 環境中,透過記憶體串流提供 PDF 檔案具有多項優勢,包括更佳的效能以及減少伺服器磁碟使用量。
以下是 MVC 和 ASP.NET 的簡短範例:
如何使用 MVC 匯出 PDF?
以下程式碼片段中的資料流,是從 IronPDF 擷取的二進位資料。 回應的 MIME 類型為 'application/pdf',並指定檔案名為 'download.pdf'。 此方案能與現代 MVC 應用程式無縫整合,並可嵌入您現有的控制器中。
using System.Web.Mvc;
using System.IO;
public ActionResult ExportPdf()
{
// Assume pdfAsStream is a MemoryStream containing PDF data
MemoryStream pdfAsStream = new MemoryStream();
return new FileStreamResult(pdfAsStream, "application/pdf")
{
FileDownloadName = "download.pdf"
};
}
using System.Web.Mvc;
using System.IO;
public ActionResult ExportPdf()
{
// Assume pdfAsStream is a MemoryStream containing PDF data
MemoryStream pdfAsStream = new MemoryStream();
return new FileStreamResult(pdfAsStream, "application/pdf")
{
FileDownloadName = "download.pdf"
};
}
Imports System.Web.Mvc
Imports System.IO
Public Function ExportPdf() As ActionResult
' Assume pdfAsStream is a MemoryStream containing PDF data
Dim pdfAsStream As New MemoryStream()
Return New FileStreamResult(pdfAsStream, "application/pdf") With {.FileDownloadName = "download.pdf"}
End Function
針對更進階的應用情境,例如當您使用 Razor Pages 或需要實作自訂標頭時:
using System.Web.Mvc;
using IronPdf;
public ActionResult GenerateReport(string reportType)
{
var renderer = new ChromePdfRenderer();
// Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Generate PDF based on report type
string htmlContent = GetReportHtml(reportType);
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Add metadata
pdf.MetaData.Author = "Your Application";
pdf.MetaData.Title = $"{reportType} Report";
// Return as downloadable file
return File(pdf.Stream, "application/pdf",
$"{reportType}_Report_{DateTime.Now:yyyyMMdd}.pdf");
}
using System.Web.Mvc;
using IronPdf;
public ActionResult GenerateReport(string reportType)
{
var renderer = new ChromePdfRenderer();
// Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Generate PDF based on report type
string htmlContent = GetReportHtml(reportType);
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Add metadata
pdf.MetaData.Author = "Your Application";
pdf.MetaData.Title = $"{reportType} Report";
// Return as downloadable file
return File(pdf.Stream, "application/pdf",
$"{reportType}_Report_{DateTime.Now:yyyyMMdd}.pdf");
}
Imports System.Web.Mvc
Imports IronPdf
Public Function GenerateReport(reportType As String) As ActionResult
Dim renderer As New ChromePdfRenderer()
' Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 50
renderer.RenderingOptions.MarginBottom = 50
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait
' Generate PDF based on report type
Dim htmlContent As String = GetReportHtml(reportType)
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Add metadata
pdf.MetaData.Author = "Your Application"
pdf.MetaData.Title = $"{reportType} Report"
' Return as downloadable file
Return File(pdf.Stream, "application/pdf", $"{reportType}_Report_{DateTime.Now:yyyyMMdd}.pdf")
End Function
如何使用 ASP.NET 匯出 PDF 檔案?
與上述範例類似,此流是指從 IronPDF 擷取的二進位資料。 接著會配置該回應並進行刷新,以確保其能傳送至客戶端。 此方法對於 ASP.NET Web Forms 應用程式特別有用,或當您需要對 HTTP 回應進行更多控制時。
using System.IO;
using System.Web;
public class PdfHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Assume pdfAsStream is a MemoryStream containing PDF data
MemoryStream pdfAsStream = new MemoryStream();
context.Response.Clear();
context.Response.Co/ntentType = "application/octet-stream";
context.Response.OutputStream.Write(pdfAsStream.ToArray(), 0, (int)pdfAsStream.Length);
context.Response.Flush();
}
public bool IsReusable => false;
}
using System.IO;
using System.Web;
public class PdfHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Assume pdfAsStream is a MemoryStream containing PDF data
MemoryStream pdfAsStream = new MemoryStream();
context.Response.Clear();
context.Response.Co/ntentType = "application/octet-stream";
context.Response.OutputStream.Write(pdfAsStream.ToArray(), 0, (int)pdfAsStream.Length);
context.Response.Flush();
}
public bool IsReusable => false;
}
Imports System.IO
Imports System.Web
Public Class PdfHandler
Implements IHttpHandler
Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
' Assume pdfAsStream is a MemoryStream containing PDF data
Dim pdfAsStream As New MemoryStream()
context.Response.Clear()
context.Response.ContentType = "application/octet-stream"
context.Response.OutputStream.Write(pdfAsStream.ToArray(), 0, CInt(pdfAsStream.Length))
context.Response.Flush()
End Sub
Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
對於現代的 ASP.NET Core 應用程式,流程更加簡化:
using Microsoft.AspNetCore.Mvc;
using IronPdf;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
[HttpGet("generate")]
public async Task<IActionResult> GeneratePdf()
{
var renderer = new ChromePdfRenderer();
// Render HTML to PDF asynchronously for better performance
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Dynamic PDF</h1>");
// Return PDF as file stream
return File(pdf.Stream, "application/pdf", "generated.pdf");
}
[HttpPost("convert")]
public async Task<IActionResult> ConvertHtmlToPdf([FromBody] string htmlContent)
{
var renderer = new ChromePdfRenderer();
// Apply custom styling and rendering options
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync(htmlContent);
// Stream directly to response without saving to disk
return File(pdf.Stream, "application/pdf");
}
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
[HttpGet("generate")]
public async Task<IActionResult> GeneratePdf()
{
var renderer = new ChromePdfRenderer();
// Render HTML to PDF asynchronously for better performance
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Dynamic PDF</h1>");
// Return PDF as file stream
return File(pdf.Stream, "application/pdf", "generated.pdf");
}
[HttpPost("convert")]
public async Task<IActionResult> ConvertHtmlToPdf([FromBody] string htmlContent)
{
var renderer = new ChromePdfRenderer();
// Apply custom styling and rendering options
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync(htmlContent);
// Stream directly to response without saving to disk
return File(pdf.Stream, "application/pdf");
}
}
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf
Imports System.Threading.Tasks
<ApiController>
<Route("api/[controller]")>
Public Class PdfController
Inherits ControllerBase
<HttpGet("generate")>
Public Async Function GeneratePdf() As Task(Of IActionResult)
Dim renderer As New ChromePdfRenderer()
' Render HTML to PDF asynchronously for better performance
Dim pdf As PdfDocument = Await renderer.RenderHtmlAsPdfAsync("<h1>Dynamic PDF</h1>")
' Return PDF as file stream
Return File(pdf.Stream, "application/pdf", "generated.pdf")
End Function
<HttpPost("convert")>
Public Async Function ConvertHtmlToPdf(<FromBody> htmlContent As String) As Task(Of IActionResult)
Dim renderer As New ChromePdfRenderer()
' Apply custom styling and rendering options
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
renderer.RenderingOptions.PrintHtmlBackgrounds = True
Dim pdf As PdfDocument = Await renderer.RenderHtmlAsPdfAsync(htmlContent)
' Stream directly to response without saving to disk
Return File(pdf.Stream, "application/pdf")
End Function
End Class
記憶體流管理的最佳實踐
在網頁應用程式中處理 PDF 記憶體流時,請遵循以下最佳實務:
-
正確釋放資源:請務必使用
using語句,或明確釋放MemoryStream物件,以防止記憶體洩漏。 -
非同步操作:為提升可擴展性,特別是在處理非同步操作時,請盡可能使用非同步方法。
-
流大小考量:對於大型 PDF 檔案,建議採用串流式回應機制,以避免將整個 PDF 檔案一次載入記憶體中。
- 快取:對於經常存取的 PDF 檔案,請考慮將位元組陣列快取於記憶體中,或使用分散式快取來提升效能。
// Example of proper resource management with caching
public class PdfService
{
private readonly IMemoryCache _cache;
private readonly ChromePdfRenderer _renderer;
public PdfService(IMemoryCache cache)
{
_cache = cache;
_renderer = new ChromePdfRenderer();
}
public async Task<byte[]> GetCachedPdfAsync(string cacheKey, string htmlContent)
{
// Try to get from cache first
if (_cache.TryGetValue(cacheKey, out byte[] cachedPdf))
{
return cachedPdf;
}
// Generate PDF if not in cache
using (var pdf = await _renderer.RenderHtmlAsPdfAsync(htmlContent))
{
byte[] pdfBytes = pdf.BinaryData;
// Cache for 10 minutes
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromMinutes(10));
return pdfBytes;
}
}
}
// Example of proper resource management with caching
public class PdfService
{
private readonly IMemoryCache _cache;
private readonly ChromePdfRenderer _renderer;
public PdfService(IMemoryCache cache)
{
_cache = cache;
_renderer = new ChromePdfRenderer();
}
public async Task<byte[]> GetCachedPdfAsync(string cacheKey, string htmlContent)
{
// Try to get from cache first
if (_cache.TryGetValue(cacheKey, out byte[] cachedPdf))
{
return cachedPdf;
}
// Generate PDF if not in cache
using (var pdf = await _renderer.RenderHtmlAsPdfAsync(htmlContent))
{
byte[] pdfBytes = pdf.BinaryData;
// Cache for 10 minutes
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromMinutes(10));
return pdfBytes;
}
}
}
Imports System
Imports System.Threading.Tasks
' Example of proper resource management with caching
Public Class PdfService
Private ReadOnly _cache As IMemoryCache
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New(cache As IMemoryCache)
_cache = cache
_renderer = New ChromePdfRenderer()
End Sub
Public Async Function GetCachedPdfAsync(cacheKey As String, htmlContent As String) As Task(Of Byte())
' Try to get from cache first
Dim cachedPdf As Byte() = Nothing
If _cache.TryGetValue(cacheKey, cachedPdf) Then
Return cachedPdf
End If
' Generate PDF if not in cache
Using pdf = Await _renderer.RenderHtmlAsPdfAsync(htmlContent)
Dim pdfBytes As Byte() = pdf.BinaryData
' Cache for 10 minutes
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromMinutes(10))
Return pdfBytes
End Using
End Function
End Class
透過遵循這些模式並運用 IronPDF 的記憶體流功能,您可以建置高效且可擴展的網頁應用程式,在無需依賴檔案系統操作的情況下,即可處理 PDF 的產生與傳遞。 此方法在部署至 AWS 等雲端平台,或於容器化環境中作業時,尤為有益。
常見問題
如何在 C# 中將 PDF 轉換為 MemoryStream?
IronPDF 提供兩種將 PDF 轉換至記憶體的主要方式:使用 Stream 屬性匯出為 System.IO.MemoryStream,或使用 BinaryData 屬性匯出為位元組陣列。只需建立或載入 PdfDocument,並存取這些屬性,即可在不接觸檔案系統的情況下,於記憶體中處理 PDF 檔案。
在記憶體中處理 PDF 檔案而非檔案本身,有哪些好處?
Using IronPDF to process PDF files in memory offers several advantages: it improves performance by avoiding disk I/O operations, it is compatible with cloud platforms such as Azure, which may restrict file system access, it enhances security by not storing sensitive PDF files on disk, and it provides seamless integration with web applications and APIs.
我可以從記憶體流載入現有的 PDF 檔案嗎?
是的,IronPDF 允許您透過 PdfDocument.FromStream() 方法(適用於 MemoryStream 輸入)或 PdfDocument.FromBytes() 方法(適用於位元組陣列輸入)從記憶體載入 PDF 檔案。這使您能夠處理來自 Web 請求、資料庫或其他記憶體來源的 PDF 檔案,而無需將其儲存至磁碟。
如何在 ASP.NET 或 MVC 應用程式中從記憶體中提供 PDF 檔案?
IronPDF 讓您能輕鬆地在網頁應用程式中直接從記憶體提供 PDF 檔案。您可以使用 Stream 屬性或 BinaryData 屬性取得 PDF 內容,並在控制器動作中將其作為 FileResult 或 FileContentResult 傳回,非常適合在 ASP.NET Core 或 MVC 應用程式中即時產生並提供 PDF 檔案。
是否可以在記憶體中直接將 HTML 渲染為 PDF?
是的,IronPDF 的 ChromePdfRenderer 能夠將 HTML 內容直接渲染至 MemoryStream,無需建立臨時檔案。您可以使用 RenderHtmlAsPdf() 方法,並立即存取 Stream 屬性以取得 PDF 格式的 MemoryStream,這使其非常適合用於雲端應用程式及高效能情境。

