PDF to MemoryStream C#

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
VB   C#

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"}
VB   C#

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()
VB   C#