DEV Community

TemplateMaster
TemplateMaster

Posted on

How to Generate PDFs via API in C# (using TemplateMaster)

✨ Introduction

Generating PDFs dynamically in a C# application is a common need: invoices, quotes, certificates, contracts…
But implementing your own PDF engine is painful — libraries are heavy, HTML rendering is inconsistent, and templates are hard to maintain.

That's why I built TemplateMaster, a simple API-based service that lets you generate PDF documents from templates using clean JSON data.

In this article, I’ll show you how to generate a PDF from C# in just a few lines of code.

🔧 Step 1 — Add your configuration in appsettings.json

{
  "TemplateMaster": {
    "ApiKey": "YOUR_API_KEY_HERE",
    "BaseUrl": "https://api.templatemaster.fr"
  }
}
Enter fullscreen mode Exit fullscreen mode

🔨 Step 2 — Create a TemplateMaster API client

public class TemplateMasterClient
{
    private readonly HttpClient _http;
    private readonly string _apiKey;

    public TemplateMasterClient(HttpClient http, IConfiguration config)
    {
        _http = http;
        _apiKey = config["TemplateMaster:ApiKey"];

        _http.BaseAddress = new Uri(config["TemplateMaster:BaseUrl"]);
        _http.DefaultRequestHeaders.Add("X-API-KEY", _apiKey);
    }
}

Enter fullscreen mode Exit fullscreen mode

This client automatically injects the API key into every request.

📄 Step 3 — Generate a PDF

Endpoint used:
POST /documents/generate

C# method:

public async Task<byte[]> GenerateDocument(string templateId, object model)
{
    var request = new
    {
        TemplateId = templateId,
        Data = model
    };

    var response = await _http.PostAsJsonAsync("/documents/generate", request);
    response.EnsureSuccessStatusCode();

    var result = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
    var fileUrl = result["FileUrl"];

    return await _http.GetByteArrayAsync(fileUrl);
}

▶️ Usage example
var pdf = await _templateMaster.GenerateDocument("invoice-template", new {
    Customer = "John Doe",
    Amount = 120.50,
    Date = DateTime.Now.ToString("yyyy-MM-dd")
});

await File.WriteAllBytesAsync("invoice.pdf", pdf);
Enter fullscreen mode Exit fullscreen mode

🚀 Try TemplateMaster

You can test the API for free here:
👉 https://templatemaster.fr/

Top comments (0)