MemoryStream 轉為 PDF C

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

IronPDF 允許在 C# 中直接將 MemoryStream 物件轉換為 PDF 文件,無需存取檔案系統。 將您的 FileStream 或位元組陣列傳遞給 PdfDocument 建構函式,即可在記憶體中即時建立及處理 PDF 檔案。

在不接觸檔案系統的情況下,使用 C# .NET 載入並將 MemoryStream 建立為 PDF 檔案。 此功能透過 MemoryStream 命名空間中的 System.IO 物件運作。 請將此功能應用於雲端環境、網頁應用程式,或檔案系統存取受限的情境中。

快速入門:在 C# 中從 MemoryStream 建立 PDF 檔案

使用 IronPDF 僅需一行程式碼,即可將 MemoryStream 轉換為 PDF。 從 MemoryStream 初始化 PdfDocument,以便將 PDF 建立功能整合至 C# 應用程式中,無需處理實體檔案。 非常適合用於記憶體內資料處理、網路通訊或即時資料轉換。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 請複製並執行此程式碼片段。

    var bytes = File.ReadAllBytes("sample.pdf");
    var pdfDoc = new IronPdf.PdfDocument(myMemoryStream);
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronPDF

    arrow pointer

如何從記憶體中載入 PDF?

從這些 .NET 內存物件初始化 IronPdf.PdfDocument

  • A MemoryStream
  • A FileStream
  • 二進位資料作為 byte[]

以下是一個直接從 PDF 檔案讀取資料流並建立 PdfDocument 物件的範例:

:path=/static-assets/pdf/content-code-examples/how-to/pdf-memory-stream-from-stream.cs
using IronPdf;
using System.IO;

// Read PDF file as stream
var fileByte = File.ReadAllBytes("sample.pdf");

// Instantiate PDF object from stream
PdfDocument pdf = new PdfDocument(fileByte);
Imports IronPdf
Imports System.IO

' Read PDF file as stream
Private fileByte = File.ReadAllBytes("sample.pdf")

' Instantiate PDF object from stream
Private pdf As New PdfDocument(fileByte)
$vbLabelText   $csharpLabel

我可以使用哪些類型的流物件?

此範例展示如何從檔案系統讀取 PDF 檔案,並建立 PdfDocument 物件。 您亦可透過網路通訊或其他資料交換協定,從接收到的 byte[] 來初始化 PdfDocument。 將 PDF 資料轉換為可編輯物件,以便視需要進行修改。

以下是一個展示不同資料流來源的完整範例:

using IronPdf;
using System.IO;
using System.Net.Http;

// Example 1: From FileStream
using (FileStream fileStream = File.OpenRead("document.pdf"))
{
    var pdfFromFileStream = new PdfDocument(fileStream);
}

// Example 2: From MemoryStream
byte[] pdfBytes = GetPdfBytesFromDatabase(); // Your method to get PDF bytes
using (MemoryStream memoryStream = new MemoryStream(pdfBytes))
{
    var pdfFromMemoryStream = new PdfDocument(memoryStream);
}

// Example 3: From HTTP Response
using (HttpClient client = new HttpClient())
{
    byte[] pdfData = await client.GetByteArrayAsync("https://example.com/document.pdf");
    var pdfFromHttp = new PdfDocument(pdfData);
}
using IronPdf;
using System.IO;
using System.Net.Http;

// Example 1: From FileStream
using (FileStream fileStream = File.OpenRead("document.pdf"))
{
    var pdfFromFileStream = new PdfDocument(fileStream);
}

// Example 2: From MemoryStream
byte[] pdfBytes = GetPdfBytesFromDatabase(); // Your method to get PDF bytes
using (MemoryStream memoryStream = new MemoryStream(pdfBytes))
{
    var pdfFromMemoryStream = new PdfDocument(memoryStream);
}

// Example 3: From HTTP Response
using (HttpClient client = new HttpClient())
{
    byte[] pdfData = await client.GetByteArrayAsync("https://example.com/document.pdf");
    var pdfFromHttp = new PdfDocument(pdfData);
}
Imports IronPdf
Imports System.IO
Imports System.Net.Http

' Example 1: From FileStream
Using fileStream As FileStream = File.OpenRead("document.pdf")
    Dim pdfFromFileStream = New PdfDocument(fileStream)
End Using

' Example 2: From MemoryStream
Dim pdfBytes As Byte() = GetPdfBytesFromDatabase() ' Your method to get PDF bytes
Using memoryStream As New MemoryStream(pdfBytes)
    Dim pdfFromMemoryStream = New PdfDocument(memoryStream)
End Using

' Example 3: From HTTP Response
Using client As New HttpClient()
    Dim pdfData As Byte() = Await client.GetByteArrayAsync("https://example.com/document.pdf")
    Dim pdfFromHttp = New PdfDocument(pdfData)
End Using
$vbLabelText   $csharpLabel

何時應使用 MemoryStream 取代基於檔案的操作?

MemoryStream 在以下情境中表現出色:

  1. 網頁應用程式:在 ASP.NET 應用程式中動態提供 PDF 檔案,無需建立臨時伺服器檔案。

  2. 雲端環境:適用於 Azure FunctionsAWS Lambda 等環境,此類環境中檔案系統存取受限,或臨時儲存成本高昂。

  3. 安全性:在記憶體中處理敏感文件,以避免在磁碟上留下暫存檔。

  4. 效能:對於中小型 PDF 檔案,記憶體操作的速度快於磁碟 I/O,特別是在使用固態儲存裝置或網路連接儲存裝置時。

如何將 PDF 匯出至 MemoryStream?

將載入或建立的 PDF 文件匯出回 MemoryStream using 進行處理或傳輸。 這在透過網頁應用程式提供 PDF 檔案或將其儲存於資料庫時非常實用。

以下是將 PDF 匯出至 MemoryStream 的方法:

using IronPdf;
using System.IO;

// Create or load a PDF document
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is a PDF from HTML</p>");

// Export to MemoryStream
using (MemoryStream memoryStream = new MemoryStream())
{
    pdf.SaveAs(memoryStream);

    // Example: Convert to byte array for database storage
    byte[] pdfBytes = memoryStream.ToArray();

    // Example: Reset position to read from beginning
    memoryStream.Position = 0;

    // Use the stream as needed (e.g., return in web response)
}
using IronPdf;
using System.IO;

// Create or load a PDF document
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is a PDF from HTML</p>");

// Export to MemoryStream
using (MemoryStream memoryStream = new MemoryStream())
{
    pdf.SaveAs(memoryStream);

    // Example: Convert to byte array for database storage
    byte[] pdfBytes = memoryStream.ToArray();

    // Example: Reset position to read from beginning
    memoryStream.Position = 0;

    // Use the stream as needed (e.g., return in web response)
}
Imports IronPdf
Imports System.IO

' Create or load a PDF document
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is a PDF from HTML</p>")

' Export to MemoryStream
Using memoryStream As New MemoryStream()
    pdf.SaveAs(memoryStream)

    ' Example: Convert to byte array for database storage
    Dim pdfBytes As Byte() = memoryStream.ToArray()

    ' Example: Reset position to read from beginning
    memoryStream.Position = 0

    ' Use the stream as needed (e.g., return in web response)
End Using
$vbLabelText   $csharpLabel

進階 MemoryStream 操作

從多個 MemoryStream 合併 PDF 檔案

無需存取檔案系統,即可在記憶體中合併多個 PDF 文件

using IronPdf;
using System.Collections.Generic;
using System.IO;

public static byte[] MergePdfsFromMemory(List<byte[]> pdfBytesList)
{
    List<PdfDocument> pdfs = new List<PdfDocument>();

    // Load all PDFs from byte arrays
    foreach (var pdfBytes in pdfBytesList)
    {
        pdfs.Add(new PdfDocument(pdfBytes));
    }

    // Merge PDFs
    PdfDocument merged = PdfDocument.Merge(pdfs);

    // Export merged PDF to byte array
    using (MemoryStream ms = new MemoryStream())
    {
        merged.SaveAs(ms);
        return ms.ToArray();
    }
}
using IronPdf;
using System.Collections.Generic;
using System.IO;

public static byte[] MergePdfsFromMemory(List<byte[]> pdfBytesList)
{
    List<PdfDocument> pdfs = new List<PdfDocument>();

    // Load all PDFs from byte arrays
    foreach (var pdfBytes in pdfBytesList)
    {
        pdfs.Add(new PdfDocument(pdfBytes));
    }

    // Merge PDFs
    PdfDocument merged = PdfDocument.Merge(pdfs);

    // Export merged PDF to byte array
    using (MemoryStream ms = new MemoryStream())
    {
        merged.SaveAs(ms);
        return ms.ToArray();
    }
}
Imports IronPdf
Imports System.Collections.Generic
Imports System.IO

Public Shared Function MergePdfsFromMemory(pdfBytesList As List(Of Byte())) As Byte()
    Dim pdfs As New List(Of PdfDocument)()

    ' Load all PDFs from byte arrays
    For Each pdfBytes In pdfBytesList
        pdfs.Add(New PdfDocument(pdfBytes))
    Next

    ' Merge PDFs
    Dim merged As PdfDocument = PdfDocument.Merge(pdfs)

    ' Export merged PDF to byte array
    Using ms As New MemoryStream()
        merged.SaveAs(ms)
        Return ms.ToArray()
    End Using
End Function
$vbLabelText   $csharpLabel

在記憶體中套用安全性設定

在將所有內容保留於記憶體中的同時,為 PDF 設定密碼與權限

using IronPdf;
using System.IO;

// Load PDF from memory
byte[] unsecuredPdfBytes = GetPdfFromDatabase();
PdfDocument pdf = new PdfDocument(unsecuredPdfBytes);

// Apply security settings
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
pdf.SecuritySettings.AllowUserPrinting = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;

// Export secured PDF to memory
using (MemoryStream securedStream = new MemoryStream())
{
    pdf.SaveAs(securedStream);
    byte[] securedPdfBytes = securedStream.ToArray();
    // Store or transmit secured PDF bytes
}
using IronPdf;
using System.IO;

// Load PDF from memory
byte[] unsecuredPdfBytes = GetPdfFromDatabase();
PdfDocument pdf = new PdfDocument(unsecuredPdfBytes);

// Apply security settings
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
pdf.SecuritySettings.AllowUserPrinting = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;

// Export secured PDF to memory
using (MemoryStream securedStream = new MemoryStream())
{
    pdf.SaveAs(securedStream);
    byte[] securedPdfBytes = securedStream.ToArray();
    // Store or transmit secured PDF bytes
}
Imports IronPdf
Imports System.IO

' Load PDF from memory
Dim unsecuredPdfBytes As Byte() = GetPdfFromDatabase()
Dim pdf As New PdfDocument(unsecuredPdfBytes)

' Apply security settings
pdf.SecuritySettings.UserPassword = "user123"
pdf.SecuritySettings.OwnerPassword = "owner456"
pdf.SecuritySettings.AllowUserPrinting = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False

' Export secured PDF to memory
Using securedStream As New MemoryStream()
    pdf.SaveAs(securedStream)
    Dim securedPdfBytes As Byte() = securedStream.ToArray()
    ' Store or transmit secured PDF bytes
End Using
$vbLabelText   $csharpLabel

MemoryStream PDF 操作的最佳實踐

  1. 正確釋放資源:請使用 Dispose 語句,或明確釋放 MemoryStreamPdfDocument 物件,以防止記憶體洩漏。

  2. 考量記憶體限制:處理大型 PDF 檔案或大量資料時,請監控記憶體使用狀況。 請考慮採用壓縮技術,或分段處理 PDF 檔案。

  3. 錯誤處理:在處理資料流時(特別是面對損壞或格式錯誤的 PDF 資料時),應實作 try-catch 區塊來處理例外狀況。

  4. 非同步操作:在網頁應用程式中處理 PDF 時,請使用非同步方法以維持系統的響應性。

與其他 IronPDF 功能的整合

MemoryStreams 提供了多種 PDF 處理的可能性:

準備好探索更多可能性了嗎? 請點此查看我們的教學頁面:編輯 PDF

常見問題

如何在不存取檔案系統的情況下,於 C# 中將 MemoryStream 轉換為 PDF?

IronPDF 允許直接將 MemoryStream 物件轉換為 PDF 文件,無需存取檔案系統。只需將您的 MemoryStream 傳遞給 PdfDocument 建構函式即可:var pdfDoc = new IronPdf.PdfDocument(myMemoryStream)。此方法非常適合雲端環境、網頁應用程式,或檔案系統存取受限的情境。

我可以使用哪些類型的流物件來在記憶體中建立 PDF 檔案?

IronPDF 的 PdfDocument 建構函式接受三種記憶體內物件:MemoryStream、FileStream 以及位元組陣列 (byte[])。您可以從上述任何來源初始化 PdfDocument,使其能靈活適用於各種資料來源,例如網路通訊、資料庫二進位大物件 (blobs) 或 API 回應。

我能否從位元組陣列載入 PDF,而非透過檔案路徑?

是的,IronPDF 支援直接從位元組陣列載入 PDF 檔案。您可以透過以下方式,使用二進位資料建立 PdfDocument 物件:var pdfDoc = new IronPdf.PdfDocument(pdfBytes)。此功能在透過網路通訊接收 PDF 資料,或從資料庫擷取 PDF 資料時特別實用。

如何從 HTTP 回應串流建立 PDF 檔案?

透過 IronPDF,您可以從 HTTP 回應建立 PDF 檔案,方法是先將回應轉換為位元組陣列:byte[] pdfData = await client.GetByteArrayAsync(url);接著初始化 PdfDocument:var pdfFromHttp = new IronPdf.PdfDocument(pdfData)。這使您能夠從 Web API 或遠端來源進行無縫的 PDF 處理。

使用 MemoryStream 進行 PDF 操作有哪些好處?

搭配 IronPDF 使用 MemoryStream 具有多項優勢:無需依賴檔案系統、更快的記憶體內處理、更高的安全性(無需建立暫存檔),且特別適合檔案系統存取可能受限或受管制的雲端環境或容器化應用程式。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

審閱者:
Jeff Fritz
Jeffrey T. Fritz
首席程式經理 - .NET 社群團隊
Jeff 同時也是 .NET 與 Visual Studio 團隊的首席程式經理。他是 .NET Conf 虛擬會議系列的執行製作人,並主持每週播出兩次的開發者直播節目《Fritz and Friends》,在節目中他會與觀眾一起探討技術話題並共同編寫程式碼。Jeff 負責撰寫工作坊內容、準備簡報,並為 Microsoft Build、Microsoft Ignite、.NET Conf 以及 Microsoft MVP Summit 等微軟最大規模的開發者活動規劃內容。
準備開始了嗎?
Nuget 下載 19,014,616 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronPdf
執行範例 觀看您的 HTML 轉為 PDF。