PDF to MemoryStream C#

Chaknith Bin
Chaknith Bin
January 25, 2023
Updated January 12, 2025
Share:

We can export PDF to MemoryStream in C# .NET without even touching the file system. This is possible through the MemoryStream object present inside the System.IO .NET namespace.

Get started with IronPDF

Start using IronPDF in your project today with a free trial.

First Step:
green arrow pointer



Save a PDF to Memory

An IronPdf.PdfDocument can be saved directly to memory in one of 2 ways:

: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
$vbLabelText   $csharpLabel

Serve a PDF to Web from Memory

To serve or export a PDF on the web, you need to send the PDF file as binary data instead of HTML. You can find out more in this guide on exporting and saving PDF documents in C#.

Here is a quick example for MVC and ASP.NET:

Export a PDF with MVC

The stream in the code snippet below is the binary data retrieved from IronPDF. The MIME type of the response is 'application/pdf', specifying the filename as 'download.pdf'.

return new FileStreamResult(pdfAsStream, "application/pdf")
{
    FileDownloadName = "download.pdf"
};
return new FileStreamResult(pdfAsStream, "application/pdf")
{
    FileDownloadName = "download.pdf"
};
Return New FileStreamResult(pdfAsStream, "application/pdf") With {.FileDownloadName = "download.pdf"}
$vbLabelText   $csharpLabel

Export a PDF with ASP.NET

Similar to the example above, the stream is the binary data retrieved from IronPDF. The Response is then configured and flushed to ensure that it is sent to the client.

Response.Clear();

Response.ContentType = "application/octet-stream";

Context.Response.OutputStream.Write(pdfAsStream, 0, stream.Length);

Response.Flush();
Response.Clear();

Response.ContentType = "application/octet-stream";

Context.Response.OutputStream.Write(pdfAsStream, 0, stream.Length);

Response.Flush();
Response.Clear()

Response.ContentType = "application/octet-stream"

Context.Response.OutputStream.Write(pdfAsStream, 0, stream.Length)

Response.Flush()
$vbLabelText   $csharpLabel
Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.