Frameworks · Updated 2026-12-03
Generate PDFs in C# and .NET
This guide turns JSON into a finished PDF from C#. You send a template id and your data to one endpoint and get a link or the file back. There is no headless browser or wkhtmltopdf binary to install, patch and keep alive on your servers, so the same code runs on Windows, Linux containers, Azure App Service or AWS Lambda.
You need .NET 8 or later and a DevilPDF API key. The free plan includes 500 documents a month.
#1. Get an API key
Sign up, open API keys in the dashboard and create a key. It starts with dp_live_. Keep it in an environment variable or your secrets store, never in appsettings.json you commit:
export DEVILPDF_API_KEY="dp_live_..."ASP.NET Core and the generic host read environment variables into IConfiguration, so configuration["DEVILPDF_API_KEY"] finds it. In development you can use dotnet user-secrets set DEVILPDF_API_KEY dp_live_... instead.
#2. Add a typed client
One small class wraps the API. It is registered with IHttpClientFactory, so connections are pooled and reused, and the key is read from configuration once.
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public sealed record RenderRequest(
string Template,
object Data,
string? Filename = null,
string? Locale = null,
string? Output = null);
public sealed record RenderedDocument(string Id, string Status, string? Url, int? Pages, long Bytes);
public sealed record ApiError(string Type, string Message);
public sealed record ErrorBody(ApiError Error);
public sealed class DevilPdfException(int status, string type, string message)
: Exception($"{type}: {message}")
{
public int Status { get; } = status;
public string Type { get; } = type;
}
public sealed class DevilPdfClient(HttpClient http)
{
static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
// Returns the document object with a signed download link.
public async Task<RenderedDocument> RenderAsync(RenderRequest request, CancellationToken ct = default)
{
using var res = await http.PostAsJsonAsync("v1/render", request, Json, ct);
await ThrowIfFailedAsync(res, ct);
return (await res.Content.ReadFromJsonAsync<RenderedDocument>(Json, ct))!;
}
// Returns the PDF bytes. Nothing is stored on DevilPDF's side.
public async Task<byte[]> RenderPdfAsync(RenderRequest request, CancellationToken ct = default)
{
using var res = await http.PostAsJsonAsync("v1/render", request with { Output = "file" }, Json, ct);
await ThrowIfFailedAsync(res, ct);
return await res.Content.ReadAsByteArrayAsync(ct);
}
static async Task ThrowIfFailedAsync(HttpResponseMessage res, CancellationToken ct)
{
if (res.IsSuccessStatusCode) return;
var body = await res.Content.ReadFromJsonAsync<ErrorBody>(Json, ct);
throw new DevilPdfException(
(int)res.StatusCode,
body?.Error.Type ?? "unknown",
body?.Error.Message ?? res.ReasonPhrase ?? "Request failed");
}
}
public static class DevilPdfServiceCollectionExtensions
{
public static IServiceCollection AddDevilPdf(this IServiceCollection services)
{
services.AddHttpClient<DevilPdfClient>((sp, client) =>
{
var key = sp.GetRequiredService<IConfiguration>()["DEVILPDF_API_KEY"]
?? throw new InvalidOperationException("DEVILPDF_API_KEY is not set.");
client.BaseAddress = new Uri("https://devilpdf.com/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
client.Timeout = TimeSpan.FromSeconds(60);
});
return services;
}
}JsonNamingPolicy.SnakeCaseLower writes C# names the way the API expects: Filename becomes filename, and a UnitPrice property on your own records becomes unit_price. Null fields are left out of the request.
#3. Render an invoice and get a link
Every account can use seven starter templates: invoice, quote, receipt, statement, report, packing-slip and certificate. This console app renders the invoice starter. Add the hosting packages first:
dotnet new console -n Invoices
cd Invoices
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.Httpusing Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddDevilPdf();
using var host = builder.Build();
var devilpdf = host.Services.GetRequiredService<DevilPdfClient>();
var doc = await devilpdf.RenderAsync(new RenderRequest(
Template: "invoice",
Filename: "INV-1001",
Data: new
{
number = "INV-1001",
issue_date = "2026-12-03",
due_date = "2027-01-02",
company = new { name = "Northwind Studio", address = "410 Bay Street\nToronto, ON M5H 2Y4" },
customer = new { name = "Acme Robotics Inc.", address = "2200 Mission Street\nSan Francisco, CA 94110" },
items = new object[]
{
new { name = "Brand identity system", quantity = 1, unit_price = 4800m },
new { name = "Front-end development", description = "Billed hourly", quantity = 46, unit_price = 135m },
},
tax_rate = 13,
tax_label = "HST",
}));
Console.WriteLine($"{doc.Url} pages: {doc.Pages}");Run it with dotnet run. The response is a document object with an id, the page count in pages, and a signed download link in url. The template adds up the line items, tax and total itself, so you never send totals.
Anonymous objects keep the data close to the JSON it becomes. Your own records and classes work just as well. decimal values go out as JSON numbers, so money needs no conversion.
To see every field a starter accepts, fetch it and read sample_data:
curl https://devilpdf.com/v1/templates/invoice \
-H "Authorization: Bearer $DEVILPDF_API_KEY"#4. Get the PDF bytes and save them
RenderPdfAsync sends "output": "file", so the response body is the PDF itself.
var pdf = await devilpdf.RenderPdfAsync(new RenderRequest(
Template: "receipt",
Data: new
{
number = "R-10482",
paid_at = "2026-12-03",
company = new { name = "Lumen Cycle Works" },
customer = new { name = "Jordan Alvarez" },
payment = new { method = "Visa", last4 = "4242" },
items = new[] { new { name = "Full tune-up", quantity = 1, unit_price = 129m } },
}));
await File.WriteAllBytesAsync("receipt.pdf", pdf);
Console.WriteLine($"Saved receipt.pdf ({pdf.Length} bytes)");Errors still come back as JSON with an error object, which is why the client checks the status before reading the body as a file. The devilpdf-document-id and devilpdf-pages response headers identify the document if you want them in your log.
#5. Return it from an ASP.NET Core minimal API
An endpoint that sends a PDF to the browser. The API key stays on the server.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDevilPdf();
var app = builder.Build();
app.MapGet("/invoices/{number}.pdf", async (string number, DevilPdfClient devilpdf, CancellationToken ct) =>
{
var order = await LoadOrderAsync(number);
if (order is null) return Results.NotFound();
try
{
var pdf = await devilpdf.RenderPdfAsync(
new RenderRequest("invoice", order, Filename: $"invoice-{number}"), ct);
return Results.File(pdf, "application/pdf");
}
catch (DevilPdfException ex)
{
return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway);
}
});
app.Run();
// Replace with your database lookup.
static Task<object?> LoadOrderAsync(string number) => Task.FromResult<object?>(new
{
number,
customer = new { name = "Acme Robotics Inc." },
items = new[] { new { name = "Consulting", quantity = 3, unit_price = 150m } },
});Results.File(pdf, "application/pdf") opens the PDF in the browser tab. Pass a third argument, such as $"invoice-{number}.pdf", to make it a download with that file name instead.
#6. Or from an MVC controller
The same request from a controller, built from an Entity Framework Core entity. Register controllers with builder.Services.AddControllers() and app.MapControllers() next to AddDevilPdf().
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
[ApiController]
[Route("invoices")]
public sealed class InvoicesController(DevilPdfClient devilpdf, AppDbContext db) : ControllerBase
{
[HttpGet("{number}.pdf")]
public async Task<IActionResult> Pdf(string number, CancellationToken ct)
{
var invoice = await db.Invoices
.Include(i => i.Lines)
.SingleOrDefaultAsync(i => i.Number == number, ct);
if (invoice is null) return NotFound();
var pdf = await devilpdf.RenderPdfAsync(new RenderRequest(
Template: "invoice",
Data: new
{
number = invoice.Number,
customer = new { name = invoice.CustomerName },
items = invoice.Lines.Select(l => new { name = l.Name, quantity = l.Quantity, unit_price = l.UnitPrice }),
}), ct);
return File(pdf, "application/pdf", $"invoice-{invoice.Number}.pdf");
}
}AppDbContext, Invoices and Lines stand for your own model. A render normally takes well under a second, so calling it inside a request is fine.
#7. Any language, same code
Add Locale and the starter's labels, dates and money switch language. Arabic, Hebrew, Persian and Urdu also flip the page right to left. Fonts for every script are loaded for you.
var pdf = await devilpdf.RenderPdfAsync(new RenderRequest(
Template: "invoice",
Locale: "ar",
Data: new
{
number = "INV-1002",
currency = "SAR",
customer = new { name = "شركة الأفق للتجارة" },
items = new[] { new { name = "استشارات", quantity = 3, unit_price = 1250m } },
}));See languages and locales for the full list.
#Many documents at once
For hundreds of PDFs, do not loop over /v1/render and await each one. Send them to POST /v1/render/batch in one request, with what they share at the top level and what differs in items, and get a webhook when they finish. Batch documents are always stored and returned as links. See async and batch.
If a call fails, branch on DevilPdfException.Type, not the message. rate_limited, render_timeout and internal_error are worth a retry with a short backoff; anything else will fail the same way until the request changes. See errors.
#Next steps
- Quickstart: the same request in curl, Node, Python, PHP, Go and Ruby.
- Render reference: page size, margins, passwords and every other option.
- Templates: copy a starter and make it yours.
- Generate PDFs in Node.js and in Python.
- Get a free API key