MemoryStream 到 PDF C

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

IronPDF 啟用直接將 MemoryStream 物件轉換為 C# 中的 PDF 文件,無需存取檔案系統。 將您的 FileStream 或位元組陣列傳入 PdfDocument 建構函式,以在記憶體中立即建立和操作 PDF。

在 C# .NET 中載入和建立 MemoryStream 到 PDF 檔案,而不需接觸檔案系統。 這通過 MemoryStream 物件在 System.IO 命名空間中運作。 在雲環境、網頁應用程式或檔案系統存取受限的情況下使用這種功能。

快速開始:在 C# 中從 MemoryStream 建立 PDF

using IronPDF 透過一行程式碼將 MemoryStream 轉換為 PDF。 從 MemoryStream 初始化一個 PdfDocument,以便在不處理實體檔案的情況下將 PDF 建立整合到 C# 應用程式中。 理想用於記憶體中的資料處理、網路通訊或即時資料轉換。

  1. 使用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

  • 一個 MemoryStream
  • 一個 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 資料轉換為可編輯物件,以便按照需求進行修改。

這裡有一個顯示不同流來源的全範例:

:path=/static-assets/pdf/content-code-examples/how-to/pdf-memory-stream-3.cs
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 函式AWS Lambda 中使用,檔案系統存取受限或臨時儲存成本昂貴。

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

  4. 性能:對於小到中型的 PDF,記憶體操作比磁碟 I/O 更快,尤其是對於固態或網路附加儲存。
Icon Quote related to 什麼時候應該使用 MemoryStream 而不是基於檔案的操作?

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic related to 什麼時候應該使用 MemoryStream 而不是基於檔案的操作?

Milan Jovanovic

Microsoft MVP

查看案例研究
Icon Quote related to 什麼時候應該使用 MemoryStream 而不是基於檔案的操作?

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle related to 什麼時候應該使用 MemoryStream 而不是基於檔案的操作?

Brent Matzelle

首席技術官,OPYN

查看案例研究
Icon Quote related to 什麼時候應該使用 MemoryStream 而不是基於檔案的操作?

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones related to 什麼時候應該使用 MemoryStream 而不是基於檔案的操作?

David Jones

首席軟體工程師,Agorus Build

查看案例研究

如何將 PDF 匯出到 MemoryStream?

將已載入或已建立的 PDF 文件匯回到 MemoryStream using 進行處理或傳輸。 這在 在網頁應用程式中提供 PDF 或將其儲存在資料庫中時十分有用。

這裡是如何將 PDF 匯出到 MemoryStream:

:path=/static-assets/pdf/content-code-examples/how-to/pdf-memory-stream-4.cs
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 = pdf.Stream)
{
    // Example: Convert to byte array for database storage
    byte[] pdfBytes = pdf.BinaryData;
    
    // 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 MemoryStream = pdf.Stream
    ' Example: Convert to byte array for database storage
    Dim pdfBytes As Byte() = pdf.BinaryData
    
    ' 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 操作

從多個 MemoryStreams 合併 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,同時將所有內容保持在記憶體中:

:path=/static-assets/pdf/content-code-examples/how-to/pdf-memory-stream-6.cs
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 = IronPdf.Security.PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;

// Export secured PDF to memory
byte[] securedPdfBytes = pdf.BinaryData;
// 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 = IronPdf.Security.PdfPrintSecurity.NoPrint
pdf.SecuritySettings.AllowUserCopyPasteContent = False

' Export secured PDF to memory
Dim securedPdfBytes As Byte() = pdf.BinaryData
' Store or transmit secured PDF bytes
$vbLabelText   $csharpLabel

MemoryStream PDF 操作的最佳實踐

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

  2. 考慮記憶限制:監控大體積 PDF 或高負荷處理的記憶使用。 考慮實施壓縮 或分塊處理 PDF。

  3. 錯誤處理:實施 try-catch 區塊來處理與流相關的異常,特別是針對損壞或格式不正確的 PDF 資料。

  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,使其對於各種資料來源如網路通信、資料庫blob或API回應具有靈活性。

我可以從位元組陣列載入PDF而不是文件路徑嗎?

是的,IronPDF支持直接從位元組陣列載入PDF。您可以使用:var pdfDoc = new IronPdf.PdfDocument(pdfBytes)從二進制資料建立PdfDocument物件。這在接收來自網路通信的PDF資料或從資料庫檢索資料時特別有用。

如何從HTTP回應流建立PDF?

使用IronPDF,您可以通過首先將HTTP回應轉換為位元組陣列來建立PDF:byte[] pdfData = await client.GetByteArrayAsync(url); 然後初始化一個PdfDocument:var pdfFromHttp = new IronPdf.PdfDocument(pdfData)。這使得從網頁API或遠程來源的PDF處理無縫連接。

使用MemoryStream進行PDF操作有什麼好處?

與IronPDF一起使用MemoryStream提供多種優勢:無需文件系統依賴、更快的記憶體處理、更高的安全性(無臨時文件),並且非常適合用於雲環境或文件系統存取可能有限或受限的容器化應用。

Curtis Chau
技術作家

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

除了開發,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 下載 20,296,129 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想快速獲得證明嗎? PM > Install-Package IronPdf
執行範例 看您的HTML變成PDF。