C# Export PDFs and Save to MemoryStream

IronPDF is a C# PDF Library that allows you to use C# to save your HTML as a PDF. It also allows C# / VB developers to edit PDF documents programatically.


Step 1

1. Install IronPDF to Your Project

To Install IronPDF into your .NET project use the NUGET package manager: https://www.nuget.org/packages/IronPdf

PM > Install-Package IronPdf

Alternatively, the IronPDF DLL can be downloaded and manually installed here.


How to Tutorial

2. Options for Saving PDFs

2.1 How to Save PDF to Disk

Use IronPDF.PdfDocument.SaveAs() to save your PDF to disk.

You will find that this method supports adding password protection. You may also wish to explore the PdfDocument documentation to discover methods for digitally signing exported PDFS.

2.2 How to Save a PDF File to MemorySteam in C# (System.IO.MemoryStream)

The IronPDF.PdfDocument.Stream property saves the PDF to memory using a System.IO.MemoryStream

2.3 How to Save to Binary Data

The IronPDF.PdfDocument.BinaryData property exports the PDF document as binary data in memory.

This outputs the PDF as a ByteArray, which is expressed in C# as byte[].

2.4 How to Serve from a Web Server to Browser

To serve a PDF to the web, we need to send it as binary data rather than HTML.

MVC PDF Export


/// send MyPdfDocument.Stream to this method
return new FileStreamResult(stream, "application/pdf")
{
    FileDownloadName = "file.pdf"
};

/// send MyPdfDocument.Stream to this method
return new FileStreamResult(stream, "application/pdf")
{
    FileDownloadName = "file.pdf"
};
''' send MyPdfDocument.Stream to this method
Return New FileStreamResult(stream, "application/pdf") With {.FileDownloadName = "file.pdf"}
VB   C#

ASP.NET PDF Export

byte[] Binary = MyPdfDocument.BinaryData;
Response.Clear();
Response.ContentType = "application/octet-stream";
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();      
byte[] Binary = MyPdfDocument.BinaryData;
Response.Clear();
Response.ContentType = "application/octet-stream";
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();      
Dim Binary() As Byte = MyPdfDocument.BinaryData
Response.Clear()
Response.ContentType = "application/octet-stream"
Context.Response.OutputStream.Write(Binary, 0, Binary.Length)
Response.Flush()
VB   C#