C# Export to PDF [Code Example Tutorial]
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 programmatically.
How to Export PDF in C#
- Download and install Export to PDF C# Library
- Explore the PdfDocument documentation to discover methods for digitally signing exported PDFs
- Save PDF to memory using a System.IO.MemoryStream
- Serve a PDF to the web as binary data rather than HTML
- Export the PDF as file
Install with NuGet
Install-Package IronPdf
Options for Saving PDFs
How to Save PDF to Disk
Use the PdfDocument.SaveAs method to save your PDF to disk.
You will find that this method supports adding password protection. Check out the following articles to learn more about digitally signing exported PDFs: 'Digitally Sign a PDF Document.'
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
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 [].
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"}
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()