April 6, 2026

C# / .NET PDF API Guide — iTextSharp Alternative

C#.NETASP.NET CorePDF APIiTextSharp alternative

When generating PDFs in C#, developers typically reach for iTextSharp, QuestPDF, or FastReport.NET. However, iText 5 (iTextSharp) is EOL and in maintenance mode, receiving only security-related releases, while new development happens on iText Core 9. iText Core is dual-licensed: under AGPLv3 you may not deploy it on a network without disclosing your own application's source code, so closed-source SaaS products typically need a commercial license. QuestPDF is ergonomic, but it builds documents with a fluent C# API rather than converting HTML — if you want to turn a Razor view into a PDF, you need a separate conversion step.

FUNBREW PDF API lets you generate PDFs by posting HTML to an HTTP endpoint and then downloading the result. There is no PDF library license to manage, rendering runs outside your app server, and integrating it into ASP.NET Core takes a modest amount of code.

This guide walks you through integrating FUNBREW PDF API into an ASP.NET Core application using HttpClient with DI, Razor template rendering, BackgroundService-based async processing, HttpMessageHandler mocking for tests, and production best practices.

For other languages and frameworks, see the language quickstart guide. For error handling patterns, see the error handling guide.

Why API-Based PDF Generation?

The iTextSharp / iText 7 License Problem

iText 5 (iTextSharp) is EOL and in maintenance mode (security-related releases only); new development happens on iText Core 9. iText Core is offered under AGPLv3 or a commercial license. iText's own AGPLv3 page states that you may not deploy it on a network without disclosing the full source code of your own applications, and that a commercial license releases you from those copyleft restrictions. For proprietary SaaS products, that usually means buying a commercial license.

Library License Commercial Constraint
iTextSharp (iText 5) AGPL / Commercial (EOL, maintenance mode) Security fixes only; AGPL obligations or a commercial license
iText Core (7 and later) AGPLv3 / Commercial Commercial license if you cannot comply with AGPLv3
QuestPDF Community (free, with eligibility conditions) / Professional / Enterprise Paid license when you do not meet the Community conditions
FUNBREW PDF API SaaS (subscription) No library license; send HTML over HTTP

QuestPDF Is Not an HTML Converter

QuestPDF uses a fluent C# API to define PDF layouts programmatically and positions itself as an alternative to HTML-to-PDF tools. It excels at building structured documents in code, but reusing existing Razor views or HTML templates means adding a separate HTML-to-PDF step. With an API-based approach, you pass the HTML string you already have to the endpoint.

Server Resource Savings

Libraries like iText and QuestPDF run PDF generation inside your application process. Complex documents or high throughput can put significant pressure on CPU and memory. In containerized environments, you end up provisioning extra capacity specifically for PDF workloads.

With an API-based approach, rendering is offloaded to an external service. Your application only issues HTTP requests, keeping instance sizes smaller and scaling more predictable.

Japanese Font Support

When you generate Japanese PDFs with an in-process library, you are responsible for making suitable fonts such as Noto Sans JP available in every environment (development machines, CI, containers). FUNBREW PDF includes a Noto CJK JP font check, but the quality engine has plan and Gotenberg configuration requirements, so verify Japanese text in an actual PDF. For more details on Japanese font handling, see the Japanese font guide.

ASP.NET Core Project Setup

This guide targets .NET 8 (ASP.NET Core 8). There is no official FUNBREW .NET SDK; you call the REST API with HttpClient. In an ASP.NET Core project, HttpClient, IHttpClientFactory, and System.Net.Http.Json are available without extra NuGet packages (the resilience and Key Vault sections below add packages).

The API works in two steps:

  1. POST https://pdf.funbrew.cloud/api/pdf/generate-from-html with {"html": "...", "options": {...}} and an Authorization: Bearer <API key> header. The response is JSON, not PDF bytes: {"success": true, "data": {"download_url": "...", ...}}.
  2. GET the data.download_url with the same Bearer key to receive the PDF bytes.

Options go under options: page-size (A3, A4, A5, Letter, Legal), orientation (Portrait, Landscape), margin-top / margin-right / margin-bottom / margin-left (numbers in mm, 0–50), and engine (fast or quality). See the API documentation for all fields.

appsettings.json Configuration

Never hardcode API keys in source code. Read them from environment variables or a secrets manager.

// appsettings.json
{
  "FunbrewPdf": {
    "ApiUrl": "https://pdf.funbrew.cloud/api/pdf/generate-from-html",
    "TimeoutSeconds": 60
  }
}
// appsettings.Development.json
{
  "FunbrewPdf": {
    "ApiKey": "sk-your-dev-api-key"
  }
}

In production, override with an environment variable:

FunbrewPdf__ApiKey=sk-your-production-api-key

Options Class

Use the IOptions<T> pattern to bind configuration in a type-safe way.

// FunbrewPdfOptions.cs
namespace MyApp.Pdf;

public sealed class FunbrewPdfOptions
{
    public const string SectionName = "FunbrewPdf";

    public string ApiKey { get; set; } = string.Empty;
    public string ApiUrl { get; set; } = "https://pdf.funbrew.cloud/api/pdf/generate-from-html";
    public int TimeoutSeconds { get; set; } = 60;
}

PdfService Implementation

Encapsulate all PDF API logic in a service class with a dedicated interface, so it can be mocked in tests.

// IPdfService.cs
namespace MyApp.Pdf;

public interface IPdfService
{
    Task<byte[]> GenerateFromHtmlAsync(string html, PdfGenerateOptions? options = null, CancellationToken ct = default);
}
// PdfGenerateOptions.cs
namespace MyApp.Pdf;

public sealed class PdfGenerateOptions
{
    public string PageSize { get; set; } = "A4";          // A3, A4, A5, Letter, Legal
    public string Orientation { get; set; } = "Portrait"; // Portrait or Landscape
    public string Engine { get; set; } = "fast";          // fast or quality (quality requires a paid plan)
    public MarginOptions? Margin { get; set; }
}

// Margins are numbers in millimetres (0-50)
public sealed class MarginOptions
{
    public double Top { get; set; } = 20;
    public double Right { get; set; } = 15;
    public double Bottom { get; set; } = 20;
    public double Left { get; set; } = 15;
}
// PdfService.cs
using System.Diagnostics;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Options;

namespace MyApp.Pdf;

public sealed class PdfService : IPdfService
{
    private readonly HttpClient _httpClient;
    private readonly FunbrewPdfOptions _options;
    private readonly ILogger<PdfService> _logger;

    public PdfService(
        HttpClient httpClient,
        IOptions<FunbrewPdfOptions> options,
        ILogger<PdfService> logger)
    {
        _httpClient = httpClient;
        _options    = options.Value;
        _logger     = logger;
    }

    public async Task<byte[]> GenerateFromHtmlAsync(
        string html,
        PdfGenerateOptions? options = null,
        CancellationToken ct = default)
    {
        var opts = options ?? new PdfGenerateOptions();

        // Keys such as "page-size" are not valid C# identifiers, so build the
        // request with dictionaries. System.Text.Json writes dictionary keys as-is.
        var pdfOptions = new Dictionary<string, object>
        {
            ["page-size"]   = opts.PageSize,
            ["orientation"] = opts.Orientation,
            ["engine"]      = opts.Engine,
        };

        if (opts.Margin is not null)
        {
            pdfOptions["margin-top"]    = opts.Margin.Top;
            pdfOptions["margin-right"]  = opts.Margin.Right;
            pdfOptions["margin-bottom"] = opts.Margin.Bottom;
            pdfOptions["margin-left"]   = opts.Margin.Left;
        }

        var payload = new Dictionary<string, object>
        {
            ["html"]    = html,
            ["options"] = pdfOptions,
        };

        var stopwatch = Stopwatch.StartNew();

        // Step 1: generate. The response is JSON that contains data.download_url.
        using var generateResponse = await _httpClient.PostAsJsonAsync(_options.ApiUrl, payload, ct);
        await EnsureSuccessAsync(generateResponse, "generate", stopwatch, ct);

        await using var json = await generateResponse.Content.ReadAsStreamAsync(ct);
        using var document   = await JsonDocument.ParseAsync(json, cancellationToken: ct);

        var downloadUrl =
            document.RootElement.TryGetProperty("data", out var data) &&
            data.TryGetProperty("download_url", out var url)
                ? url.GetString()
                : null;

        if (string.IsNullOrEmpty(downloadUrl))
        {
            throw new PdfGenerationException("PDF generation response did not contain data.download_url.");
        }

        // Step 2: download the PDF with the same Bearer key (set on the HttpClient).
        using var downloadResponse = await _httpClient.GetAsync(downloadUrl, ct);
        await EnsureSuccessAsync(downloadResponse, "download", stopwatch, ct);

        var pdfBytes = await downloadResponse.Content.ReadAsByteArrayAsync(ct);

        _logger.LogInformation(
            "PDF generated. Size={Size}bytes, Elapsed={Elapsed}ms",
            pdfBytes.Length, stopwatch.ElapsedMilliseconds);

        return pdfBytes;
    }

    private async Task EnsureSuccessAsync(
        HttpResponseMessage response, string step, Stopwatch stopwatch, CancellationToken ct)
    {
        if (response.IsSuccessStatusCode)
        {
            return;
        }

        var body = await response.Content.ReadAsStringAsync(ct);
        _logger.LogError(
            "PDF {Step} failed. Status={Status}, Elapsed={Elapsed}ms, Body={Body}",
            step, (int)response.StatusCode, stopwatch.ElapsedMilliseconds, body);

        throw new PdfGenerationException(
            $"PDF {step} failed: HTTP {(int)response.StatusCode} — {body}");
    }
}
// PdfGenerationException.cs
namespace MyApp.Pdf;

public sealed class PdfGenerationException : Exception
{
    public PdfGenerationException(string message) : base(message) { }
    public PdfGenerationException(string message, Exception inner) : base(message, inner) { }
}

Registering with the DI Container (Program.cs)

Use IHttpClientFactory — it manages the lifetime of the underlying handlers, which avoids the DNS problems that come from managing HttpClient lifetimes by hand.

// Program.cs
using MyApp.Pdf;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// Bind FunbrewPdf configuration section
builder.Services.Configure<FunbrewPdfOptions>(
    builder.Configuration.GetSection(FunbrewPdfOptions.SectionName));

// Register typed HttpClient
builder.Services.AddHttpClient<IPdfService, PdfService>(
    "FunbrewPdf",
    (sp, client) =>
    {
        var options = sp.GetRequiredService<IOptions<FunbrewPdfOptions>>().Value;
        client.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", options.ApiKey);
        client.Timeout = TimeSpan.FromSeconds(options.TimeoutSeconds);
    });

var app = builder.Build();
// ...
app.Run();

With this setup, IPdfService can be constructor-injected into controllers and other scoped or transient services. The Authorization header is configured once on the HttpClient and sent with both the generation request and the download request. Typed clients are registered as transient; do not capture them in singletons (see the BackgroundService section).

Basic PDF Generation

Returning a PDF from an API Controller

// Controllers/PdfController.cs
using Microsoft.AspNetCore.Mvc;
using MyApp.Pdf;

[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
    private readonly IPdfService _pdfService;

    public PdfController(IPdfService pdfService)
    {
        _pdfService = pdfService;
    }

    [HttpPost("generate")]
    public async Task<IActionResult> Generate(
        [FromBody] GeneratePdfRequest request,
        CancellationToken ct)
    {
        try
        {
            var pdfBytes = await _pdfService.GenerateFromHtmlAsync(request.Html, null, ct);
            return File(pdfBytes, "application/pdf", "document.pdf");
        }
        catch (PdfGenerationException ex)
        {
            return StatusCode(502, new { error = ex.Message });
        }
    }
}

public sealed record GeneratePdfRequest(string Html);

For a deep dive into HTML-to-PDF conversion techniques and CSS optimizations, see the HTML to PDF complete guide.

Razor Template Integration

The typical .NET pattern is to render a Razor view to an HTML string and then send that string to the API. This lets you reuse your existing view templates without any duplication.

IRazorViewRenderer

// IRazorViewRenderer.cs
namespace MyApp.Pdf;

public interface IRazorViewRenderer
{
    Task<string> RenderToStringAsync<TModel>(string viewName, TModel model);
}
// RazorViewRenderer.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;

namespace MyApp.Pdf;

public sealed class RazorViewRenderer : IRazorViewRenderer
{
    private readonly IRazorViewEngine _viewEngine;
    private readonly ITempDataProvider _tempDataProvider;
    private readonly IServiceProvider _serviceProvider;

    public RazorViewRenderer(
        IRazorViewEngine viewEngine,
        ITempDataProvider tempDataProvider,
        IServiceProvider serviceProvider)
    {
        _viewEngine      = viewEngine;
        _tempDataProvider = tempDataProvider;
        _serviceProvider = serviceProvider;
    }

    public async Task<string> RenderToStringAsync<TModel>(string viewName, TModel model)
    {
        var httpContext   = new DefaultHttpContext { RequestServices = _serviceProvider };
        var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

        using var sw = new StringWriter();

        // viewName is an app-relative path such as "~/Views/Pdf/Invoice.cshtml"
        var viewResult = _viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);
        if (!viewResult.Success)
        {
            throw new InvalidOperationException($"View '{viewName}' not found.");
        }

        var viewData = new ViewDataDictionary<TModel>(
            new EmptyModelMetadataProvider(),
            new ModelStateDictionary())
        {
            Model = model,
        };

        var tempData    = new TempDataDictionary(httpContext, _tempDataProvider);
        var viewContext = new ViewContext(
            actionContext,
            viewResult.View,
            viewData,
            tempData,
            sw,
            new HtmlHelperOptions());

        await viewResult.View.RenderAsync(viewContext);
        return sw.ToString();
    }
}

Register the renderer in Program.cs:

// Program.cs (additions)
builder.Services.AddControllersWithViews(); // required for Razor views
builder.Services.AddScoped<IRazorViewRenderer, RazorViewRenderer>();

Invoice ViewModel and Razor Template

// Models/InvoiceViewModel.cs
namespace MyApp.Models;

public sealed class InvoiceViewModel
{
    public string InvoiceNumber { get; set; } = "";
    public DateOnly IssuedAt { get; set; }
    public DateOnly DueAt { get; set; }
    public CustomerInfo Customer { get; set; } = new("", "", "");
    public CompanyInfo Company { get; set; } = new("", "", "");
    public List<InvoiceItem> Items { get; set; } = [];
    public decimal Total => Items.Sum(i => i.Quantity * i.UnitPrice);
}

public sealed record CustomerInfo(string Name, string Address, string Email);
public sealed record CompanyInfo(string Name, string Address, string Email);
public sealed record InvoiceItem(string Name, int Quantity, decimal UnitPrice);
@* Views/Pdf/Invoice.cshtml *@
@model MyApp.Models.InvoiceViewModel
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <style>
    body {
      font-family: -apple-system, 'Segoe UI', sans-serif;
      color: #1a1a1a;
      margin: 0;
      padding: 32px;
    }
    .header { display: flex; justify-content: space-between; margin-bottom: 32px; }
    .invoice-title { font-size: 28px; font-weight: 700; color: #2563eb; }
    table { width: 100%; border-collapse: collapse; margin-top: 24px; }
    th { background: #f1f5f9; padding: 10px 12px; text-align: left; font-size: 13px; }
    td { padding: 10px 12px; border-bottom: 1px solid #e2e8f0; font-size: 14px; }
    .total-row { text-align: right; font-size: 18px; font-weight: 700; margin-top: 16px; }
    .footer { margin-top: 48px; font-size: 12px; color: #64748b; text-align: center; }
  </style>
</head>
<body>
  <div class="header">
    <div>
      <div class="invoice-title">INVOICE</div>
      <p>No. @Model.InvoiceNumber</p>
      <p>Issued: @Model.IssuedAt.ToString("MMMM d, yyyy")</p>
      <p>Due: @Model.DueAt.ToString("MMMM d, yyyy")</p>
    </div>
    <div>
      <p><strong>@Model.Company.Name</strong></p>
      <p>@Model.Company.Address</p>
      <p>@Model.Company.Email</p>
    </div>
  </div>

  <div>
    <p><strong>Bill To: @Model.Customer.Name</strong></p>
    <p>@Model.Customer.Address</p>
  </div>

  <table>
    <thead>
      <tr>
        <th>Description</th>
        <th>Qty</th>
        <th>Unit Price</th>
        <th>Amount</th>
      </tr>
    </thead>
    <tbody>
      @foreach (var item in Model.Items)
      {
        <tr>
          <td>@item.Name</td>
          <td>@item.Quantity</td>
          <td>$@item.UnitPrice.ToString("N2")</td>
          <td>$@((item.Quantity * item.UnitPrice).ToString("N2"))</td>
        </tr>
      }
    </tbody>
  </table>

  <div class="total-row">
    Total: $@Model.Total.ToString("N2")
  </div>

  <div class="footer">
    @Model.Company.Name — @Model.Company.Address — @Model.Company.Email
  </div>
</body>
</html>

InvoiceController

// Controllers/InvoiceController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyApp.Models;
using MyApp.Pdf;

[Authorize]
public class InvoiceController : Controller
{
    private readonly IPdfService _pdfService;
    private readonly IRazorViewRenderer _renderer;

    public InvoiceController(IPdfService pdfService, IRazorViewRenderer renderer)
    {
        _pdfService = pdfService;
        _renderer   = renderer;
    }

    [HttpGet("/invoices/{invoiceId:int}/pdf")]
    public async Task<IActionResult> Download(int invoiceId, CancellationToken ct)
    {
        // In production, fetch data from your database
        var model = new InvoiceViewModel
        {
            InvoiceNumber = $"INV-{invoiceId:D5}",
            IssuedAt      = DateOnly.FromDateTime(DateTime.Today),
            DueAt         = DateOnly.FromDateTime(DateTime.Today.AddDays(30)),
            Customer      = new CustomerInfo("Acme Corp.", "123 Main St, San Francisco, CA", "billing@acme.com"),
            Company       = new CompanyInfo("My Company Inc.", "456 Market St, San Francisco, CA", "info@mycompany.com"),
            Items =
            [
                new InvoiceItem("Consulting services", 1, 1200.00m),
                new InvoiceItem("Support hours", 2, 150.00m),
            ],
        };

        var html = await _renderer.RenderToStringAsync("~/Views/Pdf/Invoice.cshtml", model);

        try
        {
            var pdfBytes = await _pdfService.GenerateFromHtmlAsync(html, new PdfGenerateOptions
            {
                PageSize    = "A4",
                Orientation = "Portrait",
                Engine      = "quality", // Chromium; requires a paid plan (otherwise HTTP 403)
            }, ct);

            return File(pdfBytes, "application/pdf", $"invoice-{invoiceId}.pdf");
        }
        catch (PdfGenerationException ex)
        {
            return StatusCode(502, ex.Message);
        }
    }
}

The quality engine renders with Chromium (Gotenberg) and requires a paid plan; on a plan without it, an explicit quality request returns HTTP 403. The fast engine uses wkhtmltopdf. For PDF-specific CSS techniques, see the HTML to PDF CSS optimization guide. For automating invoice PDF generation at scale, see the invoice PDF automation guide.

Async Processing with BackgroundService

For large reports or high-volume scenarios, it is better to queue jobs and process them in the background rather than blocking the HTTP request. The following pattern uses Channel<T> as an in-process queue with a BackgroundService worker. The queue lives in memory, so queued jobs are lost if the process restarts; use a durable queue if that matters. (FUNBREW also has a server-side batch endpoint, POST /api/pdf/batch, covered in the batch processing guide linked below.)

PdfJobQueue

// PdfJobQueue.cs
using System.Threading.Channels;

namespace MyApp.Pdf;

public sealed class PdfJobQueue
{
    private readonly Channel<PdfJob> _channel =
        Channel.CreateBounded<PdfJob>(new BoundedChannelOptions(1000)
        {
            FullMode = BoundedChannelFullMode.Wait,
        });

    public ValueTask EnqueueAsync(PdfJob job, CancellationToken ct = default)
        => _channel.Writer.WriteAsync(job, ct);

    public IAsyncEnumerable<PdfJob> ReadAllAsync(CancellationToken ct = default)
        => _channel.Reader.ReadAllAsync(ct);
}

public sealed record PdfJob(
    string JobId,
    string Html,
    string StoragePath,
    PdfGenerateOptions? Options = null);

PdfWorker (BackgroundService)

// PdfWorker.cs
using MyApp.Pdf;

public sealed class PdfWorker : BackgroundService
{
    private readonly PdfJobQueue _queue;
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<PdfWorker> _logger;

    // Hosted services are singletons. Do not inject the typed client (IPdfService)
    // directly; resolve a fresh one per job from a scope instead.
    public PdfWorker(PdfJobQueue queue, IServiceScopeFactory scopeFactory, ILogger<PdfWorker> logger)
    {
        _queue        = queue;
        _scopeFactory = scopeFactory;
        _logger       = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("PdfWorker started.");

        await foreach (var job in _queue.ReadAllAsync(stoppingToken))
        {
            try
            {
                _logger.LogInformation("Processing PDF job {JobId}", job.JobId);

                await using var scope = _scopeFactory.CreateAsyncScope();
                var pdfService = scope.ServiceProvider.GetRequiredService<IPdfService>();

                var pdfBytes = await pdfService.GenerateFromHtmlAsync(
                    job.Html, job.Options, stoppingToken);

                // In production, store to Azure Blob Storage, S3, etc.
                Directory.CreateDirectory(Path.GetDirectoryName(job.StoragePath)!);
                await File.WriteAllBytesAsync(job.StoragePath, pdfBytes, stoppingToken);

                _logger.LogInformation(
                    "PDF job {JobId} completed. Path={Path}", job.JobId, job.StoragePath);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "PDF job {JobId} failed.", job.JobId);
                // Notify via Slack, email, etc.
            }
        }
    }
}

Register in Program.cs:

// Program.cs (additions)
builder.Services.AddSingleton<PdfJobQueue>();
builder.Services.AddHostedService<PdfWorker>();

Enqueueing from a Controller

// Controllers/ReportController.cs
using Microsoft.AspNetCore.Mvc;
using MyApp.Pdf;

public sealed record ReportViewModel(int ReportId);

[ApiController]
[Route("api/[controller]")]
public class ReportController : ControllerBase
{
    private readonly PdfJobQueue _queue;
    private readonly IRazorViewRenderer _renderer;

    public ReportController(PdfJobQueue queue, IRazorViewRenderer renderer)
    {
        _queue    = queue;
        _renderer = renderer;
    }

    [HttpPost("{reportId:int}/generate")]
    public async Task<IActionResult> GenerateAsync(int reportId, CancellationToken ct)
    {
        var html = await _renderer.RenderToStringAsync("~/Views/Pdf/Report.cshtml", new ReportViewModel(reportId));

        var jobId      = Guid.NewGuid().ToString("N");
        var outputPath = $"/tmp/reports/report-{reportId}-{DateTime.UtcNow:yyyyMMdd}.pdf";

        await _queue.EnqueueAsync(new PdfJob(jobId, html, outputPath), ct);

        return Accepted(new
        {
            jobId,
            storagePath = outputPath,
            message     = "PDF generation started. The file will be available for download once complete.",
        });
    }
}

For batch processing patterns and high-volume generation strategies, see the PDF batch processing guide. For notifying clients when async PDF generation completes, see the webhook integration guide.

Testing with HttpMessageHandler Mocking

Because PdfService receives its HttpClient from outside, you can build it with a fake HttpMessageHandler in tests and avoid real HTTP calls. The fake below answers the generation POST with JSON and the download GET with PDF bytes, matching the real two-step flow.

FakeHttpMessageHandler

// Tests/FakeHttpMessageHandler.cs
namespace MyApp.Tests;

public sealed class FakeHttpMessageHandler : HttpMessageHandler
{
    private readonly Func<HttpRequestMessage, Task<HttpResponseMessage>> _handler;

    public FakeHttpMessageHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler)
    {
        _handler = handler;
    }

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
        => _handler(request);
}

Unit Tests for PdfService

// Tests/PdfServiceTests.cs
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using MyApp.Pdf;
using Xunit;

namespace MyApp.Tests;

public sealed class PdfServiceTests
{
    private const string DownloadUrl = "https://pdf.funbrew.cloud/api/pdf/download/test.pdf";

    private static IPdfService CreateService(
        Func<HttpRequestMessage, Task<HttpResponseMessage>> handler)
    {
        var fakeHandler = new FakeHttpMessageHandler(handler);
        var httpClient  = new HttpClient(fakeHandler);

        // Set the header manually because this test does not go through DI
        httpClient.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "test-api-key");

        var options = Options.Create(new FunbrewPdfOptions
        {
            ApiKey         = "test-api-key",
            ApiUrl         = "https://pdf.funbrew.cloud/api/pdf/generate-from-html",
            TimeoutSeconds = 30,
        });

        return new PdfService(httpClient, options, NullLogger<PdfService>.Instance);
    }

    // POST returns JSON with data.download_url; GET returns the PDF bytes
    private static HttpResponseMessage FakeApi(HttpRequestMessage request, byte[] pdf)
        => request.Method == HttpMethod.Post
            ? new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = JsonContent.Create(new { success = true, data = new { download_url = DownloadUrl } }),
            }
            : new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(pdf)
                {
                    Headers = { ContentType = new("application/pdf") },
                },
            };

    [Fact]
    public async Task GenerateFromHtmlAsync_ReturnsDownloadedPdfBytes()
    {
        var fakePdfBytes = "%PDF-1.4 fake content"u8.ToArray();
        var service = CreateService(req => Task.FromResult(FakeApi(req, fakePdfBytes)));

        var result = await service.GenerateFromHtmlAsync("<h1>Test</h1>");

        Assert.Equal(fakePdfBytes, result);
    }

    [Fact]
    public async Task GenerateFromHtmlAsync_SendsBearerKeyOnBothRequests()
    {
        var requests = new List<HttpRequestMessage>();
        var service = CreateService(req =>
        {
            requests.Add(req);
            return Task.FromResult(FakeApi(req, "%PDF"u8.ToArray()));
        });

        await service.GenerateFromHtmlAsync("<h1>Test</h1>");

        Assert.Equal(2, requests.Count);
        Assert.Equal(HttpMethod.Post, requests[0].Method);
        Assert.Equal(DownloadUrl, requests[1].RequestUri?.ToString());
        Assert.All(requests, r =>
        {
            Assert.Equal("Bearer", r.Headers.Authorization?.Scheme);
            Assert.Equal("test-api-key", r.Headers.Authorization?.Parameter);
        });
    }

    [Fact]
    public async Task GenerateFromHtmlAsync_ThrowsPdfGenerationException_OnApiError()
    {
        var service = CreateService(_ => Task.FromResult(
            new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("Internal Server Error"),
            }));

        await Assert.ThrowsAsync<PdfGenerationException>(
            () => service.GenerateFromHtmlAsync("<h1>Test</h1>"));
    }

    [Fact]
    public async Task GenerateFromHtmlAsync_SendsCorrectJsonPayload()
    {
        string? capturedBody = null;

        var service = CreateService(async req =>
        {
            if (req.Method == HttpMethod.Post)
            {
                capturedBody = await req.Content!.ReadAsStringAsync();
            }

            return FakeApi(req, "%PDF"u8.ToArray());
        });

        await service.GenerateFromHtmlAsync("<h1>Test</h1>", new PdfGenerateOptions
        {
            PageSize    = "Letter",
            Orientation = "Landscape",
            Margin      = new MarginOptions { Top = 10 },
        });

        // Parse instead of comparing raw strings: System.Text.Json escapes "<" by default
        using var json = JsonDocument.Parse(capturedBody!);
        var root    = json.RootElement;
        var options = root.GetProperty("options");

        Assert.Equal("<h1>Test</h1>", root.GetProperty("html").GetString());
        Assert.Equal("Letter", options.GetProperty("page-size").GetString());
        Assert.Equal("Landscape", options.GetProperty("orientation").GetString());
        Assert.Equal(10.0, options.GetProperty("margin-top").GetDouble());
    }
}

Integration Tests with WebApplicationFactory

WebApplicationFactory<Program> needs the Microsoft.AspNetCore.Mvc.Testing package and an accessible Program class (with top-level statements, add public partial class Program { } at the end of Program.cs).

// Tests/InvoiceControllerTests.cs
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using MyApp.Pdf;
using Xunit;

namespace MyApp.Tests;

public sealed class InvoiceControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public InvoiceControllerTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    private WebApplicationFactory<Program> CreateFactory(byte[]? fakePdf = null)
    {
        var pdf = fakePdf ?? "%PDF-1.4 fake invoice"u8.ToArray();

        return _factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(services =>
            {
                var descriptor = services.SingleOrDefault(
                    d => d.ServiceType == typeof(IPdfService));
                if (descriptor is not null)
                    services.Remove(descriptor);

                services.AddScoped<IPdfService>(_ => new FakePdfService(pdf));
            });
        });
    }

    [Fact]
    public async Task Download_ReturnsPdfFile_WithCorrectHeaders()
    {
        var client   = CreateFactory().CreateClient(
            new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });

        // InvoiceController has [Authorize]: register a test authentication scheme
        // first, otherwise this request returns 401 or a login redirect.
        var response = await client.GetAsync("/invoices/1/pdf");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal("application/pdf", response.Content.Headers.ContentType?.MediaType);
        Assert.Contains("invoice-1.pdf",
            response.Content.Headers.ContentDisposition?.FileName ?? "");
    }

    private sealed class FakePdfService : IPdfService
    {
        private readonly byte[] _pdf;
        public FakePdfService(byte[] pdf) => _pdf = pdf;
        public Task<byte[]> GenerateFromHtmlAsync(
            string html, PdfGenerateOptions? options, CancellationToken ct)
            => Task.FromResult(_pdf);
    }
}

Production Tips

Retry with Polly (.NET 8 Resilience)

Microsoft provides the Microsoft.Extensions.Http.Resilience NuGet package, which builds on Polly and plugs into IHttpClientFactory through AddResilienceHandler.

dotnet add package Microsoft.Extensions.Http.Resilience
// Program.cs (retry configuration)
using Microsoft.Extensions.Http.Resilience;
using Microsoft.Extensions.Options;
using Polly;

builder.Services.AddHttpClient<IPdfService, PdfService>(
    "FunbrewPdf",
    (sp, client) =>
    {
        var options = sp.GetRequiredService<IOptions<FunbrewPdfOptions>>().Value;
        client.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", options.ApiKey);
        client.Timeout = TimeSpan.FromSeconds(options.TimeoutSeconds);
    })
    .AddResilienceHandler("pdf-pipeline", pipeline =>
    {
        // Retry up to 3 times with exponential backoff
        pipeline.AddRetry(new HttpRetryStrategyOptions
        {
            MaxRetryAttempts = 3,
            BackoffType      = DelayBackoffType.Exponential,
            Delay            = TimeSpan.FromMilliseconds(500),
            ShouldHandle     = args => ValueTask.FromResult(
                args.Outcome.Result?.StatusCode is
                    System.Net.HttpStatusCode.TooManyRequests or
                    System.Net.HttpStatusCode.ServiceUnavailable or
                    System.Net.HttpStatusCode.GatewayTimeout),
        });

        // Per-attempt timeout of 30 seconds
        pipeline.AddTimeout(TimeSpan.FromSeconds(30));
    });

Two cautions. First, the generation call is a POST: Microsoft's resilience documentation warns that retrying a POST that inserts a record can duplicate data, and here a retried request after a timeout may create a second PDF that also counts toward your monthly quota. Second, FUNBREW returns HTTP 429 both for rate limiting and when the monthly generation limit is reached; retrying the latter will not succeed, so keep the retry count small and log the response body.

For a comprehensive error handling and retry strategy reference, see the error handling guide.

Response Caching with IMemoryCache

If you generate the same PDF repeatedly from the same data, cache the result to reduce API calls.

// CachedPdfService.cs (Decorator pattern)
using Microsoft.Extensions.Caching.Memory;

namespace MyApp.Pdf;

public sealed class CachedPdfService : IPdfService
{
    private readonly IPdfService _inner;
    private readonly IMemoryCache _cache;

    public CachedPdfService(IPdfService inner, IMemoryCache cache)
    {
        _inner = inner;
        _cache = cache;
    }

    public async Task<byte[]> GenerateFromHtmlAsync(
        string html,
        PdfGenerateOptions? options = null,
        CancellationToken ct = default)
    {
        var cacheKey = $"pdf:{ComputeHash(html, options)}";

        if (_cache.TryGetValue(cacheKey, out byte[]? cached))
            return cached!;

        var pdfBytes = await _inner.GenerateFromHtmlAsync(html, options, ct);

        _cache.Set(cacheKey, pdfBytes, new MemoryCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24),
            Size = pdfBytes.Length,
        });

        return pdfBytes;
    }

    private static string ComputeHash(string html, PdfGenerateOptions? options)
    {
        var m     = options?.Margin;
        var input = $"{html}|{options?.PageSize}|{options?.Orientation}|{options?.Engine}" +
                    $"|{m?.Top}|{m?.Right}|{m?.Bottom}|{m?.Left}";
        var bytes = System.Security.Cryptography.SHA256.HashData(
            System.Text.Encoding.UTF8.GetBytes(input));
        return Convert.ToHexString(bytes)[..16];
    }
}

Secure API Key Management

In production, never put the API key in appsettings.json. Use Azure Key Vault, AWS Secrets Manager, or your platform's native secret management. The Azure Key Vault example below needs the Azure.Extensions.AspNetCore.Configuration.Secrets and Azure.Identity packages:

// Program.cs (Azure Key Vault example)
using Azure.Identity;

if (builder.Environment.IsProduction())
{
    var keyVaultUri = builder.Configuration["KeyVaultUri"]!;
    builder.Configuration.AddAzureKeyVault(
        new Uri(keyVaultUri),
        new DefaultAzureCredential());
}

For a full security best practices reference, see the security guide.

Health Check

Register a health check that verifies the PDF API is reachable. Note that each run generates a real PDF, which counts toward your monthly generation limit, so run it infrequently (for example from a scheduled monitor rather than a frequent liveness probe):

// PdfApiHealthCheck.cs
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace MyApp.Pdf;

public sealed class PdfApiHealthCheck : IHealthCheck
{
    private readonly IPdfService _pdfService;

    public PdfApiHealthCheck(IPdfService pdfService)
    {
        _pdfService = pdfService;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        try
        {
            await _pdfService.GenerateFromHtmlAsync(
                "<p>health check</p>",
                new PdfGenerateOptions { Engine = "fast" },
                cancellationToken);

            return HealthCheckResult.Healthy("PDF API is reachable.");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("PDF API is not reachable.", ex);
        }
    }
}
// Program.cs (health check registration)
builder.Services.AddHealthChecks()
    .AddCheck<PdfApiHealthCheck>("pdf-api");

app.MapHealthChecks("/health");

For a full production operations reference, see the production guide.

When QuestPDF Is Not an Option: Using FUNBREW PDF API as an Alternative

QuestPDF is a popular choice for .NET PDF generation — its ergonomic fluent API makes it easy to adopt. However, there are scenarios where QuestPDF is not a viable option, and an HTTP-based API becomes the cleaner alternative.

QuestPDF Community vs Professional / Enterprise License

QuestPDF uses a tiered licensing model. According to its Community License summary:

Usage License
Individuals and businesses with annual gross revenue under USD 1,000,000 Community License (free)
Charitable organisations, academic institutions, and open-source projects Community License (free)
Public-sector entities and publicly traded companies (regardless of revenue), or others not eligible Professional or Enterprise License (paid)

The Community License is not the MIT License. For growing SaaS companies or enterprise teams, QuestPDF can become a paid dependency — check the current terms on the official license pages and factor the cost and compliance work into the build-vs-buy decision.

QuestPDF Is Built Around Code, Not HTML or Razor Views

QuestPDF's fluent API is designed for building PDF layouts programmatically in C#, and it does not present itself as an HTML-to-PDF converter. If your team maintains Razor views or produces HTML output from an API or templating engine, turning that HTML into a PDF means adding a separate HTML-to-PDF step.

With FUNBREW PDF API, you pass the HTML string your application already produces to the endpoint.

// QuestPDF approach: build layout programmatically
// (cannot reuse existing Razor views or HTML templates)
Document.Create(container =>
{
    container.Page(page =>
    {
        page.Content().Text(invoiceModel.CustomerName);
        // Every layout element must be defined in C# code
    });
}).GeneratePdf("output.pdf");

// FUNBREW PDF API approach: send existing HTML, then download the PDF
var html = await _renderer.RenderToStringAsync("~/Views/Pdf/Invoice.cshtml", model);
var pdfBytes = await _pdfService.GenerateFromHtmlAsync(html);
// Reuses your existing Razor template — no duplication

Switching from QuestPDF to FUNBREW PDF API

If you need to migrate an existing QuestPDF implementation to FUNBREW PDF API:

  1. Create an HTML template that mirrors your QuestPDF layout. Use print CSS (@page, @media print) for page size and margins. See the HTML to PDF CSS tips guide for CSS patterns.
  2. Render the template to a string using IRazorViewRenderer (see the Razor integration section above).
  3. POST the HTML string to the FUNBREW PDF API via IPdfService.GenerateFromHtmlAsync.
  4. Remove the QuestPDF NuGet package once nothing references it — the API calls only need HttpClient.

For Japanese language PDFs, you no longer manage font files inside your own containers, but you should still verify the output: FUNBREW PDF includes a Noto CJK JP font check, and the quality engine has plan and Gotenberg configuration requirements. See the Japanese font guide for details.

When to Stay with QuestPDF

QuestPDF remains a good choice when:

  • Your team prefers building document layouts entirely in C# (no HTML templates to maintain).
  • You qualify for the Community License (for example, annual gross revenue under USD 1,000,000 and not a public-sector or publicly traded entity).
  • You need very precise programmatic control over document structure that HTML/CSS cannot express easily.

For all other scenarios — particularly when HTML-to-PDF conversion, Razor template reuse, Docker image size, or CJK font support matter — FUNBREW PDF API is typically the lower-maintenance path.

Library Comparison

Aspect iTextSharp / iText 7 QuestPDF FUNBREW PDF API
License AGPLv3 / Commercial Community (conditions apply) / Professional / Enterprise SaaS (subscription)
HTML support pdfHTML add-on (HTML5 / CSS3) Not an HTML converter (fluent layout API) Send HTML over HTTP
CSS support Via pdfHTML Custom layout API quality: Chromium (Gotenberg); fast: wkhtmltopdf
Razor templates Render to HTML, then pdfHTML Rebuild the layout in C# Render to HTML, then send the string
Japanese text You provide fonts You provide fonts Noto CJK JP check; verify output
Docker image Straightforward (include fonts) Straightforward Tiny (external API call only)
Server load Runs on app server Runs on app server Offloaded to external service
Testability Wrap behind your own interface Wrap behind your own interface Fake HttpMessageHandler
Setup NuGet + font config NuGet only API key only

When to use which:

  • iText Core: You already have a commercial license (or can meet AGPLv3) and need low-level PDF specification access.
  • QuestPDF: You prefer building layouts programmatically in C# and don't have existing HTML templates.
  • FUNBREW PDF API: You want to convert existing Razor views to PDF, you're running in Docker/Kubernetes, you need Japanese PDF support, or you want Chromium-based CSS rendering with the quality engine.

Summary

Integrating FUNBREW PDF API into ASP.NET Core takes a small service class with HttpClient and DI: POST the HTML, then download data.download_url with the same Bearer key. The patterns in this guide give you a testable, production-ready PDF generation feature:

  1. DI-first design — Encapsulate logic in IPdfService, keep controllers thin.
  2. Reuse Razor templates — IRazorViewRenderer turns any existing view into an HTML string to send to the API.
  3. Async with BackgroundService — Use Channel<T> and PdfWorker for background processing, resolving IPdfService per job from a scope; don't block the HTTP response.
  4. Mock with FakeHttpMessageHandler — Fast, deterministic tests without hitting the real API.
  5. Resilience with Polly — AddResilienceHandler retries transient failures; keep POST retries conservative.

Try your HTML in the Playground to see the output before writing any code. When you are ready, check the API documentation for all available options and the pricing page to choose a plan.

Related Articles

Powered by FUNBREW PDF