DEV Community

IronSoftware
IronSoftware

Posted on

Using IronPDF with AI APIs to Create PDFs in C#

AI can generate content. IronPDF can convert that content to professional PDFs. Together, they unlock powerful automation: AI-generated reports, personalized documents, data-driven invoices, and dynamic marketing materials—all created programmatically.

Here's how to combine AI APIs (OpenAI, Claude, Gemini) with IronPDF to generate PDFs in C#.

Why Combine AI with PDF Generation?

AI excels at content generation:

  • Writing personalized emails
  • Summarizing data
  • Generating reports from structured data
  • Creating product descriptions
  • Drafting legal documents

IronPDF excels at rendering that content as professional PDFs:

  • Pixel-perfect HTML-to-PDF conversion
  • Custom styling (CSS, fonts, branding)
  • Headers, footers, page numbers
  • Digital signatures, watermarks

Together, you get automated document generation:

Database → AI (generate content) → IronPDF (render PDF) → Storage/Email
Enter fullscreen mode Exit fullscreen mode

Use Case: AI-Generated Monthly Reports

Let's build a system that:

  1. Fetches sales data from a database
  2. Uses OpenAI to generate narrative summaries
  3. Converts the summary to a branded PDF report
  4. Emails the report to stakeholders

Step 1: Install Required Packages

dotnet add package IronPdf
dotnet add package OpenAI
Enter fullscreen mode Exit fullscreen mode

Step 2: Generate Content with OpenAI

using OpenAI;
using OpenAI.Chat;
// Install via NuGet: Install-Package OpenAI

public async Task<string> GenerateReportSummary(SalesData data)
{
    var client = new OpenAIClient("your-api-key");

    var prompt = $@"
Generate a professional executive summary for this sales data:

- Total Revenue: {data.TotalRevenue:C}
- Units Sold: {data.UnitsSold}
- Top Product: {data.TopProduct}
- Growth vs. Last Month: {data.GrowthPercentage}%

Write 2-3 paragraphs suitable for a C-level executive report.
";

    var chatRequest = new ChatRequest
    {
        Model = "gpt-4",
        Messages = new[]
        {
            new ChatMessage { Role = "system", Content = "You are a financial analyst writing executive reports." },
            new ChatMessage { Role = "user", Content = prompt }
        }
    };

    var response = await client.ChatEndpoint.GetCompletionAsync(chatRequest);
    return response.FirstChoice.Message.Content;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Convert AI Content to PDF with IronPDF

using IronPdf;
// Install via NuGet: Install-Package IronPdf

public async Task<PdfDocument> CreateReportPdf(string aiGeneratedSummary, SalesData data)
{
    var html = $@"
<!DOCTYPE html>
<html>
<head>
    <style>
        body {{ font-family: 'Segoe UI', Arial, sans-serif; margin: 40px; }}
        .header {{ background: #2c3e50; color: white; padding: 20px; text-align: center; }}
        .summary {{ background: #ecf0f1; padding: 20px; margin: 20px 0; border-left: 4px solid #3498db; }}
        .metrics {{ display: flex; justify-content: space-between; margin: 30px 0; }}
        .metric {{ text-align: center; padding: 20px; background: #fff; border: 1px solid #ddd; flex: 1; margin: 0 10px; }}
        .metric-value {{ font-size: 32px; font-weight: bold; color: #2c3e50; }}
        .metric-label {{ color: #7f8c8d; }}
    </style>
</head>
<body>
    <div class='header'>
        <h1>Monthly Sales Report</h1>
        <p>{DateTime.Now:MMMM yyyy}</p>
    </div>

    <h2>Executive Summary</h2>
    <div class='summary'>
        {aiGeneratedSummary}
    </div>

    <h2>Key Metrics</h2>
    <div class='metrics'>
        <div class='metric'>
            <div class='metric-value'>{data.TotalRevenue:C0}</div>
            <div class='metric-label'>Total Revenue</div>
        </div>
        <div class='metric'>
            <div class='metric-value'>{data.UnitsSold:N0}</div>
            <div class='metric-label'>Units Sold</div>
        </div>
        <div class='metric'>
            <div class='metric-value'>{data.GrowthPercentage}%</div>
            <div class='metric-label'>Growth</div>
        </div>
    </div>
</body>
</html>";

    var renderer = new ChromePdfRenderer();
    renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;

    return renderer.RenderHtmlAsPdf(html);
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Complete Workflow

using IronPdf;
// Install via NuGet: Install-Package IronPdf

public async Task GenerateAndEmailReport()
{
    // 1. Fetch data from database
    var salesData = await _database.GetMonthlySalesData();

    // 2. Generate summary with AI
    var aiSummary = await GenerateReportSummary(salesData);

    // 3. Create PDF with IronPDF
    var pdf = await CreateReportPdf(aiSummary, salesData);
    pdf.SaveAs($"report-{DateTime.Now:yyyy-MM}.pdf");

    // 4. Email to stakeholders
    await _emailService.SendReport(pdf.BinaryData, "Monthly Sales Report");
}
Enter fullscreen mode Exit fullscreen mode

Output: Professional PDF with AI-generated narrative and structured data visualization.

Use Case: Personalized Marketing Materials

Generate personalized product brochures for each customer using AI and IronPDF.

using OpenAI;
using OpenAI.Chat;
using IronPdf;
// Install via NuGet: Install-Package IronPdf and OpenAI

public async Task<PdfDocument> GeneratePersonalizedBrochure(Customer customer, Product product)
{
    var client = new OpenAIClient("your-api-key");

    // AI generates personalized pitch
    var prompt = $@"
Write a personalized product pitch for:

Customer: {customer.Name}
Industry: {customer.Industry}
Product: {product.Name}
Key Features: {string.Join(", ", product.Features)}

Write 2-3 paragraphs explaining why this product is perfect for their industry.
";

    var chatRequest = new ChatRequest
    {
        Model = "gpt-4",
        Messages = new[]
        {
            new ChatMessage { Role = "system", Content = "You are a sales consultant writing personalized product pitches." },
            new ChatMessage { Role = "user", Content = prompt }
        }
    };

    var response = await client.ChatEndpoint.GetCompletionAsync(chatRequest);
    var personalizedPitch = response.FirstChoice.Message.Content;

    // Convert to branded PDF
    var html = $@"
<!DOCTYPE html>
<html>
<head>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 0; padding: 0; }}
        .header {{ background: #3498db; color: white; padding: 40px; text-align: center; }}
        .content {{ padding: 40px; }}
        .pitch {{ font-size: 16px; line-height: 1.6; margin: 20px 0; }}
        .cta {{ background: #e74c3c; color: white; padding: 15px 30px; text-decoration: none; display: inline-block; margin-top: 30px; }}
    </style>
</head>
<body>
    <div class='header'>
        <h1>{product.Name}</h1>
        <p>Personalized for {customer.Name}</p>
    </div>
    <div class='content'>
        <h2>Why {product.Name} is Perfect for {customer.Industry}</h2>
        <div class='pitch'>{personalizedPitch}</div>
        <a href='{product.LearnMoreUrl}' class='cta'>Schedule a Demo</a>
    </div>
</body>
</html>";

    var renderer = new ChromePdfRenderer();
    return renderer.RenderHtmlAsPdf(html);
}
Enter fullscreen mode Exit fullscreen mode

Result: Each customer receives a PDF brochure with AI-personalized content explaining why the product fits their specific industry.

Use Case: AI-Powered Invoice Generation

Generate invoices with AI-written descriptions and payment terms.

using OpenAI;
using OpenAI.Chat;
using IronPdf;
// Install via NuGet: Install-Package IronPdf and OpenAI

public async Task<PdfDocument> GenerateInvoice(Invoice invoice)
{
    var client = new OpenAIClient("your-api-key");

    // AI generates friendly invoice description
    var prompt = $@"
Write a friendly, professional invoice description for:

Services: {string.Join(", ", invoice.LineItems.Select(i => i.Description))}
Total: {invoice.Total:C}

Write 1-2 sentences thanking the customer and describing the services rendered.
";

    var chatRequest = new ChatRequest
    {
        Model = "gpt-4",
        Messages = new[]
        {
            new ChatMessage { Role = "system", Content = "You are writing friendly invoice descriptions." },
            new ChatMessage { Role = "user", Content = prompt }
        }
    };

    var response = await client.ChatEndpoint.GetCompletionAsync(chatRequest);
    var friendlyDescription = response.FirstChoice.Message.Content;

    var html = $@"
<!DOCTYPE html>
<html>
<head>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; }}
        .invoice-header {{ text-align: center; margin-bottom: 40px; }}
        .description {{ background: #f9f9f9; padding: 20px; margin: 20px 0; border-left: 4px solid #3498db; }}
        table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }}
        th, td {{ padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }}
        .total {{ font-size: 24px; font-weight: bold; text-align: right; }}
    </style>
</head>
<body>
    <div class='invoice-header'>
        <h1>Invoice #{invoice.Number}</h1>
        <p>Date: {invoice.Date:MMMM dd, yyyy}</p>
    </div>

    <div class='description'>
        {friendlyDescription}
    </div>

    <table>
        <thead>
            <tr>
                <th>Description</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            {string.Join("", invoice.LineItems.Select(item => $@"
            <tr>
                <td>{item.Description}</td>
                <td>{item.Quantity}</td>
                <td>{item.Price:C}</td>
                <td>{item.Total:C}</td>
            </tr>"))}
        </tbody>
    </table>

    <div class='total'>
        Total: {invoice.Total:C}
    </div>
</body>
</html>";

    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(html);

    // Add digital signature
    pdf.MetaData.Title = $"Invoice {invoice.Number}";
    pdf.MetaData.Author = "Your Company";

    return pdf;
}
Enter fullscreen mode Exit fullscreen mode

Use Case: Legal Document Generation with Claude

Use Claude's long context window to draft contracts from templates.

using Anthropic;
using IronPdf;
// Install via NuGet: Install-Package IronPdf and Anthropic SDK

public async Task<PdfDocument> GenerateContract(ContractData data)
{
    var anthropic = new AnthropicClient("your-api-key");

    var prompt = $@"
Generate a professional service agreement based on this template and data:

Template: [Insert your contract template here]

Data:
- Client: {data.ClientName}
- Services: {string.Join(", ", data.Services)}
- Duration: {data.Duration} months
- Payment Terms: {data.PaymentTerms}
- Start Date: {data.StartDate:MMMM dd, yyyy}

Fill in all placeholders and ensure legal language is appropriate.
";

    var message = await anthropic.Messages.CreateAsync(new()
    {
        Model = "claude-3-sonnet-20240229",
        MaxTokens = 4096,
        Messages = new[] { new Message { Role = "user", Content = prompt } }
    });

    var contractText = message.Content[0].Text;

    // Convert to PDF with legal formatting
    var html = $@"
<!DOCTYPE html>
<html>
<head>
    <style>
        body {{ font-family: 'Times New Roman', serif; margin: 60px; line-height: 1.8; }}
        h1 {{ text-align: center; margin-bottom: 40px; }}
        .clause {{ margin: 20px 0; }}
        .signature-line {{ margin-top: 60px; border-top: 1px solid #000; width: 300px; }}
    </style>
</head>
<body>
    <h1>SERVICE AGREEMENT</h1>
    {contractText}
    <div class='signature-line'>
        <p>Client Signature: _______________________</p>
        <p>Date: _______________________</p>
    </div>
</body>
</html>";

    var renderer = new ChromePdfRenderer();
    renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;

    var pdf = renderer.RenderHtmlAsPdf(html);

    // Add metadata for legal compliance
    pdf.MetaData.Title = $"Service Agreement - {data.ClientName}";
    pdf.MetaData.Author = "Your Legal Department";
    pdf.MetaData.CreationDate = DateTime.Now;

    return pdf;
}
Enter fullscreen mode Exit fullscreen mode

Best Practices: AI + IronPDF Integration

1. Sanitize AI Output Before Rendering

AI can generate malicious HTML/JavaScript. Always sanitize:

using System.Web;
using IronPdf;
// Install via NuGet: Install-Package IronPdf

public string SanitizeAIOutput(string aiGeneratedText)
{
    // Encode HTML to prevent script injection
    return HttpUtility.HtmlEncode(aiGeneratedText);
}

public PdfDocument SafeRender(string aiContent)
{
    var sanitized = SanitizeAIOutput(aiContent);

    var html = $@"
    <div>
        {sanitized}
    </div>";

    var renderer = new ChromePdfRenderer();
    renderer.RenderingOptions.EnableJavaScript = false; // Disable JS for security
    return renderer.RenderHtmlAsPdf(html);
}
Enter fullscreen mode Exit fullscreen mode

2. Cache AI Responses to Reduce API Costs

using Microsoft.Extensions.Caching.Memory;
using IronPdf;
// Install via NuGet: Install-Package IronPdf

public class CachedAIService
{
    private readonly IMemoryCache _cache;

    public async Task<string> GetOrGenerateContent(string cacheKey, Func<Task<string>> generateFunc)
    {
        if (_cache.TryGetValue(cacheKey, out string cachedContent))
            return cachedContent;

        var content = await generateFunc();
        _cache.Set(cacheKey, content, TimeSpan.FromHours(24));

        return content;
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Handle AI API Rate Limits

using Polly;
using IronPdf;
// Install via NuGet: Install-Package IronPdf and Polly

public async Task<string> GenerateContentWithRetry(string prompt)
{
    var retryPolicy = Policy
        .Handle<RateLimitException>()
        .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

    return await retryPolicy.ExecuteAsync(async () =>
    {
        // Call AI API
        return await _aiClient.Generate(prompt);
    });
}
Enter fullscreen mode Exit fullscreen mode

4. Use Templates for Consistent Branding

using IronPdf;
// Install via NuGet: Install-Package IronPdf

public class BrandedPdfGenerator
{
    private readonly string _template;

    public BrandedPdfGenerator()
    {
        _template = File.ReadAllText("templates/branded-report.html");
    }

    public PdfDocument Generate(string aiContent, Dictionary<string, string> data)
    {
        var html = _template
            .Replace("{{AI_CONTENT}}", aiContent)
            .Replace("{{DATE}}", DateTime.Now.ToString("MMMM dd, yyyy"));

        foreach (var kvp in data)
        {
            html = html.Replace($"{{{{{kvp.Key}}}}}", kvp.Value);
        }

        var renderer = new ChromePdfRenderer();
        return renderer.RenderHtmlAsPdf(html);
    }
}
Enter fullscreen mode Exit fullscreen mode

Cost Optimization: AI + PDF Generation

AI API costs add up:

  • OpenAI GPT-4: ~$0.03 per 1K tokens input, ~$0.06 per 1K tokens output
  • Claude Sonnet: ~$0.003 per 1K tokens input, ~$0.015 per 1K tokens output

Optimization strategies:

  1. Cache common responses (save 80% on repetitive queries)
  2. Use cheaper models for simple tasks (GPT-3.5 vs. GPT-4)
  3. Batch requests when possible
  4. Limit token usage with concise prompts

IronPDF has no per-document fees—generate unlimited PDFs once licensed.

Complete Example: AI-Powered Report Generator

using OpenAI;
using OpenAI.Chat;
using IronPdf;
// Install via NuGet: Install-Package IronPdf and OpenAI

public class AIReportGenerator
{
    private readonly OpenAIClient _aiClient;
    private readonly ChromePdfRenderer _pdfRenderer;

    public AIReportGenerator(string openAIKey)
    {
        _aiClient = new OpenAIClient(openAIKey);
        _pdfRenderer = new ChromePdfRenderer();
    }

    public async Task<PdfDocument> GenerateReport(ReportData data)
    {
        // Step 1: Generate narrative with AI
        var narrative = await GenerateNarrative(data);

        // Step 2: Create visualizations (charts, tables)
        var charts = GenerateCharts(data);

        // Step 3: Build HTML
        var html = BuildReportHtml(narrative, charts, data);

        // Step 4: Render PDF
        _pdfRenderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
        {
            HtmlFragment = "<div style='text-align: center;'>Page {page} of {total-pages}</div>"
        };

        var pdf = _pdfRenderer.RenderHtmlAsPdf(html);

        // Step 5: Add metadata
        pdf.MetaData.Title = $"Report - {data.Title}";
        pdf.MetaData.Author = "AI Report Generator";
        pdf.MetaData.CreationDate = DateTime.Now;

        return pdf;
    }

    private async Task<string> GenerateNarrative(ReportData data)
    {
        var prompt = $@"
Analyze this data and write an executive summary:

{data.ToJson()}

Write 3-4 paragraphs highlighting key insights, trends, and recommendations.
";

        var chatRequest = new ChatRequest
        {
            Model = "gpt-4",
            Messages = new[]
            {
                new ChatMessage { Role = "system", Content = "You are a data analyst writing executive reports." },
                new ChatMessage { Role = "user", Content = prompt }
            }
        };

        var response = await _aiClient.ChatEndpoint.GetCompletionAsync(chatRequest);
        return response.FirstChoice.Message.Content;
    }

    private string BuildReportHtml(string narrative, string charts, ReportData data)
    {
        return $@"
<!DOCTYPE html>
<html>
<head>
    <style>
        body {{ font-family: 'Segoe UI', Arial, sans-serif; margin: 40px; }}
        .header {{ background: #2c3e50; color: white; padding: 30px; text-align: center; }}
        .section {{ margin: 30px 0; }}
        .narrative {{ background: #ecf0f1; padding: 20px; line-height: 1.6; }}
    </style>
</head>
<body>
    <div class='header'>
        <h1>{data.Title}</h1>
        <p>Generated: {DateTime.Now:MMMM dd, yyyy}</p>
    </div>

    <div class='section'>
        <h2>Executive Summary</h2>
        <div class='narrative'>{narrative}</div>
    </div>

    <div class='section'>
        <h2>Data Visualizations</h2>
        {charts}
    </div>
</body>
</html>";
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Combining AI content generation with IronPDF's rendering capabilities unlocks powerful automation:

  • AI generates: Summaries, descriptions, narratives, personalized content
  • IronPDF renders: Professional PDFs with branding, styling, and structure

This pattern works for:

  • Monthly reports
  • Personalized marketing materials
  • Invoices with AI-generated descriptions
  • Legal contracts from templates
  • Customer proposals
  • Data-driven presentations

Key takeaways:

  1. AI handles content generation (OpenAI, Claude, Gemini)
  2. IronPDF handles professional PDF rendering
  3. Always sanitize AI output before rendering
  4. Cache AI responses to reduce costs
  5. Use templates for consistent branding

Start experimenting—the combination is powerful and surprisingly simple to implement.


Written by Jacob Mellor, CTO at Iron Software. Jacob created IronPDF and leads a team of 50+ engineers building .NET document processing libraries.

Top comments (0)