푸터 콘텐츠로 바로가기
IRONPDF 사용

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

Create PDFs dynamically in ASP.NET Core by using IronPDF to convert HTML content into professional PDF documents instantly, streaming them directly to users without server-side storage.

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 immediate PDF file generation without server-side storage. IronPDF's effective PDF library makes it simple to create PDFs directly in your .NET Core projects.

In this article, we'll guide you through the steps to create PDF documents in your ASP.NET applications, using HTML to PDF conversion capabilities and memory stream operations.

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. The Chrome rendering engine ensures pixel-perfect output that matches your HTML design exactly.

지금 바로 IronPDF으로 시작하세요.
green arrow pointer

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

First, install IronPDF through NuGet Package Manager to add this effective 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";
        }
    }
}
$vbLabelText   $csharpLabel

This setup initializes the ChromePdfRenderer, IronPDF's effective rendering engine that converts HTML to PDF documents using Chromium. By creating a single renderer instance, you improve memory usage when you create PDFs repeatedly. Learn more about HTML to PDF conversion for advanced techniques, including JavaScript rendering, CSS support, and custom fonts. For license key configuration, explore our licensing guide.

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 complete 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");
}
$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. For more advanced features, explore custom page sizes, headers and footers, and watermarks.

What Does the Generated Invoice PDF Look Like?

Professional PDF invoice showing Invoice #123 dated 2025-11-13 with a styled header section, organized table containing Product A ($10.99) and Product B ($5.49), demonstrating dynamic PDF generation capabilities with custom CSS styling

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");
    }
}
$vbLabelText   $csharpLabel

How Does Memory-Based PDF Generation Work?

Generated PDF report showing 'Monthly Performance Review' title with formatted content demonstrating real-world business document generation including charts, metrics, and detailed analysis sections rendered from HTML template

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 processes this code to generate the PDF dynamically. This technique is particularly useful for Azure Functions and AWS Lambda deployments where file system access may be restricted.

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");
}
$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. For improved formatting, consider using CSS print styles, custom margins, and page breaks. You might also want to add charts or images from Azure Blob Storage.

How Do You Handle Advanced PDF Generation Scenarios?

For more complex requirements, IronPDF offers advanced features to improve your on-the-fly PDF generation:

[HttpPost("generate/advanced")]
public async Task<IActionResult> GenerateAdvancedPdf([FromBody] AdvancedRequest request)
{
    // Configure rendering options
    _renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = PdfPaperSize.A4,
        MarginTop = 40,
        MarginBottom = 40,
        MarginLeft = 20,
        MarginRight = 20,
        EnableJavaScript = true,
        WaitFor = new WaitFor()
        {
            RenderDelay = 500 // Wait for JavaScript execution
        }
    };

    // Add headers and footers
    _renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
    {
        CenterText = request.DocumentTitle,
        DrawDividerLine = true,
        FontSize = 12
    };

    _renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
    {
        LeftText = "{date} {time}",
        RightText = "Page {page} of {total-pages}",
        FontSize = 10
    };

    // Generate PDF with custom settings
    var pdf = await _renderer.RenderHtmlAsPdfAsync(request.HtmlContent);

    // Add security if requested
    if (request.RequirePassword)
    {
        pdf.SecuritySettings.OwnerPassword = "admin_password";
        pdf.SecuritySettings.UserPassword = request.UserPassword;
        pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.NoPrint;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    }

    return File(pdf.BinaryData, "application/pdf", $"{request.FileName}.pdf");
}
[HttpPost("generate/advanced")]
public async Task<IActionResult> GenerateAdvancedPdf([FromBody] AdvancedRequest request)
{
    // Configure rendering options
    _renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = PdfPaperSize.A4,
        MarginTop = 40,
        MarginBottom = 40,
        MarginLeft = 20,
        MarginRight = 20,
        EnableJavaScript = true,
        WaitFor = new WaitFor()
        {
            RenderDelay = 500 // Wait for JavaScript execution
        }
    };

    // Add headers and footers
    _renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
    {
        CenterText = request.DocumentTitle,
        DrawDividerLine = true,
        FontSize = 12
    };

    _renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
    {
        LeftText = "{date} {time}",
        RightText = "Page {page} of {total-pages}",
        FontSize = 10
    };

    // Generate PDF with custom settings
    var pdf = await _renderer.RenderHtmlAsPdfAsync(request.HtmlContent);

    // Add security if requested
    if (request.RequirePassword)
    {
        pdf.SecuritySettings.OwnerPassword = "admin_password";
        pdf.SecuritySettings.UserPassword = request.UserPassword;
        pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.NoPrint;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    }

    return File(pdf.BinaryData, "application/pdf", $"{request.FileName}.pdf");
}
$vbLabelText   $csharpLabel

This example demonstrates rendering options, page numbering, security settings, and async operations. You can also implement digital signatures, PDF/A compliance, compression, and watermarks. For multi-threaded scenarios, IronPDF provides thread-safe operations.

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;
$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");
}
$vbLabelText   $csharpLabel

Renderer Reuse: Share ChromePdfRenderer instances across requests to improve performance when you generate multiple PDFs. The renderer is thread-safe and handles concurrent operations efficiently. Reusing the renderer saves initialization time for each request. Consider implementing custom logging to monitor performance and troubleshoot issues.

According to Microsoft's ASP.NET Core best practices, minimizing object allocations and reusing resources are key to high-performance web applications. For deployment, explore our guides for Azure, AWS, Docker, and Linux environments. You can also implement caching strategies to improve render times.

NuGet NuGet을 사용하여 설치하세요

PM >  Install-Package IronPdf

빠른 설치를 원하시면 NuGet 에서 https://www.NuGet.org/packages/IronPdf를 검색해 보세요. 1천만 건 이상의 다운로드를 기록하며 C#을 이용한 PDF 개발 방식을 혁신하고 있습니다. DLL 파일 이나 윈도우 설치 프로그램을 다운로드할 수도 있습니다.

What Have You Learned About Creating PDFs on the Fly?

Creating PDF documents on the fly with IronPDF transforms complex document generation into straightforward code. From simple invoices to complex reports, IronPDF's effective 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.

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 reliable PDF generation. You can also reach out for support if needed. Explore additional features like PDF forms, annotations, bookmarks, metadata, and PDF/UA compliance for accessibility.

Ready to transform your ASP.NET Core application with dynamic PDF capabilities? Purchase a license to reveal all features and receive professional support from our engineering team. For VB.NET developers, F# developers, and those working with MAUI or Blazor, we offer complete platform support. Check our API reference for detailed documentation and explore competitor comparisons to see why developers choose IronPDF.

자주 묻는 질문

ASP.NET Core에서 PDF를 동적으로 생성하려면 어떻게 해야 하나요?

IronPDF를 사용하면 파일을 디스크에 저장하지 않고도 ASP.NET Core에서 동적으로 PDF를 생성할 수 있습니다. 이를 통해 PDF를 브라우저로 직접 스트리밍할 수 있습니다.

PDF 생성에 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 강력한 렌더링 엔진을 제공하여 .NET Core 프로젝트 내에서 직접 동적 PDF를 생성할 수 있으므로 서버 측 저장소 없이도 즉시 PDF를 생성할 수 있습니다.

IronPDF를 사용하여 송장 및 보고서를 만들 수 있나요?

예, IronPDF는 송장, 보고서 및 인증서와 같은 다양한 유형의 문서를 생성하는 데 적합하며, 모두 ASP.NET Core 애플리케이션에서 즉석에서 생성됩니다.

IronPDF를 사용할 때 서버 측 저장소가 필요한가요?

아니요, IronPDF를 사용하면 서버 측 저장소 없이도 PDF를 생성하고 브라우저로 직접 스트리밍할 수 있으므로 효율적이고 빠릅니다.

즉석 PDF 생성으로 어떤 종류의 애플리케이션이 혜택을 받을 수 있나요?

최신 웹 애플리케이션, 특히 인보이스 시스템 및 보고 도구와 같이 실시간 문서 생성이 필요한 애플리케이션은 IronPDF에서 제공하는 즉석 PDF 생성 기능을 통해 큰 이점을 얻을 수 있습니다.

IronPDF는 .NET Core 프로젝트를 지원하나요?

예, IronPDF는 .NET Core 프로젝트와 완벽하게 호환되므로 개발자는 PDF 생성 기능을 애플리케이션에 원활하게 통합할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.