Przejdź do treści stopki
KORZYSTANIE Z IRONPDF

Jak dynamicznie generować PDF-y w C#

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

Pierwsze kroki z 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

Można też skorzystać z interfejsu NuGet Package Manager, aby pobrać i zainstalować pakiet. Zainicjuj ChromePdfRenderer w celu generowania plików PDF o idealnej rozdzielczości:

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;
Imports IronPdf

' Create Chrome renderer instance
Dim renderer As New ChromePdfRenderer()

' Configure rendering options for PDF format
renderer.RenderingOptions.MarginTop = 50
renderer.RenderingOptions.MarginBottom = 50
renderer.RenderingOptions.PrintHtmlBackgrounds = True
$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. Ta konfiguracja pomaga tworzyć dokumenty PDF dokładnie na podstawie treści HTML. Learn more about rendering options to customize your PDF documents.

How to Dynamically Create PDF Documents using a Template

Twórz szablony HTML wielokrotnego użytku z symbolami zastępczymi do dynamicznego wstawiania danych:

// 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");
' Define HTML string template with placeholders
Dim invoiceTemplate As String = "
<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
Dim invoiceData = New With {
    .InvoiceNumber = "INV-2025-001",
    .Date = DateTime.Now.ToString("yyyy-MM-dd"),
    .CustomerName = "John Doe",
    .Total = 1250.00D
}

Dim finalHtml As String = 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
Dim pdf = renderer.RenderHtmlAsPdf(finalHtml)
pdf.SaveAs("invoice.pdf")
$vbLabelText   $csharpLabel

To podejście oparte na szablonach oddziela prezentację od danych, umożliwiając projektantom modyfikowanie złożonych układów, podczas gdy programiści skupiają się na integracji danych. The Replace method substitutes template ID placeholders with runtime values, creating personalized PDF documents. W celu konwersji treści HTML zawierającej powtarzające się sekcje należy przed konwersją do formatu PDF dynamicznie zbudować kod HTML przy użyciu pętli. Explore more HTML to PDF examples for advanced templating.

Wynik

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);
}
Imports System.Threading.Tasks
Imports System.Collections.Generic

' Async batch generation for multiple PDF documents
Public Async Function GenerateMonthlyReportsAsync(customers As List(Of Customer)) As Task
    Dim renderer = New ChromePdfRenderer()
    Dim tasks = New List(Of Task)()

    For Each customer In customers
        tasks.Add(Task.Run(Async Function()
                               ' Create HTML content with dynamic data
                               Dim html As String = $"
                                   <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
                               Dim document = Await renderer.RenderHtmlAsPdfAsync(html)
                               Await document.SaveAs($"reports/{customer.Id}_report.pdf")
                           End Function))
    Next

    Await Task.WhenAll(tasks)
End Function
$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

Programowo przekształcaj strony internetowe z formularzami HTML w pliki PDF z możliwością wypełniania:

// 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");
' Enable form fields creation in rendering options
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Define HTML string with form elements
Dim formHtml As String = "
<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
Dim pdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdfDocument.SaveAs("survey_form.pdf")
$vbLabelText   $csharpLabel

Setting CreatePdfFormsFromHtml converts HTML form elements into interactive PDF form fields. Użytkownicy mogą wypełniać, zapisywać i przesyłać te dokumenty PDF drogą elektroniczną. 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.

Wynik

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. Uzyskaj dostęp do klucza API natychmiast po zakupie. View licensing options to find the right NuGet package for your project.

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

Wnioski

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.

Często Zadawane Pytania

Czym jest dynamiczne generowanie PDF w C#?

Dynamiczne generowanie PDF w C# odnosi się do procesu tworzenia dokumentów PDF w czasie wykonywania, często przy użyciu treści opartych na danych lub spersonalizowanych szablonów. IronPDF ułatwia to, oferując solidne narzędzia do płynnej integracji z C# i .NET Framework.

Dlaczego warto używać IronPDF do generowania PDF?

IronPDF jest wiodącym rozwiązaniem do dynamicznego generowania PDF dzięki potężnemu silnikowi renderującemu opartemu na Chrome, który zapewnia wysoką jakość wyjścia. Integruje się płynnie z C# i .NET Framework, co czyni go idealnym dla nowoczesnych aplikacji webowych.

Jak IronPDF wspiera deweloperów C#?

IronPDF wspiera deweloperów C# oferując wszechstronny zestaw funkcji do dynamicznego generowania PDF, w tym możliwość tworzenia spersonalizowanych faktur, raportów opartych na danych i dostosowanych pól formularzy, wszystko w środowisku C#.

Jakie są zalety renderowania opartego na Chrome w IronPDF?

Renderowanie oparte na Chrome w IronPDF zapewnia wysokiej jakości dokumenty PDF, które zachowują integralność złożonych układów i stylów, gwarantując, że generowane PDF wyglądają spójnie w różnych środowiskach.

Czy IronPDF może generować PDF z zawartości HTML?

Tak, IronPDF może generować PDF z zawartości HTML, umożliwiając deweloperom konwertowanie stron webowych, ciągów HTML lub szablonów na dokumenty PDF najwyższej jakości.

Czy IronPDF jest kompatybilny z .NET Framework?

IronPDF jest w pełni kompatybilny z .NET Framework, co czyni go wszechstronnym narzędziem dla deweloperów pracujących w tym środowisku do dynamicznego generowania PDF.

Jakie rodzaje dokumentów można tworzyć za pomocą IronPDF?

Korzystając z IronPDF, deweloperzy mogą tworzyć szeroką gamę dokumentów, w tym spersonalizowane faktury, raporty oparte na danych i dostosowane pola formularzy, wszystko dynamicznie generowane z aplikacji C#.

Czy IronPDF obsługuje PDFy w wielu językach?

Tak, IronPDF obsługuje generowanie PDF-ów w wielu językach, umożliwiając deweloperom tworzenie dokumentów dostosowanych do różnorodnych wymagań językowych.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie