C# PDF report generator: a paged table with totals and page numbers
Published 3 min read
A report is rows that do not fit on one page. It needs a table that carries its header onto the next sheet, a total at the end and a “Page 2 of 5” on every page. In C# that is a layout job more than a code job, and it is easier when the layout is HTML and CSS you already know. This guide builds one with the rustedf.cloud API and a typed client like the one in the C# and ASP.NET Core guide.
The data
Send the rows as a list and the amounts as text:
using System.Globalization;
public sealed record SaleRow(string Product, int Quantity, string Amount);
var rows = sales .Select(s => new SaleRow( s.Product, s.Quantity, s.Total.ToString("0.00", CultureInfo.InvariantCulture))) .ToList();An amount written as "1234.50" is formatted for the reader by the currency filter, and it
avoids the surprises of floating point. System.Text.Json renames the properties of a record
(Product becomes product), so the template uses the lowercase names.
The template
The page rules, the table and the loop are all HTML and CSS:
<style> @page { size: A4; margin: 20mm; @bottom-right { content: "Page " counter(page) " of " counter(pages); } } th { text-align: left; border-bottom: 1pt solid #000; } td { padding: 3pt 0; border-bottom: 0.5pt solid #ccc; } .number { text-align: right; } tr { break-inside: avoid; }</style>
<h1>{{ title }}</h1><p>{{ generated | date(style="long") }}</p>
<table> <thead> <tr><th>Product</th><th class="number">Qty</th><th class="number">Amount</th></tr> </thead> <tbody> {% for row in rows %} <tr> <td>{{ row.product }}</td> <td class="number">{{ row.quantity | number }}</td> <td class="number">{{ row.amount | currency(code="USD") }}</td> </tr> {% endfor %} </tbody></table>
<p><strong>Total {{ total | currency(code="USD") }}</strong></p>Three details do the work of a report:
@pagesets the paper and the margin, and the margin box at the bottom holds the page number. You do not count pages: the total is filled in once the whole document is laid out.- The header row of a table is repeated on every page the table spans, so the column titles travel with the data.
break-inside: avoidkeeps a row from being split between two pages.
Render it and read the page count
Keep the template in a file or an embedded resource and send it as html, together with the
data:
public async Task<(byte[] Pdf, int Pages)> RenderReportAsync( string html, object data, CancellationToken cancellationToken = default){ using var response = await http.PostAsJsonAsync( "v1/render", new { html, data, locale = "en-US", title = "Sales report" }, cancellationToken);
if (!response.IsSuccessStatusCode) { var body = await response.Content.ReadFromJsonAsync<ErrorBody>(cancellationToken); throw new InvalidOperationException( body?.Error?.Message ?? $"Render failed ({(int)response.StatusCode})"); }
var pages = int.Parse(response.Headers.GetValues("X-Pages").First()); return (await response.Content.ReadAsByteArrayAsync(cancellationToken), pages);}
var data = new{ title = "Sales, October", generated = DateTime.UtcNow.ToString("yyyy-MM-dd"), rows, total = rows.Sum(r => decimal.Parse(r.Amount, CultureInfo.InvariantCulture)) .ToString("0.00", CultureInfo.InvariantCulture),};
var (pdf, pages) = await client.RenderReportAsync(template, data);The X-Pages header says how many pages the report has, so you can show it or refuse a
report that is too long without opening the file.
The html is sent again on every request. If the same report is generated often, save the
template in your account and send only the data with template_id; see
Render with a saved template.
When the report is long
A report that grows hits the limits of the plan, and each limit has its own answer:
| Status | code |
What happened |
|---|---|---|
| 413 | payload_too_large |
The request or the data is over a size limit. |
| 422 | invalid_template |
The template failed, or the report has more pages than your plan allows. |
| 504 | render_timeout |
The report took longer than your plan’s time limit. |
Two limits apply to data whatever the plan: at most 200,000 values and 32 levels deep. Add
up and group in your database and send the result; a report of a hundred thousand lines
usually needs a summary and a link to the detail, not every line.
Check the layout
Send the same body to POST /v1/validate while you build the report. It returns what the
service could not use and the number of pages, without a PDF and without a credit. In your
tests, add "strict": true so a report that starts using something unsupported fails with
422 strict_mode_rejected instead of silently losing it.
Read Supported HTML and CSS, Locales and formatting and Errors and limits. For the page rules in detail, see Page numbers, headers and footers in a PDF.
Keep reading
Code and integrations
Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Turn a Razor view into a PDF in ASP.NET Core with one API call: a view renderer, a print-ready view, an MVC action, a Razor Pages handler and the traps to avoid.
3 min read
Code and integrations
Convert a web page to PDF in C# without a headless browser
Fetch a page with HttpClient and turn its HTML into a PDF with one API call in C#. Which pages this suits, which it does not, and how to check before you rely on it.
3 min read
Code and integrations
Save a PDF in C#: to disk, as a download or in blob storage
Save the PDF returned by a render call in C#: write it to disk, send it as a download from ASP.NET Core, keep a signed link or upload it, and avoid saving an error.
2 min read
Code and integrations
Generate thousands of PDFs in C#: pacing, 429 and safe retries
Make a batch of PDFs from C# without a wall of 429 errors: pace the calls, retry only what is safe, resume a stopped run and stop when the credits run out.
3 min read