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.
How to Convert MemoryStream to PDF in C#
- Download the IronPDF C# library to convert MemoryStream to PDF
- Load an existing PDF as PdfDocument object
- Render a new PDF from a URL or an HTML string/file
- Convert the PDF to a Stream using the
Stream
method and BinaryData property - Serve the MemoryStream to the Web, including MVC and ASP.NET
Save a PDF to Memory
An IronPdf.PdfDocument can be saved directly to memory in one of 2 ways:
- IronPdf.PdfDocument.Stream exports the PDF as a System.IO.MemoryStream
- IronPdf.PdfDocument.BinaryData exports the PDF as a Byte Array (byte [])
: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
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"}
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()