MemoryStream to PDF C#

We can load, create, and export MemoryStream to PDF files in C# .NET without even touching the file system. This is possible through the MemoryStream object present inside the System.IO .NET namespace. Follow the tutorial below to find out how to export HTML to PDF in your C# project.

Get started with IronPDF

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

First Step:
green arrow pointer



Load a PDF from Memory

A new instance of IronPdf.PdfDocument can be initialized in any of these .NET in-memory-objects:

  • A MemoryStream
  • A FileStream
  • Binary Data as a Byte array (byte [])

Here is an example of reading a URL directly into a stream, then saving the PDF file to disk by using C#:

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

var renderer = new IronPdf.ChromePdfRenderer();

// Conversion of the URL into PDF
Uri url = new Uri("https://ironpdf.com/how-to/pdf-memory-stream/");

MemoryStream pdfAsStream = renderer.RenderUrlAsPdf(url).Stream; //Read stream
Imports System
Imports System.IO

Private renderer = New IronPdf.ChromePdfRenderer()

' Conversion of the URL into PDF
Private url As New Uri("https://ironpdf.com/how-to/pdf-memory-stream/")

Private pdfAsStream As MemoryStream = renderer.RenderUrlAsPdf(url).Stream 'Read stream
VB   C#

Save a PDF to Memory

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


Serve a PDF to Web from Memory

To serve or export a PDF to 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 'downloadedfile.pdf'.

return new FileStreamResult(pdfAsStream, "application/pdf")
{
    FileDownloadName = "downloadedfile.pdf"
};
return new FileStreamResult(pdfAsStream, "application/pdf")
{
    FileDownloadName = "downloadedfile.pdf"
};
Return New FileStreamResult(pdfAsStream, "application/pdf") With {.FileDownloadName = "downloadedfile.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#