API guide · Quickstart · C#

Generate PDFs from JSON in C#

This quickstart turns a JSON array into PDFs with the RowScribe API: one PDF for each object in the array, made from a template you design in RowScribe. The whole program is about 95 lines of C# using only HttpClient and System.Text.Json. It sends the rows, waits for the job and saves the result.

Last updated November 27, 2026

What you need

  • .NET 8 or later. The program uses only HttpClient and System.Text.Json.
  • A template. In RowScribe, create a PDF template from the Award Certificate starter. The example rows below have its columns. To use your own template, give each row that template's columns instead.
  • An API key with the templates:read and jobs:write scopes, from Developers → API. API access is on Starter and above. The key is shown once, so copy it then.

Steps

  1. Set your key and template

    The program reads both from environment variables. The template's id is in its address in the editor (/templates/{id}/edit/pdf), or in GET /templates.

    macOS / Linux
    export ROWSCRIBE_API_KEY="rsc_…"
    export ROWSCRIBE_TEMPLATE_ID="your template's id"
    Windows (PowerShell)
    $env:ROWSCRIBE_API_KEY = "rsc_…"
    $env:ROWSCRIBE_TEMPLATE_ID = "your template's id"
  2. Save the rows

    Each object becomes one PDF, and each key is a column the template prints. Save this as rows.json.

    rows.json
    [
      {
        "OrganizationName": "Acme Inc.",
        "RecipientName": "John Smith",
        "AwardTitle": "Outstanding Customer Service",
        "AwardDescription": "For outstanding dedication to our customers in 2026.",
        "Date": "December 12, 2026",
        "SignerName": "Sarah Johnson",
        "SignerTitle": "Chief Executive Officer",
        "SecondSignerName": "Michael Brown",
        "SecondSignerTitle": "Head of People"
      },
      {
        "OrganizationName": "Acme Inc.",
        "RecipientName": "Jane Doe",
        "AwardTitle": "Excellence in Teamwork",
        "AwardDescription": "For bringing the whole team together on every project in 2026.",
        "Date": "December 12, 2026",
        "SignerName": "Sarah Johnson",
        "SignerTitle": "Chief Executive Officer",
        "SecondSignerName": "Michael Brown",
        "SecondSignerTitle": "Head of People"
      },
      {
        "OrganizationName": "Acme Inc.",
        "RecipientName": "Emily Davis",
        "AwardTitle": "Five Years of Service",
        "AwardDescription": "For five years of hard work and loyalty to Acme Inc.",
        "Date": "December 12, 2026",
        "SignerName": "Sarah Johnson",
        "SignerTitle": "Chief Executive Officer",
        "SecondSignerName": "Michael Brown",
        "SecondSignerTitle": "Head of People"
      }
    ]
  3. Save the program

    Run this first:

    Terminal
    dotnet new console -o generate

    Then, in the generate folder it made, replace Program.cs with the program below and put rows.json next to it.

    Program.cs
    // Generate one PDF per row of rows.json with the RowScribe API.
    // Needs .NET 8 or later. Run: dotnet run
    using System.Net.Http.Json;
    using System.Text.Json;
    
    const string api = "https://rowscribe.com/api/v1/";
    var templateId = Environment.GetEnvironmentVariable("ROWSCRIBE_TEMPLATE_ID") ?? Stop<string>("Set ROWSCRIBE_TEMPLATE_ID.");
    using var http = new HttpClient { BaseAddress = new Uri(api) };
    http.DefaultRequestHeaders.Add("X-API-Key",
        Environment.GetEnvironmentVariable("ROWSCRIBE_API_KEY") ?? Stop<string>("Set ROWSCRIBE_API_KEY."));
    
    // 1. The template, and the columns each row needs.
    var template = await ReadAsync(await http.GetAsync($"templates/{templateId}"));
    var rows = JsonSerializer.Deserialize<List<Dictionary<string, JsonElement>>>(await File.ReadAllTextAsync("rows.json"))!;
    var columns = rows.SelectMany(row => row.SelectMany(column => Keys(column.Key, column.Value))).ToHashSet();
    var missing = template.GetProperty("dataColumns").EnumerateArray()
        .Select(column => column.GetString()!)
        .Where(column => !columns.Contains(column))
        .ToList();
    if (missing.Count > 0)
        Stop<int>($"rows.json has no {string.Join(", ", missing)}, which {template.GetProperty("name").GetString()} uses.");
    
    // 2. One job: each row becomes one PDF. The Idempotency-Key makes a retried request safe.
    using var request = new HttpRequestMessage(HttpMethod.Post, "jobs") { Content = JsonContent.Create(new { templateId, rows }) };
    request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
    var response = await http.SendAsync(request);
    var job = await ReadAsync(response);
    var id = job.GetProperty("id").GetString();
    Console.WriteLine($"Job {id}: {job.GetProperty("totalRows").GetInt32()} rows");
    
    // 3. Wait for it, checking as often as Retry-After says.
    string[] waiting = ["pending", "scheduled", "processing"];
    var deadline = DateTime.UtcNow.AddMinutes(10);
    while (waiting.Contains(Status(job)))
    {
        if (DateTime.UtcNow > deadline)
            Stop<int>($"Still {Status(job)} after 10 minutes; job {id} carries on in RowScribe.");
        await Task.Delay(response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(5));
        response = await http.GetAsync($"jobs/{id}");
        job = await ReadAsync(response);
    }
    
    if (Status(job) != "completed")
    {
        var reason = job.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.String
            ? error.GetString()
            : "see the job in RowScribe";
        Stop<int>($"Job {Status(job)}: {reason}");
    }
    
    // 4. Download: one PDF, or a ZIP with a PDF per row.
    var file = await http.GetAsync($"jobs/{id}/download");
    await EnsureOkAsync(file);
    var name = file.Content.Headers.ContentType?.MediaType == "application/pdf" ? "output.pdf" : "output.zip";
    await File.WriteAllBytesAsync(name, await file.Content.ReadAsByteArrayAsync());
    Console.WriteLine($"Saved {name}");
    
    static string? Status(JsonElement job) => job.GetProperty("status").GetString();
    
    // A row's columns are its keys, and the keys of the items in any list (an invoice's line items).
    static IEnumerable<string> Keys(string name, JsonElement value) =>
        value.ValueKind != JsonValueKind.Array
            ? [name]
            : value.EnumerateArray()
                .Where(item => item.ValueKind == JsonValueKind.Object)
                .SelectMany(item => item.EnumerateObject().SelectMany(property => Keys(property.Name, property.Value)))
                .Prepend(name);
    
    static async Task<JsonElement> ReadAsync(HttpResponseMessage response)
    {
        await EnsureOkAsync(response);
        return await response.Content.ReadFromJsonAsync<JsonElement>();
    }
    
    // Every error has a code and a message; stop on the first one.
    static async Task EnsureOkAsync(HttpResponseMessage response)
    {
        if (response.IsSuccessStatusCode) return;
        string code = "", message = response.ReasonPhrase ?? "";
        try
        {
            var error = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync());
            code = error.GetProperty("code").GetString() ?? "";
            message = error.GetProperty("message").GetString() ?? message;
        }
        catch (Exception e) when (e is JsonException or KeyNotFoundException or InvalidOperationException) { }
        Stop<int>($"{(int)response.StatusCode} {code}: {message}");
    }
    
    static T Stop<T>(string message)
    {
        Console.Error.WriteLine(message);
        Environment.Exit(1);
        return default!;
    }
  4. Run it

    Terminal
    dotnet run

    It prints the job and the file it saved: output.zip, with a PDF for each row, or output.pdf when the job's documents are merged into one. Each row counts as one document toward your plan's monthly allowance.

    Output
    Job 8d0f6c2a-4b1e-4c57-9a3e-2f6d1b7c9e40: 3 rows
    Saved output.zip

How it works

  1. GET /templates/{id} reads the columns the template needs. The program stops if none of the rows has one of them: the API refuses a job with a missing column, and this says which one before anything is sent. A column can also be a key of the items in a row's list, such as an invoice's line items in "Items": [{ "Description": …, "Qty": … }].
  2. POST /jobs creates one job for all the rows, with an Idempotency-Key so a retried request can't create it twice.
  3. GET /jobs/{id} checks on the job as often as its Retry-After header says, until it has finished. It gives up after ten minutes; the job carries on either way.
  4. GET /jobs/{id}/download saves the output.

Every error the API returns has a code and a message, and the program stops with both. The errors table lists every code.

Next steps

  • Be told when it's done. In production a webhook beats checking: RowScribe posts a signed job.completed event to your server when the documents are ready. See Webhooks.
  • Email each person their PDF. Add a delivery to the job to send each row's PDF from your connected Gmail or Outlook, or to upload the output to your own storage. See Delivering documents.
  • Every endpoint is in the API reference, with a Postman collection.
  • The same program in Node.js and Python, and all three on GitHub.