Skip to footer content
USING IRONPDF

ASP Create PDF on the Fly: Dynamic PDF Generation in .NET Core

When building modern web applications in ASP.NET Core, the ability to generate PDF documents dynamically is essential. Whether you're creating invoices, reports, or certificates, users expect instant PDF file generation without server-side storage. IronPDF's powerful PDF library makes it simple to create PDFs on the fly directly in your .NET Core projects.

In this article, we'll walk you through the steps required to start easily creating PDF documents on the fly in your ASP.NET applications.

What Does Creating PDFs on the Fly Mean?

Creating PDFs on the fly means generating PDF documents dynamically in memory and streaming them directly to the user's browser. This server-side process eliminates the need to save PDF files to disk, improving both performance and security. With IronPDF's SDK, you can transform HTML content into professional PDF documents instantly, perfect for web applications that need to create PDFs without storing files on the server.

Get stated with IronPDF now.
green arrow pointer

How Do You Set Up IronPDF for Dynamic PDF File Generation?

First, install IronPDF through NuGet Package Manager to add this powerful PDF library to your ASP.NET Core project:

Install-Package IronPdf

Next, configure IronPDF in your ASP.NET Core application to create PDF files dynamically:

using IronPdf;
using Microsoft.AspNetCore.Mvc;

namespace PdfGenerator.Controllers
{
    public class DocumentController : Controller
    {
        private readonly ChromePdfRenderer _renderer;

        public DocumentController()
        {
            // Initialize the renderer once for reuse
            _renderer = new ChromePdfRenderer();
            // Optional: Set your license key
            License.LicenseKey = "YOUR-LICENSE-KEY";
        }
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;

namespace PdfGenerator.Controllers
{
    public class DocumentController : Controller
    {
        private readonly ChromePdfRenderer _renderer;

        public DocumentController()
        {
            // Initialize the renderer once for reuse
            _renderer = new ChromePdfRenderer();
            // Optional: Set your license key
            License.LicenseKey = "YOUR-LICENSE-KEY";
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This setup initializes the ChromePdfRenderer, IronPDF's powerful rendering engine that converts HTML to PDF documents using Chromium. By creating a single renderer instance, you optimize memory usage when you create PDFs repeatedly. Learn more about HTML to PDF conversion for advanced techniques.

How Can You Create PDF Documents from HTML Content?

The core functionality to create PDF files involves converting HTML strings into PDF documents. Here's a comprehensive example showing how to generate an invoice on the fly:

[HttpGet]
public IActionResult GenerateInvoice(int orderId)
{
    // Fetch data from your database or service
    var orderData = GetOrderData(orderId);
    // Build HTML content with dynamic data
    string htmlContent = $@"
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; }}
                .header {{ background-color: #f0f0f0; padding: 20px; }}
                table {{ width: 100%; border-collapse: collapse; }}
                td, th {{ padding: 10px; border: 1px solid #ddd; }}
            </style>
        </head>
        <body>
            <div class='header'>
                <h1>Invoice #{orderData.InvoiceNumber}</h1>
                <p>Date: {DateTime.Now:yyyy-MM-dd}</p>
            </div>
            <table>
                <tr>
                    <th>Item</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>";
    foreach(var item in orderData.Items)
    {
        htmlContent += $@"
                <tr>
                    <td>{item.Name}</td>
                    <td>{item.Quantity}</td>
                    <td>${item.Price:F2}</td>
                </tr>";
    }
    htmlContent += @"
            </table>
        </body>
        </html>";
    // Create PDF from HTML
    var pdf = _renderer.RenderHtmlAsPdf(htmlContent);
    // Convert to byte array for streaming
    byte[] pdfBytes = pdf.BinaryData;
    // Return PDF to browser
    return File(pdfBytes, "application/pdf", $"invoice_{orderId}.pdf");
}
[HttpGet]
public IActionResult GenerateInvoice(int orderId)
{
    // Fetch data from your database or service
    var orderData = GetOrderData(orderId);
    // Build HTML content with dynamic data
    string htmlContent = $@"
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; }}
                .header {{ background-color: #f0f0f0; padding: 20px; }}
                table {{ width: 100%; border-collapse: collapse; }}
                td, th {{ padding: 10px; border: 1px solid #ddd; }}
            </style>
        </head>
        <body>
            <div class='header'>
                <h1>Invoice #{orderData.InvoiceNumber}</h1>
                <p>Date: {DateTime.Now:yyyy-MM-dd}</p>
            </div>
            <table>
                <tr>
                    <th>Item</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>";
    foreach(var item in orderData.Items)
    {
        htmlContent += $@"
                <tr>
                    <td>{item.Name}</td>
                    <td>{item.Quantity}</td>
                    <td>${item.Price:F2}</td>
                </tr>";
    }
    htmlContent += @"
            </table>
        </body>
        </html>";
    // Create PDF from HTML
    var pdf = _renderer.RenderHtmlAsPdf(htmlContent);
    // Convert to byte array for streaming
    byte[] pdfBytes = pdf.BinaryData;
    // Return PDF to browser
    return File(pdfBytes, "application/pdf", $"invoice_{orderId}.pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code demonstrates how to generate dynamic PDF files by combining HTML page templates with real-time data. The RenderHtmlAsPdf method processes the HTML content, including CSS styles, and produces a professional document ready for download. The method supports complex layouts, images, and even JavaScript execution. You can view the output in a new tab.

Example Output

ASP Create PDF on the Fly: Dynamic PDF Generation in .NET Core: Image 1 - Example PDF generated on the fly with our ASP.NET program

How Do You Stream PDF Files Directly to Users Without Saving to Disk?

Streaming PDFs on the fly requires working with memory streams and byte arrays. This approach ensures PDF documents never touch the server's file system, which is crucial for cloud deployments and containerized applications:

[HttpPost]
public async Task<IActionResult> CreateReport([FromBody] ReportRequest request)
{
    // Generate HTML from request data
    string html = BuildReportHtml(request);
    // Create PDF in memory
    var pdfDocument = _renderer.RenderHtmlAsPdf(html);
    // Use MemoryStream for efficient streaming
    using (var memoryStream = new MemoryStream())
    {
        // Write PDF binary data to the memory stream
        memoryStream.Write(pdfDocument.BinaryData, 0, pdfDocument.BinaryData.Length);
        // Set response headers for inline display
        Response.Headers.Add("Content-Disposition", "inline; filename=report.pdf");
        // Return FileContentResult with proper content type
        return new FileContentResult(memoryStream.ToArray(), "application/pdf");
    }
}
[HttpPost]
public async Task<IActionResult> CreateReport([FromBody] ReportRequest request)
{
    // Generate HTML from request data
    string html = BuildReportHtml(request);
    // Create PDF in memory
    var pdfDocument = _renderer.RenderHtmlAsPdf(html);
    // Use MemoryStream for efficient streaming
    using (var memoryStream = new MemoryStream())
    {
        // Write PDF binary data to the memory stream
        memoryStream.Write(pdfDocument.BinaryData, 0, pdfDocument.BinaryData.Length);
        // Set response headers for inline display
        Response.Headers.Add("Content-Disposition", "inline; filename=report.pdf");
        // Return FileContentResult with proper content type
        return new FileContentResult(memoryStream.ToArray(), "application/pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Example Output PDF Document

ASP Create PDF on the Fly: Dynamic PDF Generation in .NET Core: Image 2 - PDF created using Byte arrays and streams

The byte array approach allows you to create PDFs entirely in memory. The content type "application/pdf" tells the browser how to handle the file, while the Content-Disposition header determines whether the PDF file opens in the browser or triggers a download. For more details on PDF to MemoryStream conversion, check our documentation. When the user presses the button to send the request, the server will run this code to continue the process.

Start your free trial and implement dynamic PDF generation today!

How Can You Generate PDFs from Dynamic Database Content?

Real-world ASP.NET Core applications often need to create PDF reports from database queries. Here's how to generate PDFs using Entity Framework Core data with proper error handling:

[HttpGet("report/monthly")]
public async Task<IActionResult> MonthlyReport(int year, int month)
{
    // Query database for report data
    var reportData = await _context.Transactions
        .Where(t => t.Date.Year == year && t.Date.Month == month)
        .GroupBy(t => t.Category)
        .Select(g => new {
            Category = g.Key,
            Total = g.Sum(t => t.Amount),
            Count = g.Count()
        })
        .ToListAsync();
    // Build HTML template with style
    var htmlTemplate = @"<h2>Monthly Report</h2>
                         <table style='width:100%'>";
    foreach(var item in reportData)
    {
        htmlTemplate += $"<tr><td>{item.Category}</td>" +
                       $"<td>{item.Count} items</td>" +
                       $"<td>${item.Total:F2}</td></tr>";
    }
    htmlTemplate += "</table>";
    // Generate PDF document with settings
    var pdf = _renderer.RenderHtmlAsPdf(htmlTemplate);
    // Add metadata to PDF
    pdf.MetaData.Title = $"Report {month}/{year}";
    pdf.MetaData.Author = "Reporting System";
    // Stream PDF to user
    return File(pdf.BinaryData, "application/pdf");
}
[HttpGet("report/monthly")]
public async Task<IActionResult> MonthlyReport(int year, int month)
{
    // Query database for report data
    var reportData = await _context.Transactions
        .Where(t => t.Date.Year == year && t.Date.Month == month)
        .GroupBy(t => t.Category)
        .Select(g => new {
            Category = g.Key,
            Total = g.Sum(t => t.Amount),
            Count = g.Count()
        })
        .ToListAsync();
    // Build HTML template with style
    var htmlTemplate = @"<h2>Monthly Report</h2>
                         <table style='width:100%'>";
    foreach(var item in reportData)
    {
        htmlTemplate += $"<tr><td>{item.Category}</td>" +
                       $"<td>{item.Count} items</td>" +
                       $"<td>${item.Total:F2}</td></tr>";
    }
    htmlTemplate += "</table>";
    // Generate PDF document with settings
    var pdf = _renderer.RenderHtmlAsPdf(htmlTemplate);
    // Add metadata to PDF
    pdf.MetaData.Title = $"Report {month}/{year}";
    pdf.MetaData.Author = "Reporting System";
    // Stream PDF to user
    return File(pdf.BinaryData, "application/pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This pattern allows you to create PDFs from any data source, transforming database records into formatted documents instantly. The HTML template approach makes it easy to maintain and modify report layouts. You can also explore creating PDFs from existing documents for more complex scenarios, and find a link to a further index of information. We hope this provides a good example.

What Are Best Practices for On-the-Fly PDF Generation?

When you create PDF files dynamically in ASP.NET Core, consider these optimization strategies:

Async Operations: Use async methods to prevent blocking the server thread pool when you generate multiple PDFs:

var pdfTask = _renderer.RenderHtmlAsPdfAsync(htmlContent);
var pdf = await pdfTask;
var pdfTask = _renderer.RenderHtmlAsPdfAsync(htmlContent);
var pdf = await pdfTask;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Memory Management: For large PDF files, dispose of resources properly and consider streaming directly to the response to minimize memory usage:

using (var pdf = _renderer.RenderHtmlAsPdf(html))
{
    return File(pdf.Stream, "application/pdf");
}
using (var pdf = _renderer.RenderHtmlAsPdf(html))
{
    return File(pdf.Stream, "application/pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Renderer Reuse: Share ChromePdfRenderer instances across requests to improve performance when you generate multiple PDFs. The renderer is thread-safe and can handle concurrent operations efficiently. It is also true that reusing the renderer saves time. Don't miss this optimization.

According to Microsoft's ASP.NET Core best practices, minimizing object allocations and reusing resources are key to high-performance web applications.

NuGet Install with NuGet

PM >  Install-Package IronPdf

Check out IronPDF on NuGet for quick installation. With over 10 million downloads, it’s transforming PDF development with C#. You can also download the DLL or Windows installer.

Conclusion

Creating PDF documents on the fly with IronPDF transforms complex document generation into straightforward code. From simple invoices to complex reports, IronPDF's powerful SDK handles the heavy lifting while you focus on your application logic. The ability to generate and stream PDFs without saving to disk makes your ASP.NET Core applications more efficient and secure. We are constantly merging new features and you can draw inspiration from all our examples. This is an official DOC for the library.

With IronPDF, you can create PDFs from HTML content, stream them as byte arrays, and deliver professional documents to users instantly. Whether you're building a reporting system, invoice generator, or document management solution, IronPDF provides all the functionality you need to implement robust PDF generation. You can also compose a new message to get support. The text is clear.

Ready to transform your ASP.NET Core application with dynamic PDF capabilities? Purchase a license to unlock all features and receive professional support from our engineering team.

Frequently Asked Questions

How can I generate PDFs dynamically in ASP.NET Core?

You can use IronPDF to generate PDFs dynamically in ASP.NET Core without saving files to disk. It allows you to stream PDFs directly to browsers.

What are the benefits of using IronPDF for PDF generation?

IronPDF provides a powerful rendering engine that enables dynamic PDF creation directly within your .NET Core projects, ensuring instant PDF generation without the need for server-side storage.

Can IronPDF be used to create invoices and reports?

Yes, IronPDF is suitable for creating various types of documents such as invoices, reports, and certificates, all generated on-the-fly in ASP.NET Core applications.

Is server-side storage necessary when using IronPDF?

No, IronPDF allows you to generate and stream PDFs directly to browsers without the need for server-side storage, making it efficient and fast.

What kind of applications can benefit from on-the-fly PDF generation?

Modern web applications, particularly those requiring real-time document creation like invoicing systems and reporting tools, can greatly benefit from on-the-fly PDF generation provided by IronPDF.

Does IronPDF support .NET Core projects?

Yes, IronPDF is fully compatible with .NET Core projects, allowing developers to integrate PDF generation capabilities seamlessly into their applications.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More