C# Export to PDF Code Example Tutorial
Use IronPDF to export HTML content to PDF in C# with simple methods like SaveAs(), Stream, and BinaryData. This C# PDF library enables developers to programmatically convert HTML to PDF documents and serve them to web browsers or save to disk.
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. Whether you're generating reports, creating invoices, or converting web pages, IronPDF provides a robust solution for PDF generation in C# applications.
Quickstart: Export HTML to PDF in C# with IronPDF
Export your HTML content to PDF in C# using IronPDF. This guide shows you how to convert HTML to a PDF document and save it with just a few lines of code. IronPDF simplifies PDF generation, allowing developers to integrate PDF export functionality into their applications.
Get started making PDFs with NuGet now:
Install IronPDF with NuGet Package Manager
Copy and run this code snippet.
new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");Deploy to test on your live environment
Minimal Workflow (5 steps)
- Download and install the C# PDF Export Library from NuGet
- Explore the
PdfDocumentdocumentation for digital signing methods - 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
What Are the Different Options for Saving PDFs?
When working with PDF documents in C#, IronPDF provides multiple options for saving and exporting your generated PDFs. Each method serves different use cases, from simple file storage to serving PDFs in web applications. The following sections cover the available options for exporting and saving PDFs in C#.
How to Save PDF to Disk
Use the PdfDocument.SaveAs method to save your PDF to disk. This is the most straightforward approach for desktop applications or when you need to store PDFs permanently on the server.
// Complete example for saving PDF to disk
using IronPdf;
// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();
// Create HTML content with styling
string htmlContent = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
.content { line-height: 1.6; }
</style>
</head>
<body>
<h1>Invoice #12345</h1>
<div class='content'>
<p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
<p>Thank you for your business!</p>
</div>
</body>
</html>";
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");
// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");// Complete example for saving PDF to disk
using IronPdf;
// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();
// Create HTML content with styling
string htmlContent = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
.content { line-height: 1.6; }
</style>
</head>
<body>
<h1>Invoice #12345</h1>
<div class='content'>
<p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
<p>Thank you for your business!</p>
</div>
</body>
</html>";
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");
// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");This method supports adding password protection. Check out the following article to learn more about digitally signing exported PDFs: 'Digitally Sign a PDF Document.' For additional security options, explore our guide on PDF permissions and passwords.
How to Save a PDF File to MemoryStream in C# (System.IO.MemoryStream)
The IronPdf.PdfDocument.Stream property saves the PDF to memory using a System.IO.MemoryStream. This approach is ideal when you need to manipulate the PDF data in memory or pass it to other methods without creating temporary files. Learn more about working with PDF memory streams.
// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;
var renderer = new ChromePdfRenderer();
// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");
// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;
// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);
// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");
// Remember to dispose of the stream when done
stream.Dispose();// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;
var renderer = new ChromePdfRenderer();
// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");
// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;
// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);
// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");
// Remember to dispose of the stream when done
stream.Dispose();How to Save to Binary Data
The IronPdf.PdfDocument.BinaryData property exports the PDF document as binary data in memory. This is particularly useful for database storage or when integrating with APIs that require byte arrays.
This outputs the PDF as a ByteArray, which is expressed in C# as byte [].
// Example: Convert PDF to binary data
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
MarginTop = 20,
MarginBottom = 20,
MarginLeft = 10,
MarginRight = 10,
PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};
// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");
// Get binary data
byte[] binaryData = pdf.BinaryData;
// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);
// Example: Send via API
// apiClient.UploadDocument(binaryData);// Example: Convert PDF to binary data
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
MarginTop = 20,
MarginBottom = 20,
MarginLeft = 10,
MarginRight = 10,
PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};
// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");
// Get binary data
byte[] binaryData = pdf.BinaryData;
// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);
// Example: Send via API
// apiClient.UploadDocument(binaryData);For more advanced scenarios involving binary data manipulation, see our guide on converting PDFs to MemoryStream.
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. This is essential for web applications where users need to download or view PDFs directly in their browsers. IronPDF integrates with both MVC and traditional ASP.NET applications.
MVC PDF Export
In modern MVC applications, serving PDFs is straightforward using the FileStreamResult. This approach works well with ASP.NET Core MVC applications:
// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
// Generate your HTML content
string htmlContent = GenerateInvoiceHtml(invoiceId);
// Create PDF using IronPDF
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Get the PDF stream
MemoryStream stream = pdf.Stream;
// Reset stream position
stream.Position = 0;
// Return file to browser - will prompt download
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = $"invoice_{invoiceId}.pdf"
};
}
// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));
// Return PDF for browser viewing
return File(pdf.BinaryData, "application/pdf");
}// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
// Generate your HTML content
string htmlContent = GenerateInvoiceHtml(invoiceId);
// Create PDF using IronPDF
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Get the PDF stream
MemoryStream stream = pdf.Stream;
// Reset stream position
stream.Position = 0;
// Return file to browser - will prompt download
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = $"invoice_{invoiceId}.pdf"
};
}
// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));
// Return PDF for browser viewing
return File(pdf.BinaryData, "application/pdf");
}ASP.NET PDF Export
For traditional ASP.NET WebForms applications, you can serve PDFs directly through the Response object:
// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
// Create your PDF document
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
};
// Generate PDF from current page or custom HTML
PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());
// Retrieves the PDF binary data
byte[] Binary = MyPdfDocument.BinaryData;
// Clears the existing response content
Response.Clear();
// Sets the response content type to 'application/octet-stream', suitable for PDF files
Response.ContentType = "application/octet-stream";
// Add content disposition header for download
Response.AddHeader("Content-Disposition",
"attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
// Writes the binary data to the response output stream
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
// Flushes the response to send the data to the client
Response.Flush();
// End the response
Response.End();
}// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
// Create your PDF document
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
};
// Generate PDF from current page or custom HTML
PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());
// Retrieves the PDF binary data
byte[] Binary = MyPdfDocument.BinaryData;
// Clears the existing response content
Response.Clear();
// Sets the response content type to 'application/octet-stream', suitable for PDF files
Response.ContentType = "application/octet-stream";
// Add content disposition header for download
Response.AddHeader("Content-Disposition",
"attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
// Writes the binary data to the response output stream
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
// Flushes the response to send the data to the client
Response.Flush();
// End the response
Response.End();
}Advanced Export Scenarios
Batch PDF Export
When dealing with multiple PDFs, you can optimize the export process:
// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
{
var renderer = new ChromePdfRenderer();
for (int i = 0; i < htmlDocuments.Count; i++)
{
// Render each HTML document
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);
// Add to zip archive
var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
using (var entryStream = entry.Open())
{
pdf.Stream.CopyTo(entryStream);
}
}
}
}// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
{
var renderer = new ChromePdfRenderer();
for (int i = 0; i < htmlDocuments.Count; i++)
{
// Render each HTML document
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);
// Add to zip archive
var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
using (var entryStream = entry.Open())
{
pdf.Stream.CopyTo(entryStream);
}
}
}
}Conditional Export Based on User Permissions
// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Apply security based on user role
if (userRole == UserRole.Guest)
{
// Restrict printing and copying for guests
pdf.SecuritySettings.AllowUserPrinting = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
}
else if (userRole == UserRole.Standard)
{
// Allow printing but not editing
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.SecuritySettings.AllowUserEditing = false;
}
return pdf.BinaryData;
}// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Apply security based on user role
if (userRole == UserRole.Guest)
{
// Restrict printing and copying for guests
pdf.SecuritySettings.AllowUserPrinting = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
}
else if (userRole == UserRole.Standard)
{
// Allow printing but not editing
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.SecuritySettings.AllowUserEditing = false;
}
return pdf.BinaryData;
}Best Practices for PDF Export
When exporting PDFs in production applications, consider these best practices:
- Memory Management: For large PDFs or high-traffic applications, properly dispose of PDF objects and streams to prevent memory leaks. Consider using
asyncmethods for better performance. - Error Handling: Always implement proper error handling when exporting PDFs, especially in web applications where network issues may occur.
- Compression: For large PDFs, use PDF compression to reduce file size before serving to users.
- Metadata: Set appropriate PDF metadata including title, author, and creation date for better document management.
- Cross-Platform Compatibility: Ensure your export functionality works across different platforms. IronPDF supports
Windows,Linux, andmacOS.
Conclusion
IronPDF provides comprehensive options for exporting PDFs in C# applications, from simple file saves to complex web server scenarios. Using the appropriate export method for your use case enables you to efficiently generate and deliver PDF documents to your users while maintaining security and performance standards.
Frequently Asked Questions
How do I export HTML content to PDF in C#?
You can export HTML to PDF in C# using IronPDF's ChromePdfRenderer class. Simply create a renderer instance, use the RenderHtmlAsPdf() method to convert your HTML content, and then save it using the SaveAs() method. IronPDF makes it easy to convert HTML strings, files, or URLs directly to PDF documents.
What are the different methods to save a PDF using C#?
IronPDF provides multiple methods to save PDFs: SaveAs() for saving to disk, Stream for serving PDFs in web applications without creating temporary files, and BinaryData for getting the PDF as a byte array. Each method in IronPDF serves different use cases, from simple file storage to dynamic web delivery.
Can I save a PDF to memory instead of disk?
Yes, IronPDF allows you to save PDFs to memory using System.IO.MemoryStream. This is useful for web applications where you want to serve PDFs directly to users without creating temporary files on the server. You can use the Stream property or convert the PDF to binary data.
How do I add password protection when saving a PDF?
IronPDF enables password protection by setting the Password property on the PdfDocument object before saving. Simply assign a password string to pdf.Password and then use SaveAs() to create a protected PDF file that requires the password to open.
Can I serve a PDF directly to web browsers without saving to disk?
Yes, IronPDF allows you to serve PDFs directly to web browsers as binary data. You can use the BinaryData property to get the PDF as a byte array and serve it through your web application's response stream, eliminating the need for temporary file storage.
What's the simplest way to convert and save HTML as PDF in one line?
IronPDF provides a one-line solution: new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Your HTML").SaveAs("output.pdf"). This creates a renderer, converts HTML to PDF, and saves it to disk in a single statement.







