跳過到頁腳內容
使用IRONPDF

如何在 C# 中動態生成 PDF

Modern web applications demand more than static document creation. Whether generating personalized invoices, creating data-driven PDF reports, or producing customized form fields, developers need robust tools to generate PDF documents at runtime. IronPDF emerges as the leading solution, offering powerful Chrome-based rendering to create PDF documents with seamless C# integration for dynamic PDF generation in C# and .NET Framework environments.

How to Dynamically Generate PDFs in C#: Figure 1 - Cross Platform

What is Dynamic PDF Generation in C#?

Dynamic PDF generation in C# creates PDF documents at runtime using variable data from multiple data sources, including databases, APIs, or user inputs. Unlike static PDF files, runtime generation enables personalized content, conditional sections, and data-driven layouts, these are essential for invoices, PDF reports, certificates, and forms that adapt to changing requirements. This approach to programmatically create a PDF has become crucial for modern .NET Framework and .NET Core applications.

How to Dynamically Generate PDFs in C#: Figure 2 - Cross Platform

Getting Started with IronPDF

Begin by installing the IronPDF NuGet package through Package Manager Console in Visual Studio:

Install-Package IronPdf

How to Dynamically Generate PDFs in C#: Figure 3 - Installation

Or use the NuGet Package Manager interface to download and install. Initialize the ChromePdfRenderer for pixel-perfect PDF generation:

using IronPdf;
// Create Chrome renderer instance
var renderer = new ChromePdfRenderer();
// Configure rendering options for PDF format
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
using IronPdf;
// Create Chrome renderer instance
var renderer = new ChromePdfRenderer();
// Configure rendering options for PDF format
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The ChromePdfRenderer class provides the foundation to generate a PDF at runtime. Setting margins ensures space for headers and footers, while PrintHtmlBackgrounds preserves design elements. This configuration helps create PDF documents based on HTML content exactly. Learn more about rendering options to customize your PDF documents.

How to Dynamically Create PDF Documents using a Template

Create reusable HTML templates with placeholders for dynamic data injection:

// Define HTML string template with placeholders
string invoiceTemplate = @"
<html>
<body>
    <h1>Invoice #[[INVOICE_NUMBER]]</h1>
    <p>Date: [[DATE]]</p>
    <p>Customer: [[CUSTOMER_NAME]]</p>
    <table>
        <tr><th>Item</th><th>Price</th></tr>
        [[ITEMS]]
    </table>
    <p><strong>Total: $[[TOTAL]]</strong></p>
</body>
</html>";
// Replace placeholders with dynamic data
var invoiceData = new {
    InvoiceNumber = "INV-2025-001",
    Date = DateTime.Now.ToString("yyyy-MM-dd"),
    CustomerName = "John Doe",
    Total = 1250.00m
};
string finalHtml = invoiceTemplate
    .Replace("[[INVOICE_NUMBER]]", invoiceData.InvoiceNumber)
    .Replace("[[DATE]]", invoiceData.Date)
    .Replace("[[CUSTOMER_NAME]]", invoiceData.CustomerName)
    .Replace("[[TOTAL]]", invoiceData.Total.ToString());
// Generate PDF from populated HTML content
var pdf = renderer.RenderHtmlAsPdf(finalHtml);
pdf.SaveAs("invoice.pdf");
// Define HTML string template with placeholders
string invoiceTemplate = @"
<html>
<body>
    <h1>Invoice #[[INVOICE_NUMBER]]</h1>
    <p>Date: [[DATE]]</p>
    <p>Customer: [[CUSTOMER_NAME]]</p>
    <table>
        <tr><th>Item</th><th>Price</th></tr>
        [[ITEMS]]
    </table>
    <p><strong>Total: $[[TOTAL]]</strong></p>
</body>
</html>";
// Replace placeholders with dynamic data
var invoiceData = new {
    InvoiceNumber = "INV-2025-001",
    Date = DateTime.Now.ToString("yyyy-MM-dd"),
    CustomerName = "John Doe",
    Total = 1250.00m
};
string finalHtml = invoiceTemplate
    .Replace("[[INVOICE_NUMBER]]", invoiceData.InvoiceNumber)
    .Replace("[[DATE]]", invoiceData.Date)
    .Replace("[[CUSTOMER_NAME]]", invoiceData.CustomerName)
    .Replace("[[TOTAL]]", invoiceData.Total.ToString());
// Generate PDF from populated HTML content
var pdf = renderer.RenderHtmlAsPdf(finalHtml);
pdf.SaveAs("invoice.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This template approach separates presentation from data, enabling designers to modify complex layouts while developers focus on data integration. The Replace method substitutes template ID placeholders with runtime values, creating personalized PDF documents. For converting HTML content with repeating sections, build the HTML dynamically using loops before PDF conversion. Explore more HTML to PDF examples for advanced templating.

Output

How to Dynamically Generate PDFs in C#: Figure 4 - PDF Output

Advanced Data Binding with Async Processing

Scale your PDF generation with async methods for high-volume processing:

// Async batch generation for multiple PDF documents
public async Task GenerateMonthlyReportsAsync(List<Customer> customers)
{
    var renderer = new ChromePdfRenderer();
    var tasks = new List<Task>();
    foreach (var customer in customers)
    {
        tasks.Add(Task.Run(async () =>
        {
            // Create HTML content with dynamic data
            string html = $@"
                <h2>Monthly Report - {customer.Name}</h2>
                <p>Account Balance: ${customer.Balance:F2}</p>
                <p>Transactions: {customer.TransactionCount}</p>
                <div style='page-break-after: always;'></div>";
            // Convert HTML to PDF format
            var document = await renderer.RenderHtmlAsPdfAsync(html);
            await document.SaveAs($"reports/{customer.Id}_report.pdf");
        }));
    }
    await Task.WhenAll(tasks);
}
// Async batch generation for multiple PDF documents
public async Task GenerateMonthlyReportsAsync(List<Customer> customers)
{
    var renderer = new ChromePdfRenderer();
    var tasks = new List<Task>();
    foreach (var customer in customers)
    {
        tasks.Add(Task.Run(async () =>
        {
            // Create HTML content with dynamic data
            string html = $@"
                <h2>Monthly Report - {customer.Name}</h2>
                <p>Account Balance: ${customer.Balance:F2}</p>
                <p>Transactions: {customer.TransactionCount}</p>
                <div style='page-break-after: always;'></div>";
            // Convert HTML to PDF format
            var document = await renderer.RenderHtmlAsPdfAsync(html);
            await document.SaveAs($"reports/{customer.Id}_report.pdf");
        }));
    }
    await Task.WhenAll(tasks);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The async pattern enables concurrent PDF generation, dramatically improving throughput when you generate PDF documents in batch. Task.WhenAll ensures all PDF files are complete before proceeding. The above code uses CSS page-break properties to control pagination, ensuring each customer's report starts on a new page. Review the async PDF generation documentation for enterprise web applications.

Creating Interactive PDF Forms Dynamically

Transform web pages with HTML forms into fillable PDFs programmatically:

// Enable form fields creation in rendering options
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Define HTML string with form elements
string formHtml = @"
<form>
    <h2>Customer Survey</h2>
    <label>Name: 
    <label>Email: 
    <label>Satisfaction:
        <select name='satisfaction'>
            <option>Excellent</option>
            <option>Good</option>
            <option>Fair</option>
        </select>
    </label><br>
    <label>Comments: <textarea name='comments'></textarea></label>
</form>";
// Create a PDF with interactive form fields
var pdfDocument = renderer.RenderHtmlAsPdf(formHtml);
pdfDocument.SaveAs("survey_form.pdf");
// Enable form fields creation in rendering options
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Define HTML string with form elements
string formHtml = @"
<form>
    <h2>Customer Survey</h2>
    <label>Name: 
    <label>Email: 
    <label>Satisfaction:
        <select name='satisfaction'>
            <option>Excellent</option>
            <option>Good</option>
            <option>Fair</option>
        </select>
    </label><br>
    <label>Comments: <textarea name='comments'></textarea></label>
</form>";
// Create a PDF with interactive form fields
var pdfDocument = renderer.RenderHtmlAsPdf(formHtml);
pdfDocument.SaveAs("survey_form.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Setting CreatePdfFormsFromHtml converts HTML form elements into interactive PDF form fields. Users can fill, save, and submit these PDF documents electronically. This feature streamlines workflows by eliminating paper forms while maintaining familiar HTML development patterns. The PDFDocument object provides access to manipulate form fields programmatically. Learn about PDF forms manipulation for advanced implementations, including digital signatures.

Output

How to Dynamically Generate PDFs in C#: Figure 5 - Interactive PDF Form Output

Why Choose IronPDF Over Other Methods

IronPDF's Chrome rendering engine ensures pixel-perfect accuracy when you create PDFs, eliminating the compromises of older WebKit rendering engine solutions. Unlike open source library alternatives requiring external executables or headless browser setups, IronPDF integrates seamlessly with zero dependencies. The fluent API and high-level API design make it superior to built-in classes or complex Crystal Reports implementations.

How to Dynamically Generate PDFs in C#: Figure 6 - Features

Key advantages for dynamic PDF generation in C#

  • Full JavaScript execution, unlike other methods
  • Thread-safe operations for web applications
  • Comprehensive async support with the following example patterns
  • Page numbers and font size control through a simple API endpoint configuration
  • HTML to PDF conversion matches Chrome exactly

How to Dynamically Generate PDFs in C#: Figure 7 - Dynamic PDF Generation - IronPDF

Licensing starts at $799 for single-developer licenses, with team and enterprise options available. Each package has its own advantages, and the investment pays for itself through development time savings. Access your API key instantly upon purchase. View licensing options to find the right NuGet package for your project.

How to Dynamically Generate PDFs in C#: Figure 8 - Licensing

Conclusion

Dynamic PDF generation in C# transforms how applications deliver personalized documents at runtime. IronPDF provides essential tools to generate PDF files from HTML content, web pages, and data sources. Its Chrome-based rendering ensures your PDFs in C# match design specifications exactly, while async support enables enterprise-scale processing.

The following command starts your journey: Install-Package IronPdf. With IronPDF, you can convert HTML strings, create complex PDFs with images and tables, add page numbers, control font size, and generate PDF reports from any data source. Each new document benefits from pixel-perfect rendering, whether creating a simple var page or complex layouts with multiple var document instances.

Start with IronPDF's free 30-day trial bundle.

常見問題解答

什麼是 C# 中的動態 PDF 生成?

C# 中的動態 PDF 生成是指在運行時創建 PDF 文檔的過程,通常使用數據驅動內容或個性化模板。 IronPDF 透過提供強大的工具來促成這一點,實現與 C# 和 .NET Framework 的無縫集成。

為什麼使用 IronPDF 來生成 PDF?

IronPDF 是動態生成 PDF 的領先解決方案,因為其強大的基於 Chrome 的渲染引擎可以確保高品質輸出。 它完美地與 C# 和 .NET Framework 集成,使其成為現代網絡應用程序的理想選擇。

IronPDF 如何支援 C# 開發人員?

IronPDF 通過提供一套全面的動態 PDF 生成功能支援 C# 開發人員,包括在 C# 環境中創建個性化發票、數據驅動報告和自定義表單字段的能力。

IronPDF 中基於 Chrome 的渲染有哪些優勢?

IronPDF 中基於 Chrome 的渲染提供高保真 PDF 文檔,可以維護複雜佈局和樣式的完整性,確保生成的 PDF 在不同環境中看起來一致。

IronPDF 可以從 HTML 內容生成 PDF 嗎?

是的,IronPDF 能夠從 HTML 內容生成 PDF,允許開發人員將網頁、HTML 字串或模板轉換為專業品質的 PDF 文檔。

IronPDF 是否與 .NET Framework 兼容?

IronPDF 與 .NET Framework 完全兼容,使其成為在此環境中工作的開發人員動態生成 PDF 的多功能工具。

可使用 IronPDF 創建哪類型文檔?

使用 IronPDF,開發人員可以創建各種文檔,包括動態生成的個性化發票、數據驅動報告和自定義表單字段,全部來源於 C# 應用程序。

IronPDF 是否支持多語言 PDF?

是的,IronPDF 支持多語言 PDF 的生成,讓開發人員能夠創建滿足多種語言要求的文檔。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。