MemoryStream を PDF C

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

IronPDFは、MemoryStream オブジェクトをC#でファイルシステムにアクセスせずにPDFドキュメントに直接変換できるようにします。 メモリ内で即座にPDFを作成および操作するために、PdfDocument コンストラクタに渡してください。

C# .NETでファイルシステムに触れずにMemoryStream を読み込み、PDFファイルとして作成します。 これはMemoryStream オブジェクトでSystem.IO 名前空間内で動作します。 この機能は、クラウド環境、Webアプリケーション、またはファイルシステムへのアクセスが制限されているシナリオに使用します。

クイックスタート: C# で MemoryStream から PDF を作成する

IronPDFを使用して、1行のコードでMemoryStream をPDFに変換します。 物理ファイルを扱わずにC#アプリケーションにPDF作成を統合するためにPdfDocumentMemoryStream から初期化します。 インメモリデータ処理、ネットワーク通信、リアルタイムデータ変換に最適です。

  1. IronPDF をNuGetパッケージマネージャでインストール

    PM > Install-Package IronPdf
  2. このコード スニペットをコピーして実行します。

    var bytes = File.ReadAllBytes("sample.pdf");
    var pdfDoc = new IronPdf.PdfDocument(myMemoryStream);
  3. 実際の環境でテストするためにデプロイする

    今日プロジェクトで IronPDF を使い始めましょう無料トライアル

    arrow pointer

メモリから PDF を読み込むには?

これら for .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.Webアプリケーション:サーバーの一時ファイルを作成することなく、ASP.NETアプリケーションでPDFを動的に提供します。

2.クラウド環境Azure Functions または 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 にエクスポートします。 WebアプリケーションでPDFを提供するときや、データベースに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

高度なメモリストリームの操作

複数の MemoryStreams から PDF をマージする

ファイルシステムにアクセスすることなく、複数のIronPDFドキュメントをメモリ内でマージします:

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

メモリーストリームPDF操作のベストプラクティス

  1. 適切に破棄する: メモリリークを防ぐためにDispose 文を使用するか、MemoryStream およびPdfDocument オブジェクトを明示的に破棄してください。

2.メモリ制限を考慮する:大きなPDFや大量処理のメモリ使用量を監視してください。 圧縮の実装や、PDFを塊で処理することを検討してください。

  1. エラー処理: 特に壊れているか不正な形式のPDFデータを扱う際は、ストリーム操作中に例外を処理するためにtry-catch ブロックを実装してください。

4.非同期操作:WebアプリケーションでPDFを処理するときは、asyncメソッドを使用して応答性を維持します。

IronPDFの他の機能との統合

MemoryStreamsは、数多くのPDF操作の可能性を可能にします:

次に何ができるのかを見てみましょうか? こちらのチュートリアルページをご覧ください: PDFの編集

よくある質問

ファイルシステムにアクセスせずにC#でMemoryStreamをPDFに変換するには?

IronPDFはファイルシステムにアクセスすることなく、MemoryStreamオブジェクトをPDFドキュメントに直接変換することができます。PdfDocumentコンストラクタにMemoryStreamを渡すだけです: var pdfDoc = new IronPdf.PdfDocument(myMemoryStream).var pdfDoc = new IronPdf.PdfDocument(myMemoryStream) この方法はクラウド環境、ウェブアプリケーション、ファイルシステムへのアクセスが制限されているシナリオに最適です。

メモリ内でPDFを作成するために、どのような種類のストリームオブジェクトを使用できますか?

IronPDFのPdfDocumentコンストラクタは3種類のインメモリオブジェクトを受け入れます:MemoryStream、FileStream、そしてバイト配列(byte[])です。PdfDocumentはこれらのどのソースからでも初期化することができ、ネットワーク通信やデータベースのブロブ、APIのレスポンスなどさまざまなデータソースに柔軟に対応することができます。

ファイルパスの代わりにバイト配列からPDFを読み込むことはできますか?

はい、IronPDFはバイト配列から直接PDFをロードすることができます。バイナリデータからPdfDocumentオブジェクトを作成するには次のようにします: var pdfDoc = new IronPdf.PdfDocument(pdfBytes).これは特に、ネットワーク通信経由でPDFデータを受信したり、データベースから取得したりする場合に便利です。

HTTP レスポンスストリームから PDF を作成するには?

IronPDFでは、まずレスポンスをバイト配列に変換することでHTTPレスポンスからPDFを作成することができます: byte[] pdfData = await client.GetByteArrayAsync(url); 次にPdfDocumentを初期化します: var pdfFromHttp = new IronPdf.PdfDocument(pdfData).これにより、ウェブAPIやリモートソースからのシームレスなPDF処理が可能になります。

PDF操作にMemoryStreamを使用する利点は何ですか?

MemoryStreamをIronPDFと一緒に使うことで、ファイルシステムに依存しない、より高速なインメモリー処理、より優れたセキュリティ(テンポラリファイルがない)、ファイルシステムへのアクセスが制限されているクラウド環境やコンテナ化されたアプリケーションに最適、といった利点があります。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたり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サミットを含む最大のMicrosoft開発者イベントのコンテンツを企画しています。
準備はできましたか?
Nuget ダウンロード 19,936,792 | バージョン: 2026.7 リリースされたばかり
Still Scrolling Icon

まだスクロールしていますか?

すぐに証拠が欲しいですか? PM > Install-Package IronPdf
サンプルを実行するHTML が PDF に変換されるのを確認します。