PDF documents
Paperwork is a small web app that makes three PDF documents, the way a business needs them.
Each document is an HTML page with CSS. Novis\Pdf\Document turns it into a PDF file.
The links below open the files that the app returns. You can look at them before you install anything.
The invoice
Section titled “The invoice”The invoice has three pages. The table of items continues from one page to the next, and each page shows the amount carried forward. At the end, a banking app can read a QR code to pay the invoice.
The file follows PDF/A-3b, the standard for archived files. It also contains the same invoice as XML in the Factur-X format. An accounting program reads this XML, so nobody needs to type the invoice again.
The quarterly report
Section titled “The quarterly report”The report has eight pages: a cover, a table of contents, key figures, charts and tables. It is
confidential, so the file is encrypted. Your PDF viewer needs the password novis before it shows the
report.
The file follows PDF/UA-1, the standard for accessible files. A screen reader can read it aloud, and each chart has a text that describes it.
The event tickets
Section titled “The event tickets”This file is for the person who bought four tickets. Page 1 is a summary of the order. Then each
ticket has its own page, with a QR code and a barcode. The app renders each ticket as its own PDF
file. Then Pages::merge joins the five files into one.
The code
Section titled “The code”Each tab shows one file of the app. These are the same files that you download below.
# The server listens on port 8143. The other apps in this repository use other ports,# so all of them can run at the same time.[server]listen = ["127.0.0.1:8143"]
# The app reads one file: the logo that the three documents show.# The path is relative to this folder. The app may read no other file, and it may write none.[capabilities.fs]read = ["assets/logo.svg"]<?nvs// This is the entry file. `nvs serve public/index.nvs` runs it once for each request.// The `autoload` line reads each class `Paperwork\...` from the folder `src`.autoload 'Paperwork' from '../src';
// `dispatch` finds the route for the request and calls its method.// `Paperwork\Gate` decides if the method may run, and it shows the error pages.Core\Router::dispatch(new Paperwork\Gate());<?nvsnamespace Paperwork;
use Core\Access;use Core\Audience;use Core\Http\Method;use Core\Response;use Core\Route;
// The routes of the app. Each method with a `Route` handles one kind of request.// `Core\Router::dispatch` in `public/index.nvs` calls the method of the route that matches.final class App{ // Shows a link to each document. #[Route(path: '/', method: Method::Get)] #[Access(allow: Audience::Public)] public static function home(): void { Response::sendHtml(Home::page(Report::password())); }
// Sends the invoice. #[Route(path: '/invoice.pdf', method: Method::Get)] #[Access(allow: Audience::Public)] public static function invoice(): void { App::send(Invoice::render()->bytes, 'invoice.pdf'); }
// Sends the report. A PDF viewer needs the password before it shows the report. // This app shows the password on the home page. A real app gets it from the person who requests the report. #[Route(path: '/report.pdf', method: Method::Get)] #[Access(allow: Audience::Public)] public static function report(): void { App::send(Report::render(Report::password())->bytes, 'report.pdf'); }
// Sends the tickets of one order as one file. #[Route(path: '/tickets.pdf', method: Method::Get)] #[Access(allow: Audience::Public)] public static function tickets(): void { App::send(Tickets::order(), 'tickets.pdf'); }
// Sends a PDF file. `inline` tells the browser to show the file, and `filename` is the name for a download. private static function send(tainted bytes $pdf, string $filename): void { Response::setHeader('content-disposition', "inline; filename=\"{$filename}\""); Response::sendBytes($pdf, 'application/pdf'); }}<?nvsnamespace Paperwork;
use Core\Http\Method;use Core\Str;use Core\Test;
// Tests that send requests to the app. `Test::request` runs the app without a server.final class AppTest{ #[Test] public function theHomePageLinksEachDocument(): void { var $response = Test::request(Method::Get, '/'); Test::assertEquals($response->status(), 200); Test::assertTrue(Str::contains($response->body(), "<a href=\"/invoice.pdf\">")); Test::assertTrue(Str::contains($response->body(), "<a href=\"/report.pdf\">")); Test::assertTrue(Str::contains($response->body(), "<a href=\"/tickets.pdf\">")); Test::assertTrue(Str::contains($response->body(), '<code>novis</code>')); }
#[Test] public function eachDocumentIsSentAsAPdf(): void { array<string> $names = ['invoice.pdf', 'report.pdf', 'tickets.pdf']; foreach ($names as string $name) { var $response = Test::request(Method::Get, "/{$name}"); Test::assertEquals($response->status(), 200); Test::assertEquals($response->header('content-type'), 'application/pdf'); Test::assertEquals($response->header('content-disposition'), "inline; filename=\"{$name}\""); } }
#[Test] public function anUnknownPathIsNotFound(): void { var $response = Test::request(Method::Get, '/no-such-page'); Test::assertEquals($response->status(), 404); Test::assertTrue(Str::contains($response->body(), 'There is no page at this address.')); }
#[Test] public function aWrongMethodIsNotAllowed(): void { // The documents have only `GET` routes. The `allow` header lists the methods a path has. var $response = Test::request(Method::Post, '/invoice.pdf'); Test::assertEquals($response->status(), 405); Test::assertEquals($response->header('allow'), 'GET'); Test::assertTrue(Str::contains($response->body(), 'This address only opens a document.')); }}<?nvsnamespace Paperwork;
use Core\Html\Markup;use Novis\Intl\NumberFormat;
// The look that the three documents share: the logo, the colours, the fonts and the money format.final class Brand{ // Reads the logo from the folder `assets`. `nvs.toml` allows the app to read this one file. // A relative path starts at the folder of this file, which is `src`. public static function logo(): bytes { return Core\IO::read('../assets/logo.svg') as bytes; }
// Writes an amount in euros, such as `€1,234.50`. public static function money(decimal $amount): string { return NumberFormat::currency([$amount], 'EUR', 'en')[0]; }
// Writes a whole number with a comma between thousands, such as `38,214`. public static function number(int $value): string { return NumberFormat::decimal([$value], 'en')[0]; }
// Divides two whole numbers and rounds the result to `$digits` decimals, such as `12.4`. public static function divide(int $part, int $whole, uint $digits): decimal { return Core\Decimal::divideRounded($part as decimal, $whole as decimal, $digits, Core\RoundMode::HalfUp); }
// The colours and fonts as CSS variables. Each document adds its own rules after these. public static function css(): Markup { return html`<style>:root { --ink: #1f2937; --muted: #6b7280; --line: #e3e7ee; --paper: #f5f7fa; --brand: #1d3557; --brand-soft: #e8eef6; --accent: #2a9d8f; --warm: #e76f51;}html { font-family: "Liberation Sans", sans-serif; font-size: 9.5pt; line-height: 1.45; color: var(--ink); }body { margin: 0; }h1, h2, h3 { color: var(--brand); line-height: 1.2; margin: 0; }p { margin: 0 0 6pt 0; }.muted { color: var(--muted); }.mono { font-family: "Liberation Mono", monospace; }.label { font-size: 7pt; font-weight: bold; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }</style>`; }}<?nvsnamespace Paperwork;
use Core\Decimal;use Core\RoundMode;use Core\Str;
// Draws the charts of the report as SVG images, from the numbers in the data.// The report adds each image as an asset, so the PDF contains it as a vector drawing.final class Chart{ // The size of each chart and of the area inside its axes. private static function width(): int { return 520; }
private static function height(): int { return 210; }
private static function left(): int { return 46; }
private static function right(): int { return 512; }
private static function top(): int { return 18; }
private static function bottom(): int { return 184; }
// A bar chart with one bar for each value. The last bar is dark blue, so you find the newest value quickly. public static function bars(array<Sample::Point> $points, int $max, int $step): string { string $svg = Chart::open() . Chart::grid(0, $max, $step); int $count = Core\Arr::count($points) as int; decimal $slot = Brand::divide(Chart::right() - Chart::left(), $count, 2); decimal $bar = '30' as decimal; int $index = 0; foreach ($points as Sample::Point $point) { bool $last = $index == $count - 1; decimal $x = (Chart::left() as decimal) + $slot * ($index as decimal) + Decimal::divideRounded($slot - $bar, 2, 2, RoundMode::HalfUp); decimal $y = Chart::y($point->value, 0, $max); decimal $height = (Chart::bottom() as decimal) - $y; decimal $middle = $x + Decimal::divideRounded($bar, 2, 2, RoundMode::HalfUp); string $fill = $last ? '#1d3557' : '#b9cbe0'; string $weight = $last ? '700' : '400'; string $value = Brand::number($point->value); $svg .= "<rect x=\"{$x}\" y=\"{$y}\" width=\"{$bar}\" height=\"{$height}\" rx=\"2\" fill=\"{$fill}\"/>"; $svg .= Chart::text($middle, $y - ('5' as decimal), $value, 'middle', '#1f2937', $weight); $svg .= Chart::text($middle, (Chart::bottom() + 16) as decimal, $point->name, 'middle', '#6b7280', $weight); $index++; } return $svg . '</svg>'; }
// A line chart of this year's values and last year's values. Last year's line is grey and dashed. public static function lines(array<Sample::Compare> $points, int $min, int $max, int $step): string { string $svg = Chart::open() . Chart::grid($min, $max, $step); int $count = Core\Arr::count($points) as int; decimal $gap = Brand::divide(Chart::right() - Chart::left() - 16, $count - 1, 2); array<string> $now = []; array<string> $last = []; string $dots = ''; int $index = 0; foreach ($points as Sample::Compare $point) { decimal $x = ((Chart::left() + 8) as decimal) + $gap * ($index as decimal); decimal $y = Chart::y($point->value, $min, $max); $now[] = "{$x},{$y}"; $last[] = "{$x}," . Chart::y($point->last, $min, $max); $dots .= "<circle cx=\"{$x}\" cy=\"{$y}\" r=\"2.6\" fill=\"#ffffff\" stroke=\"#2a9d8f\" stroke-width=\"1.6\"/>"; if ($index % 2 == 0) { $svg .= Chart::text($x, (Chart::bottom() + 16) as decimal, $point->name, 'middle', '#6b7280', '400'); } $index++; } $svg .= "<polyline points=\"" . Str::join($last, ' ') . "\" fill=\"none\" stroke=\"#9aa5b4\" stroke-width=\"1.5\" stroke-dasharray=\"4 3\"/>"; $svg .= "<polyline points=\"" . Str::join($now, ' ') . "\" fill=\"none\" stroke=\"#2a9d8f\" stroke-width=\"2.4\" stroke-linejoin=\"round\"/>"; $svg .= $dots; // The legend explains the two lines. $svg .= "<line x1=\"60\" y1=\"8\" x2=\"80\" y2=\"8\" stroke=\"#2a9d8f\" stroke-width=\"2.4\"/>"; $svg .= Chart::text('86' as decimal, '11' as decimal, '2026', 'start', '#1f2937', '700'); $svg .= "<line x1=\"130\" y1=\"8\" x2=\"150\" y2=\"8\" stroke=\"#9aa5b4\" stroke-width=\"1.5\" stroke-dasharray=\"4 3\"/>"; $svg .= Chart::text('156' as decimal, '11' as decimal, '2025', 'start', '#6b7280', '400'); return $svg . '</svg>'; }
private static function open(): string { int $width = Chart::width(); int $height = Chart::height(); return "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{$width}\" height=\"{$height}\" viewBox=\"0 0 {$width} {$height}\">"; }
// The horizontal lines of the chart, each with its value on the left. private static function grid(int $min, int $max, int $step): string { string $svg = ''; int $right = Chart::right(); for (int $value = $min; $value <= $max; $value = $value + $step) { decimal $y = Chart::y($value, $min, $max); string $color = $value == $min ? '#9aa5b4' : '#e3e7ee'; $svg .= "<line x1=\"" . Chart::left() . "\" y1=\"{$y}\" x2=\"{$right}\" y2=\"{$y}\" stroke=\"{$color}\" stroke-width=\"0.8\"/>"; $svg .= Chart::text((Chart::left() - 8) as decimal, $y + ('3' as decimal), Brand::number($value), 'end', '#6b7280', '400'); } return $svg; }
// The height of a value in the chart. A larger value is higher, so it has a smaller `y`. private static function y(int $value, int $min, int $max): decimal { int $span = Chart::bottom() - Chart::top(); return (Chart::bottom() as decimal) - Brand::divide(($value - $min) * $span, $max - $min, 2); }
private static function text(decimal $x, decimal $y, string $text, string $anchor, string $color, string $weight): string { return "<text x=\"{$x}\" y=\"{$y}\" text-anchor=\"{$anchor}\" font-family=\"Liberation Sans\" font-size=\"9\" font-weight=\"{$weight}\" fill=\"{$color}\">{$text}</text>"; }}<?nvsnamespace Paperwork;
use Core\Xml\Writer;
// Writes the XML of an electronic invoice in the Factur-X format, which is also called ZUGFeRD.// An accounting program reads this XML, so nobody needs to type the invoice again.final class FacturX{ // Returns the XML of the invoice, with every line and the same totals as the PDF. public static function xml(Sample::Invoice $invoice, Totals $totals): string { Writer $xml = Core\Xml::writer(); $xml->startDocument(); $xml->startElement('rsm:CrossIndustryInvoice'); $xml->writeAttribute('xmlns:rsm', 'urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'); $xml->writeAttribute('xmlns:ram', 'urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100'); $xml->writeAttribute('xmlns:udt', 'urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100');
// The profile says which rules the XML follows. EN 16931 is the European standard for invoices. $xml->startElement('rsm:ExchangedDocumentContext'); $xml->startElement('ram:GuidelineSpecifiedDocumentContextParameter'); FacturX::leaf($xml, 'ram:ID', 'urn:cen.eu:en16931:2017'); $xml->endElement(); $xml->endElement();
// Type code 380 means a commercial invoice. $xml->startElement('rsm:ExchangedDocument'); FacturX::leaf($xml, 'ram:ID', $invoice->number); FacturX::leaf($xml, 'ram:TypeCode', '380'); FacturX::date($xml, 'ram:IssueDateTime', $invoice->issued); $xml->endElement();
$xml->startElement('rsm:SupplyChainTradeTransaction'); uint $position = 0; foreach ($invoice->items as Sample::Item $item) { $position++; FacturX::line($xml, $position, $item); }
$xml->startElement('ram:ApplicableHeaderTradeAgreement'); FacturX::party($xml, 'ram:SellerTradeParty', $invoice->seller); FacturX::party($xml, 'ram:BuyerTradeParty', $invoice->buyer); $xml->startElement('ram:BuyerOrderReferencedDocument'); FacturX::leaf($xml, 'ram:IssuerAssignedID', $invoice->order); $xml->endElement(); $xml->endElement();
$xml->startElement('ram:ApplicableHeaderTradeDelivery'); $xml->startElement('ram:ActualDeliverySupplyChainEvent'); FacturX::date($xml, 'ram:OccurrenceDateTime', $invoice->delivered); $xml->endElement(); $xml->endElement();
// Type code 58 means a SEPA bank transfer. The IBAN is written without spaces. $xml->startElement('ram:ApplicableHeaderTradeSettlement'); FacturX::leaf($xml, 'ram:PaymentReference', $invoice->number); FacturX::leaf($xml, 'ram:InvoiceCurrencyCode', 'EUR'); $xml->startElement('ram:SpecifiedTradeSettlementPaymentMeans'); FacturX::leaf($xml, 'ram:TypeCode', '58'); $xml->startElement('ram:PayeePartyCreditorFinancialAccount'); FacturX::leaf($xml, 'ram:IBANID', Core\Str::replace(Sample::iban(), ' ', '')); $xml->endElement(); $xml->endElement();
$xml->startElement('ram:ApplicableTradeTax'); FacturX::leaf($xml, 'ram:CalculatedAmount', "{$totals->vat}"); FacturX::leaf($xml, 'ram:TypeCode', 'VAT'); FacturX::leaf($xml, 'ram:BasisAmount', "{$totals->net}"); FacturX::leaf($xml, 'ram:CategoryCode', 'S'); FacturX::leaf($xml, 'ram:RateApplicablePercent', Totals::rate() as string); $xml->endElement();
$xml->startElement('ram:SpecifiedTradePaymentTerms'); FacturX::leaf($xml, 'ram:Description', "Payable within {$invoice->days} days without deduction."); FacturX::date($xml, 'ram:DueDateDateTime', Invoice::due($invoice)); $xml->endElement();
$xml->startElement('ram:SpecifiedTradeSettlementHeaderMonetarySummation'); FacturX::leaf($xml, 'ram:LineTotalAmount', "{$totals->net}"); FacturX::leaf($xml, 'ram:TaxBasisTotalAmount', "{$totals->net}"); $xml->startElement('ram:TaxTotalAmount'); $xml->writeAttribute('currencyID', 'EUR'); $xml->writeText("{$totals->vat}"); $xml->endElement(); FacturX::leaf($xml, 'ram:GrandTotalAmount', "{$totals->total}"); FacturX::leaf($xml, 'ram:DuePayableAmount', "{$totals->total}"); $xml->endElement();
$xml->endElement(); $xml->endElement(); $xml->endElement(); return $xml->endDocument(); }
// Writes one line of the invoice: the product, its price, the quantity and the amount. private static function line(Writer $xml, uint $position, Sample::Item $item): void { $xml->startElement('ram:IncludedSupplyChainTradeLineItem'); $xml->startElement('ram:AssociatedDocumentLineDocument'); FacturX::leaf($xml, 'ram:LineID', "{$position}"); $xml->endElement(); $xml->startElement('ram:SpecifiedTradeProduct'); FacturX::leaf($xml, 'ram:SellerAssignedID', $item->sku); FacturX::leaf($xml, 'ram:Name', $item->name); $xml->endElement(); $xml->startElement('ram:SpecifiedLineTradeAgreement'); $xml->startElement('ram:NetPriceProductTradePrice'); FacturX::leaf($xml, 'ram:ChargeAmount', "{$item->price}"); $xml->endElement(); $xml->endElement(); $xml->startElement('ram:SpecifiedLineTradeDelivery'); $xml->startElement('ram:BilledQuantity'); $xml->writeAttribute('unitCode', FacturX::unitCode($item->unit)); $xml->writeText("{$item->quantity}"); $xml->endElement(); $xml->endElement(); $xml->startElement('ram:SpecifiedLineTradeSettlement'); $xml->startElement('ram:ApplicableTradeTax'); FacturX::leaf($xml, 'ram:TypeCode', 'VAT'); FacturX::leaf($xml, 'ram:CategoryCode', 'S'); FacturX::leaf($xml, 'ram:RateApplicablePercent', Totals::rate() as string); $xml->endElement(); $xml->startElement('ram:SpecifiedTradeSettlementLineMonetarySummation'); FacturX::leaf($xml, 'ram:LineTotalAmount', Totals::line($item) as string); $xml->endElement(); $xml->endElement(); $xml->endElement(); }
// Writes a company with its address, its email address and its VAT number. private static function party(Writer $xml, string $element, Sample::Party $party): void { $xml->startElement($element); FacturX::leaf($xml, 'ram:Name', $party->name); $xml->startElement('ram:PostalTradeAddress'); FacturX::leaf($xml, 'ram:PostcodeCode', $party->postcode); FacturX::leaf($xml, 'ram:LineOne', $party->street); FacturX::leaf($xml, 'ram:CityName', $party->city); FacturX::leaf($xml, 'ram:CountryID', $party->countryCode); $xml->endElement(); $xml->startElement('ram:URIUniversalCommunication'); $xml->startElement('ram:URIID'); $xml->writeAttribute('schemeID', 'EM'); $xml->writeText($party->email); $xml->endElement(); $xml->endElement(); $xml->startElement('ram:SpecifiedTaxRegistration'); $xml->startElement('ram:ID'); $xml->writeAttribute('schemeID', 'VA'); $xml->writeText($party->vatId); $xml->endElement(); $xml->endElement(); $xml->endElement(); }
// Writes a date in the format `102`, which is `yyyyMMdd`. private static function date(Writer $xml, string $element, Core\Time\Date $date): void { $xml->startElement($element); $xml->startElement('udt:DateTimeString'); $xml->writeAttribute('format', '102'); $xml->writeText($date->format('yyyyMMdd')); $xml->endElement(); $xml->endElement(); }
// Writes an element that has only text. private static function leaf(Writer $xml, string $element, string $text): void { $xml->startElement($element); $xml->writeText($text); $xml->endElement(); }
// Returns the code of a unit in the list UN/ECE Recommendation 20, which the standard uses. private static function unitCode(string $unit): string { return match ($unit) { 'box' => 'XBX', 'pack' => 'XPK', 'set' => 'SET', default => 'H87', }; }}<?nvsnamespace Paperwork;
use Core\Audience;use Core\Response;use Core\Router\Refusal;use Throwable;
// The gate of the app. `Core\Router::dispatch` calls it for every request.// It decides if a route method may run, and it shows the error pages.final class Gate implements Core\Router\Gate{ // Runs before each route method. The method runs only when this returns `true`. // Every route of this app is public, so this checks for `Audience::Public`. public function allows(Core\Router\Match $route): bool { return $route->accessAs<Audience>() == Audience::Public; }
// Shows a page when no route method can handle the request. // `dispatch` has already set the status code, such as 404 or 405. public function refused(Refusal $reason, ?Core\Router\Match $route): void { if ($reason == Refusal::NotFound) { Response::sendHtml(Home::notFound()); return; } string $text = match ($reason) { Refusal::MethodNotAllowed => 'This address only opens a document. Use a link on the home page.', default => 'This request is not allowed.', }; Response::sendHtml(Home::problem('Not possible', $text)); }
// Shows a page when a route method throws an error, or when the app needs too much memory or time. // The status code is 500. public function failed(?Core\Router\Match $route, ?Throwable $error): void { Response::sendHtml(Home::problem('Something went wrong', 'The document could not be made. Please try again later.')); }}<?nvsnamespace Paperwork;
use Core\Html\Markup;
// Builds the HTML pages of the app. Each `{$value}` in an `html` template is escaped.final class Home{ // The home page: one link for each document, with its address. public static function page(string $password): Markup { return Home::layout('Paperwork', html`<h1>Paperwork</h1><p>This app makes three PDF documents, the way a business needs them. Open one to see it.</p><ul class="documents"><li><a href="/invoice.pdf">Invoice</a> <code>GET /invoice.pdf</code><p>An invoice over three pages, with a QR code for the payment. It is also an electronic invoice in the Factur-X format.</p></li><li><a href="/report.pdf">Quarterly report</a> <code>GET /report.pdf</code><p>A confidential report with a table of contents and charts. The password is <code>{$password}</code>.</p></li><li><a href="/tickets.pdf">Event tickets</a> <code>GET /tickets.pdf</code><p>The tickets of one order in one file: an order summary, then one page for each person.</p></li></ul>`); }
// The page for a path that has no route. public static function notFound(): Markup { return Home::problem('Not found', 'There is no page at this address.'); }
// A page with a title, one sentence and a link to the home page. public static function problem(string $title, string $text): Markup { return Home::layout($title, html`<h1>{$title}</h1><p>{$text}</p><p><a href="/">All documents</a></p>`); }
private static function layout(string $title, Markup $content): Markup { return html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{$title}</title><style>body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1rem; color: #1f2937; line-height: 1.5; }h1 { color: #1d3557; }.documents { list-style: none; padding: 0; }.documents li { border: 1px solid #e3e7ee; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; }.documents a { font-weight: bold; color: #1d3557; }.documents p { margin: 0.4rem 0 0; color: #6b7280; }code { background: #f5f7fa; padding: 0 0.3rem; border-radius: 4px; }</style></head><body>{$content}</body></html>`; }}<?nvsnamespace Paperwork;
use Core\Html\Markup;use Core\Time\Date;use Core\Unit;use Novis\Image\QrCode;use Novis\Pdf\Document;use Novis\Pdf\Page;use Novis\Pdf\Rendered;
// An invoice with many lines. It is also an electronic invoice: the PDF contains the same invoice as XML.final class Invoice{ // Renders the sample invoice as a PDF/A-3b file with the Factur-X XML inside. public static function render(): Rendered { var $invoice = Sample::invoice(); var $totals = Totals::of($invoice->items); return Document::fromHtml(Invoice::html($invoice, $totals)) ->withAsset('logo.svg', Brand::logo()) ->withAsset('pay.svg', Invoice::giroCode($invoice, $totals) as bytes) ->withHeader(fn(Page $page): Markup => Invoice::header($invoice, $page), { height: '30mm' }) ->withFooter(fn(Page $page): Markup => Invoice::footer($invoice, $page), { height: '30mm' }) ->withSlots(fn(Page $page): array<Markup> => Invoice::slots($page)) // PDF/A-3b is the standard for archived files that may contain an XML file. ->withStandard(Document::Standard::PdfA3b) // The date of the invoice is the creation time, so the same invoice always gives the same file. ->withCreationTime(Core\Time\Instant::fromIso("{$invoice->issued->format('yyyy-MM-dd')}T09:00:00Z")) ->withInvoiceXml(FacturX::xml($invoice, $totals)) ->render(); }
// The day the invoice must be paid. public static function due(Sample::Invoice $invoice): Date { return $invoice->issued->plus($invoice->days, Unit::Day); }
// The text of a SEPA bank transfer as an SVG QR code. A banking app reads it and fills in the transfer. private static function giroCode(Sample::Invoice $invoice, Totals $totals): string { string $payment = QrCode::giroCode({ name: $invoice->seller->name, iban: Sample::iban(), amount: $totals->total, text: "Invoice {$invoice->number}", }); return QrCode::svg($payment, { margin: 0 }); }
private static function html(Sample::Invoice $invoice, Totals $totals): Markup { string $title = "Invoice {$invoice->number}"; string $issued = $invoice->issued->format('d MMMM yyyy'); string $delivered = $invoice->delivered->format('d MMMM yyyy'); string $due = Invoice::due($invoice)->format('d MMMM yyyy'); string $total = Brand::money($totals->total); string $iban = Sample::iban(); string $vatLabel = 'VAT ' . (Totals::rate() as string) . ' %'; return html`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{$title}</title><meta name="author" content="{$invoice->seller->name}"><?= Brand::css() ?><?= Invoice::css() ?></head><body><section class="parties"> <?= Invoice::address('From', $invoice->seller) ?> <?= Invoice::address('Bill to', $invoice->buyer) ?> <div class="box due"> <div class="label">Amount due</div> <p class="amount">{$total}</p> <p>Please pay by <b>{$due}</b>.</p> <p class="small">Payable within {$invoice->days} days without deduction.</p> </div></section>
<h1>{$title}</h1><p class="muted">Thank you for your order. We have delivered the following items.</p>
<table class="facts"> <tr> <td><div class="label">Invoice no.</div>{$invoice->number}</td> <td><div class="label">Invoice date</div>{$issued}</td> <td><div class="label">Delivery date</div>{$delivered}</td> <td><div class="label">Customer no.</div>{$invoice->customer}</td> <td><div class="label">Your order</div>{$invoice->order}</td> </tr></table>
<table class="items"> <thead> <tr><th class="pos">#</th><th class="sku">Article</th><th>Description</th><th class="num">Qty</th><th class="num">Unit price</th><th class="num">Amount</th></tr> <tr class="carry" data-repeat="continued"><td colspan="5">Brought forward</td><td class="num"><slot name="brought"></slot></td></tr> </thead> <tbody><?= Invoice::rows($invoice->items) ?> </tbody> <tfoot> <tr class="carry" data-repeat="continued"><td colspan="5">Carried forward</td><td class="num"><slot name="carried"></slot></td></tr> <tr class="sum first" data-repeat="last"><td colspan="5">Subtotal (net)</td><td class="num"><?= Brand::money($totals->net) ?></td></tr> <tr class="sum" data-repeat="last"><td colspan="5">{$vatLabel}</td><td class="num"><?= Brand::money($totals->vat) ?></td></tr> <tr class="grand" data-repeat="last"><td colspan="5">Total due</td><td class="num">{$total}</td></tr> </tfoot></table>
<section class="pay"> <table> <tr> <td class="code"><img src="pay.svg" alt="QR code for the bank transfer"></td> <td> <h2>Pay by bank transfer</h2> <p>Please transfer <b>{$total}</b> by <b>{$due}</b>. Scan the code with your banking app, and it fills in the transfer for you.</p> <table class="account"> <tr><th>Account holder</th><td>{$invoice->seller->name}</td></tr> <tr><th>IBAN</th><td class="mono">{$iban}</td></tr> <tr><th>Reference</th><td class="mono">Invoice {$invoice->number}</td></tr> <tr><th>Amount</th><td>{$total}</td></tr> </table> </td> </tr> </table></section><p class="thanks muted">This invoice is also an electronic invoice. Your accounting software can read the attached Factur-X file.</p></body></html>`; }
// One table row for each item. `data-mark` gives the row its amount, and the slots add these up. private static function rows(array<Sample::Item> $items): Markup { var $rows = html``; uint $position = 0; foreach ($items as Sample::Item $item) { $position++; decimal $amount = Totals::line($item); string $price = Brand::money($item->price); string $line = Brand::money($amount); $rows = $rows + html`<tr data-mark="amount:{$amount}"><td class="pos">{$position}</td><td class="sku">{$item->sku}</td><td>{$item->name}</td><td class="num">{$item->quantity} {$item->unit}</td><td class="num">{$price}</td><td class="num">{$line}</td></tr>`; } return $rows; }
private static function address(string $label, Sample::Party $party): Markup { return html`<div class="box"> <div class="label">{$label}</div> <p><b>{$party->name}</b><br>{$party->street}<br>{$party->postcode} {$party->city}<br>{$party->country}</p> <p class="muted small">VAT ID {$party->vatId}<br>{$party->email}</p> </div>`; }
// Fills the two slots of the table. `marksUpTo` returns the amounts on this page and on every page before it. private static function slots(Page $page): array<Markup> { decimal $upTo = Totals::sum($page->marksUpTo('amount')); decimal $before = $upTo - Totals::sum($page->marks('amount')); return ['carried' => Invoice::fill($upTo), 'brought' => Invoice::fill($before)]; }
// The HTML of a slot does not get the styles of the document, so it sets its own font and alignment. private static function fill(decimal $amount): Markup { string $text = Brand::money($amount); return html`<div style="font-family: 'Liberation Sans', sans-serif; font-size: 9pt; font-weight: bold; color: #1d3557; text-align: right; line-height: 1.45">{$text}</div>`; }
// The header shows the logo on every page. Page 1 has the word "Invoice", and the other pages have the number. private static function header(Sample::Invoice $invoice, Page $page): Markup { string $right = $page->isFirst() ? 'Invoice' : "Invoice {$invoice->number}, continued"; return html`<div style="font-family: 'Liberation Sans', sans-serif; display: flex; justify-content: space-between; align-items: flex-end; padding-top: 12mm"><img src="logo.svg" alt="Shop" style="height: 10mm"><div style="font-size: 8.5pt; letter-spacing: 0.14em; text-transform: uppercase; color: #6b7280; padding-bottom: 1mm; white-space: nowrap">{$right}</div></div>`; }
// The footer has the legal and bank details of the shop, and the page number. private static function footer(Sample::Invoice $invoice, Page $page): Markup { var $shop = $invoice->seller; string $iban = Sample::iban(); return html`<div style="font-family: 'Liberation Sans', sans-serif; font-size: 6.8pt; line-height: 1.55; color: #6b7280; margin-top: 6mm; padding-top: 3mm; border-top: 0.75pt solid #e3e7ee; display: flex; justify-content: space-between; white-space: nowrap"><div><b style="color: #1d3557">{$shop->name}</b><br>{$shop->street}<br>{$shop->postcode} {$shop->city}, {$shop->country}</div><div>Phone +49 30 1234 5678<br>{$shop->email}<br>www.example.com</div><div>Example Bank<br>IBAN {$iban}<br>VAT ID {$shop->vatId}</div><div>Managing director: Ada Lovelace<br>Local court of Berlin<br>HRB 123456</div><div style="text-align: right; color: #1d3557; font-weight: bold">Page {$page->number} of {$page->count}</div></div>`; }
private static function css(): Markup { return html`<style>@page { size: A4; margin: 0 18mm; }.small { font-size: 8pt; }.parties { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 9pt; margin: 7mm 0 8mm 0; }.box { border: 0.75pt solid var(--line); border-radius: 5pt; padding: 9pt 11pt 4pt 11pt; background: var(--paper); }.box .label { margin-bottom: 5pt; }.box p { margin-bottom: 5pt; }.box.due { background: var(--brand); border-color: var(--brand); color: #ffffff; }.box.due .label { color: #a8c5e2; }.box.due .amount { font-size: 19pt; font-weight: bold; margin: 2pt 0 6pt 0; }.box.due .small { color: #c9d8ea; }h1 { font-size: 19pt; margin-bottom: 3pt; }table.facts { width: 100%; border-collapse: collapse; margin: 5mm 0 6mm 0; border-top: 0.75pt solid var(--line); border-bottom: 0.75pt solid var(--line); }.facts td { padding: 6pt 8pt 6pt 0; font-weight: bold; color: var(--brand); }.facts .label { margin-bottom: 2pt; }table.items { width: 100%; border-collapse: collapse; }.items th { background: var(--brand); color: #ffffff; font-size: 7pt; font-weight: bold; letter-spacing: 0.06em; text-transform: uppercase; text-align: left; padding: 6pt 6pt; }.items td { padding: 5pt 6pt; border-bottom: 0.5pt solid var(--line); vertical-align: top; }.items tbody tr:nth-child(even) td { background: #f6f8fb; }.items .pos { color: var(--muted); }.items td.sku { font-family: "Liberation Mono", monospace; font-size: 7.5pt; color: var(--muted); padding-top: 5.5pt; }.num { text-align: right; white-space: nowrap; }.items th.num { text-align: right; }.account td.mono { font-weight: normal; color: var(--brand); }.items tr.carry td { background: var(--brand-soft); color: var(--brand); font-weight: bold; border-bottom: none; }.items tr.sum td { border-bottom: none; padding: 3pt 6pt; }.items tr.sum.first td { padding-top: 9pt; }.items tr.grand td { background: var(--brand); color: #ffffff; font-size: 11pt; font-weight: bold; padding: 7pt 6pt; }.pay { margin-top: 9mm; padding: 12pt; border: 1pt solid var(--accent); border-radius: 6pt; break-inside: avoid; }.pay > table { width: 100%; border-collapse: collapse; table-layout: fixed; }.pay td { vertical-align: top; }.pay td.code { width: 36mm; }.pay img { width: 31mm; height: 31mm; }.pay h2 { font-size: 12pt; margin-bottom: 5pt; }table.account { border-collapse: collapse; margin-top: 4pt; }.account th { text-align: left; font-weight: normal; color: var(--muted); padding: 1pt 12pt 1pt 0; }.account td { padding: 1pt 0; font-weight: bold; }.thanks { margin-top: 6mm; font-size: 8pt; }</style>`; }}<?nvsnamespace Paperwork;
use Core\Arr;use Core\Str;use Core\Test;use Novis\Pdf\Reader;
// Tests for the invoice. `Reader` opens the finished PDF file and reads its pages and its XML.final class InvoiceTest{ #[Test] public function theTotalsAddUp(): void { var $totals = Totals::of(Sample::invoice()->items); Test::assertSame($totals->net as string, '5142.45'); Test::assertSame($totals->vat as string, '977.07'); Test::assertSame($totals->total as string, '6119.52'); }
#[Test] public function theLastPageShowsTheTotal(): void { var $reader = Reader::open(Invoice::render()->bytes); Test::assertTrue($reader->pageCount >= 3); Test::assertTrue(Str::contains($reader->text($reader->pageCount), 'Total due')); Test::assertTrue(Str::contains($reader->text($reader->pageCount), '€6,119.52')); }
#[Test] public function theCarriedForwardAmountIsOnPageOne(): void { var $reader = Reader::open(Invoice::render()->bytes); Test::assertTrue(Str::contains($reader->text(1), 'Carried forward')); Test::assertTrue(Str::contains($reader->text(2), 'Brought forward')); }
#[Test] public function theXmlHasTheSameNumberAndTotal(): void { ?tainted string $xml = Reader::open(Invoice::render()->bytes)->invoiceXml(); Test::assertTrue($xml != null); tainted string $text = $xml ?? ''; Test::assertTrue(Str::contains($text, '<ram:ID>2026-1042</ram:ID>')); Test::assertTrue(Str::contains($text, '<ram:GrandTotalAmount>6119.52</ram:GrandTotalAmount>')); Test::assertTrue(Str::contains($text, '<ram:DuePayableAmount>6119.52</ram:DuePayableAmount>')); }
#[Test] public function nothingIsDroppedOrCutOff(): void { var $rendered = Invoice::render(); Test::assertCount($rendered->dropped, 0); Test::assertCount($rendered->missingGlyphs, 0); Test::assertCount($rendered->overflows, 0); }
#[Test] public function twoRendersGiveTheSameFile(): void { Test::assertTrue(Invoice::render()->bytes == Invoice::render()->bytes); Test::assertTrue(Arr::count(Sample::invoice()->items) > 40); }}<?nvsnamespace Paperwork;
use Core\Html\Markup;use Novis\Pdf\Document;use Novis\Pdf\Page;use Novis\Pdf\Rendered;
// A confidential quarterly report with a cover, a table of contents, charts and tables.final class Report{ // The password of the report. The home page shows it, so you can open the file. public static function password(): string { return 'novis'; }
// Renders the report. With a password, the file is encrypted, and a PDF viewer needs the password to open it. public static function render(?string $password): Rendered { var $document = Document::fromHtml(Report::html()) ->withAsset('logo.svg', Brand::logo()) ->withAsset('revenue.svg', Chart::bars(Sample::quarters(), 6000, 1000) as bytes) ->withAsset('orders.svg', Chart::lines(Sample::weeks(), 2000, 3600, 400) as bytes) ->withHeader(fn(Page $page): Markup => Report::header($page), { height: '22mm' }) ->withFooter(fn(Page $page): Markup => Report::footer($page), { height: '20mm' }) // PDF/UA is the standard for accessible files. A screen reader can read this report aloud. ->withStandard(Document::Standard::PdfUa1) ->withCreationTime(Core\Time\Instant::fromIso(Sample::reportDate()->format('yyyy-MM-dd') . 'T16:00:00Z')); if ($password != null) { $document = $document->withPassword($password); } return $document->render(); }
// The header shows the name of the chapter. The chapter heading saves its text with `string-set`. // The cover is on the page named `cover`, and it has no header. private static function header(Page $page): Markup { if ($page->name == 'cover') { return html``; } string $chapter = $page->string('chapter') ?? ''; return html`<div style="font-family: 'Liberation Sans', sans-serif; font-size: 7.5pt; color: #6b7280; display: flex; justify-content: space-between; padding-top: 11mm; padding-bottom: 2mm; border-bottom: 0.75pt solid #e3e7ee"><div><b style="color: #1d3557">Shop GmbH</b> · Quarterly report Q3 2026</div><div style="color: #1d3557; font-weight: bold">{$chapter}</div></div>`; }
// The footer says that the report is confidential, and gives the page number. private static function footer(Page $page): Markup { if ($page->name == 'cover') { return html``; } return html`<div style="font-family: 'Liberation Sans', sans-serif; font-size: 7.5pt; color: #6b7280; display: flex; justify-content: space-between; padding-top: 6mm"><div><b style="color: #e76f51; letter-spacing: 0.08em">CONFIDENTIAL</b> · Page {$page->number} of {$page->count}</div><div>For the board of Shop GmbH only</div></div>`; }
private static function html(): Markup { string $written = Sample::reportDate()->format('d MMMM yyyy'); return html`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Quarterly report Q3 2026</title><meta name="author" content="Shop GmbH"><meta name="description" content="Revenue, orders, regions and products of Shop GmbH in the third quarter of 2026."><?= Brand::css() ?><?= Report::css() ?></head><body>
<section class="cover"> <div class="band"> <p class="pill">Confidential</p> <h1>Quarterly report</h1> <p class="quarter">Third quarter 2026</p> <p class="period">1 July to 30 September 2026</p> </div> <div class="cover-body"> <img src="logo.svg" alt="Shop"> <p><b>Prepared for the board of Shop GmbH</b><br>Written on {$written} by Ada Lovelace, managing director</p> <p class="muted">This report contains figures that are not public. Please do not forward it.</p> </div></section>
<section class="contents"> <h2>Contents</h2> <ol class="toc"> <li><a href="#summary">Summary of the quarter</a></li> <li><a href="#revenue">Revenue and orders</a></li> <li><a href="#regions">Revenue by region</a></li> <li><a href="#products">Products</a></li> <li><a href="#outlook">Outlook for the fourth quarter</a></li> </ol></section>
<section class="chapter"> <p class="eyebrow">Chapter 1</p> <h2 id="summary">Summary of the quarter</h2> <p class="lead">The third quarter was the best third quarter in the history of the shop. Revenue grew by 12.4 % to €4.82 million, and the gross margin rose to 41.3 %.</p> <div class="kpis"><?= Report::kpis() ?> </div> <h3>What went well</h3> <ul> <li>September was the strongest month of the year. Offices restocked after the summer, and paper and toner sold well.</li> <li>Technology products such as headsets and USB-C hubs grew by 27 %. They have a higher margin than paper.</li> <li>2,940 companies ordered for the first time. Most of them came through the new price comparison listings.</li> </ul> <h3>What needs attention</h3> <ul> <li>Delivery times in Italy and Spain were 1.4 days longer than our target of 3 days.</li> <li>The price of copy paper rose by 6 % in August. We passed on only half of it to customers.</li> </ul></section>
<section class="chapter"> <p class="eyebrow">Chapter 2</p> <h2 id="revenue">Revenue and orders</h2> <p>Revenue grows every year in the third quarter, because offices buy supplies after the summer holidays. This year the growth was larger than in 2025.</p> <div class="chart"> <p class="caption">Revenue per quarter, in thousand euros</p> <img src="revenue.svg" alt="Bar chart of the revenue in the last eight quarters. It rose from 4,290 thousand euros in Q3 2025 to 4,820 thousand euros in Q3 2026."> </div> <table class="data"> <thead><tr><th>Month</th><th class="num">2026</th><th class="num">2025</th><th class="num">Change</th></tr></thead> <tbody><?= Report::compareRows(Sample::months(), false) ?> </tbody> </table> <div class="chart"> <p class="caption">Orders per week, in 2026 and in 2025</p> <img src="orders.svg" alt="Line chart of the orders in each week of the quarter. Every week had more orders than the same week in 2025."> </div></section>
<section class="chapter"> <p class="eyebrow">Chapter 3</p> <h2 id="regions">Revenue by region</h2> <p>Germany is still half of the revenue. Poland and Spain grew the fastest, from a small base. Only the countries outside Europe sold less than last year.</p> <table class="data"> <thead><tr><th>Region</th><th class="num">Revenue</th><th>Share</th><th class="num">Last year</th><th class="num">Change</th></tr></thead> <tbody><?= Report::compareRows(Sample::regions(), true) ?> </tbody> </table> <p class="note muted">All amounts are in thousand euros. The share is the part of the total revenue of the quarter.</p></section>
<section class="chapter"> <p class="eyebrow">Chapter 4</p> <h2 id="products">Products</h2> <p>The table lists the products with the most revenue. The margin is the part of the revenue that is left after the cost of buying the product.</p> <table class="data products"> <thead><tr><th class="num">#</th><th>Product</th><th>Line</th><th class="num">Units</th><th class="num">Revenue</th><th class="num">Margin</th></tr></thead> <tbody><?= Report::productRows() ?> </tbody> </table></section>
<section class="chapter"> <p class="eyebrow">Chapter 5</p> <h2 id="outlook">Outlook for the fourth quarter</h2> <p class="lead">We expect revenue of €5.3 to €5.5 million in the fourth quarter. This is 4 % to 8 % more than in the fourth quarter of 2025.</p> <div class="columns"> <div class="panel"> <h3>Our plans</h3> <ul> <li>Open a second warehouse near Vienna in November, so orders from Austria arrive one day sooner.</li> <li>Add 120 technology products to the range before the end of the year.</li> <li>Offer a yearly contract with fixed prices for paper to our 500 largest customers.</li> </ul> </div> <div class="panel warn"> <h3>Risks</h3> <ul> <li>The price of paper may rise again in the winter.</li> <li>A strike at a parcel company could delay deliveries before Christmas.</li> <li>Many companies plan their budgets for next year with less money for offices.</li> </ul> </div> </div> <p class="sign">Ada Lovelace<br><span class="muted">Managing director, Shop GmbH</span></p></section></body></html>`; }
// One tile for each key figure. The tiles are in a CSS grid with three columns. private static function kpis(): Markup { var $tiles = html``; foreach (Sample::kpis() as Sample::Kpi $kpi) { $tiles = $tiles + html`<div class="kpi"><div class="label">{$kpi->label}</div><div class="value">{$kpi->value}</div><div class="change">{$kpi->change}</div><div class="note">{$kpi->note}</div></div>`; } return $tiles; }
// One row for each month or region, with the change to last year. The last row is the total. private static function compareRows(array<Sample::Compare> $rows, bool $withShare): Markup { int $total = 0; int $totalLast = 0; foreach ($rows as Sample::Compare $row) { $total = $total + $row->value; $totalLast = $totalLast + $row->last; } var $html = html``; foreach ($rows as Sample::Compare $row) { $html = $html + Report::compareRow($row->name, $row->value, $row->last, $withShare ? $total : 0, ''); } return $html + Report::compareRow('Total', $total, $totalLast, $withShare ? $total : 0, 'total'); }
private static function compareRow(string $name, int $value, int $last, int $total, string $class): Markup { string $now = Brand::number($value); string $before = Brand::number($last); string $change = Report::change($value, $last); string $direction = $value >= $last ? 'up' : 'down'; if ($total == 0) { return html`<tr class="{$class}"><td>{$name}</td><td class="num">{$now}</td><td class="num">{$before}</td><td class="num {$direction}">{$change}</td></tr>`; } // The bar in the share column is as wide as the share of this row. decimal $share = Brand::divide($value * 100, $total, 1); string $width = "width: {$share}%"; return html`<tr class="{$class}"><td>{$name}</td><td class="num">{$now}</td><td class="share"><div class="track"><div class="fill" style="{$width}"></div></div>{$share} %</td><td class="num">{$before}</td><td class="num {$direction}">{$change}</td></tr>`; }
// The change from last year in percent, with one decimal, such as `+12.4 %`. private static function change(int $value, int $last): string { int $difference = $value >= $last ? $value - $last : $last - $value; decimal $percent = Brand::divide($difference * 100, $last, 1); string $sign = $value >= $last ? '+' : '−'; return "{$sign}{$percent} %"; }
private static function productRows(): Markup { var $html = html``; int $position = 0; foreach (Sample::products() as Sample::Product $product) { $position++; string $units = Brand::number($product->units); string $revenue = '€' . Brand::number($product->revenue); $html = $html + html`<tr><td class="num muted">{$position}</td><td>{$product->name}</td><td class="muted">{$product->line}</td><td class="num">{$units}</td><td class="num">{$revenue}</td><td class="num">{$product->margin} %</td></tr>`; } return $html; }
private static function css(): Markup { return html`<style>@page { size: A4; margin: 0 20mm; }@page cover { margin: 0; }body { font-size: 9.5pt; }h2 { font-size: 20pt; margin-bottom: 8pt; string-set: chapter content(text); }h3 { font-size: 11pt; margin: 14pt 0 5pt 0; }ul { margin: 0 0 6pt 0; padding-left: 14pt; }li { margin-bottom: 3pt; }.lead { font-size: 11pt; line-height: 1.5; color: #374151; margin-bottom: 12pt; }
.cover { page: cover; break-after: page; }.band { height: 165mm; padding: 38mm 22mm 0 22mm; background-image: linear-gradient(135deg, #1d3557 0%, #23577a 55%, #2a9d8f 100%); color: #ffffff; }.band h1 { color: #ffffff; font-family: "Liberation Serif", serif; font-size: 44pt; font-weight: normal; margin: 14mm 0 4mm 0; }.pill { display: inline; border: 1pt solid #ffffff; border-radius: 10pt; padding: 3pt 10pt; font-size: 8pt; font-weight: bold; letter-spacing: 0.18em; text-transform: uppercase; }.quarter { font-size: 18pt; margin-bottom: 2mm; }.period { font-size: 11pt; color: #cfe3ee; }.cover-body { padding: 16mm 22mm 0 22mm; font-size: 10pt; }.cover-body img { height: 13mm; margin-bottom: 10mm; }
.contents { break-after: page; padding-top: 10mm; }.contents h2 { margin-bottom: 10mm; }ol.toc { list-style: none; padding: 0; margin: 0; }.toc li { font-size: 12pt; margin: 0; padding: 7pt 0; border-bottom: 0.75pt solid var(--line); }.toc a { color: var(--brand); text-decoration: none; }.toc a::after { content: leader('.') target-counter(attr(href), page); color: var(--muted); }
.chapter { break-before: page; padding-top: 6mm; }.contents + .chapter { break-before: auto; }.eyebrow { font-size: 8pt; font-weight: bold; letter-spacing: 0.14em; text-transform: uppercase; color: var(--accent); margin-bottom: 3pt; }
.kpis { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 9pt; margin: 6pt 0 8pt 0; }.kpi { border-radius: 6pt; padding: 10pt 12pt; background: var(--paper); border-top: 3pt solid var(--accent); }.kpi .value { font-size: 19pt; font-weight: bold; color: var(--brand); margin: 3pt 0 2pt 0; }.kpi .change { font-weight: bold; color: var(--accent); }.kpi .note { font-size: 7.5pt; color: var(--muted); }
.chart { margin: 10pt 0 12pt 0; padding: 10pt 12pt 6pt 12pt; border: 0.75pt solid var(--line); border-radius: 6pt; break-inside: avoid; }.chart img { width: 100%; }.caption { font-size: 8pt; font-weight: bold; letter-spacing: 0.06em; text-transform: uppercase; color: var(--brand); margin-bottom: 6pt; }
table.data { width: 100%; border-collapse: collapse; margin: 6pt 0 10pt 0; }.data th { text-align: left; font-size: 7.5pt; font-weight: bold; letter-spacing: 0.06em; text-transform: uppercase; color: var(--brand); padding: 6pt 6pt; border-bottom: 1.5pt solid var(--brand); }.data td { padding: 4.5pt 6pt; border-bottom: 0.5pt solid var(--line); }.data tbody tr:nth-child(even) td { background: var(--paper); }.data tr.total td { font-weight: bold; color: var(--brand); border-top: 1pt solid var(--brand); border-bottom: none; background: #ffffff; }.num { text-align: right; white-space: nowrap; }.up { color: #1f7a6f; }.down { color: #c2410c; }.data th.num { text-align: right; }td.share { font-size: 8pt; color: var(--muted); white-space: nowrap; }.track { width: 34mm; height: 5pt; background: #e3e7ee; border-radius: 3pt; margin: 2pt 0 2pt 0; }.fill { height: 5pt; background: var(--accent); border-radius: 3pt; }.note { font-size: 8pt; }
.columns { display: grid; grid-template-columns: 1fr 1fr; gap: 10pt; margin-top: 6pt; }.panel { background: var(--paper); border-radius: 6pt; padding: 4pt 12pt 6pt 12pt; border-left: 3pt solid var(--accent); }.panel.warn { border-left-color: var(--warm); }.sign { margin-top: 14mm; font-family: "Liberation Serif", serif; font-size: 12pt; }</style>`; }}<?nvsnamespace Paperwork;
use Core\Str;use Core\Test;use Novis\Pdf\Reader;use ParseError;
// Tests for the report. `Reader` cannot open an encrypted file, so most tests render the report without a password.final class ReportTest{ #[Test] public function theEncryptedReportCannotBeReadWithoutThePassword(): void { bytes $pdf = Report::render(Report::password())->bytes; Test::assertThrows(fn(): void => { Reader::open($pdf); }, ParseError::class); }
#[Test] public function theContentsGiveThePageOfEachChapter(): void { tainted string $contents = Reader::open(Report::render(null)->bytes)->text(2); Test::assertTrue(Str::contains($contents, 'Summary of the quarter 3')); Test::assertTrue(Str::contains($contents, 'Revenue and orders 4')); Test::assertTrue(Str::contains($contents, 'Revenue by region 5')); Test::assertTrue(Str::contains($contents, 'Products 6')); Test::assertTrue(Str::contains($contents, 'Outlook for the fourth quarter 8')); }
#[Test] public function theHeaderShowsTheChapter(): void { // Page 7 is the second page of the chapter "Products". Its header still shows that chapter. tainted string $page = Reader::open(Report::render(null)->bytes)->text(7); Test::assertTrue(Str::contains($page, 'Quarterly report Q3 2026')); Test::assertTrue(Str::contains($page, 'Products')); Test::assertTrue(Str::contains($page, 'Page 7 of 8')); }
#[Test] public function theLongTableRepeatsItsHeader(): void { var $reader = Reader::open(Report::render(null)->bytes); Test::assertTrue(Str::contains($reader->text(6), 'UNITS')); Test::assertTrue(Str::contains($reader->text(7), 'UNITS')); }
#[Test] public function nothingIsDroppedOrCutOff(): void { var $rendered = Report::render(Report::password()); Test::assertEquals($rendered->pageCount, 8); Test::assertCount($rendered->dropped, 0); Test::assertCount($rendered->missingGlyphs, 0); Test::assertCount($rendered->overflows, 0); }}<?nvsnamespace Paperwork;
use Core\Time\Date;
// The data that the three documents show. A real app reads it from its database.final class Sample{ type Party = { name: string, street: string, postcode: string, city: string, country: string, countryCode: string, vatId: string, email: string }; type Item = { sku: string, name: string, quantity: uint, unit: string, price: decimal }; type Invoice = { number: string, customer: string, order: string, issued: Date, delivered: Date, days: int, seller: Party, buyer: Party, items: array<Item> }; type Kpi = { label: string, value: string, change: string, note: string }; type Point = { name: string, value: int }; type Compare = { name: string, value: int, last: int }; type Product = { line: string, name: string, units: int, revenue: int, margin: int }; type Attendee = { name: string, ticket: string, id: string, zone: string, seat: string, days: string, price: decimal }; type Event = { name: string, tagline: string, venue: string, address: string, dates: string, doors: string, site: string }; type Order = { number: string, placed: Date, buyer: Party, attendees: array<Attendee> };
// The company that sends the invoice and writes the report. public static function shop(): Party { return { name: 'Shop GmbH', street: '12 Example Street', postcode: '10115', city: 'Berlin', country: 'Germany', countryCode: 'DE', vatId: 'DE123456789', email: 'billing@example.com' }; }
// The bank account of the shop. This is the standard test IBAN, and its check digits are valid. public static function iban(): string { return 'DE89 3704 0044 0532 0130 00'; }
// An invoice with many lines, so that it needs three pages. public static function invoice(): Invoice { Party $buyer = { name: 'Framework GmbH', street: '48 Example Street', postcode: '80331', city: 'Munich', country: 'Germany', countryCode: 'DE', vatId: 'DE987654321', email: 'accounts@example.com' }; array<Item> $items = [ { sku: 'PAP-A4-80', name: 'Copy paper A4, 80 g/m², 500 sheets', quantity: 40, unit: 'pack', price: '4.95' as decimal }, { sku: 'PAP-A4-120', name: 'Presentation paper A4, 120 g/m², 250 sheets', quantity: 6, unit: 'pack', price: '11.40' as decimal }, { sku: 'PAP-A3-80', name: 'Copy paper A3, 80 g/m², 500 sheets', quantity: 4, unit: 'pack', price: '10.90' as decimal }, { sku: 'ENV-C4-SK', name: 'Envelopes C4, self-seal, white', quantity: 3, unit: 'box', price: '18.75' as decimal }, { sku: 'ENV-DL-WIN', name: 'Envelopes DL with window, 1000 pieces', quantity: 2, unit: 'box', price: '24.90' as decimal }, { sku: 'LBL-70X37', name: 'Address labels 70 × 37 mm, 2400 labels', quantity: 5, unit: 'pack', price: '16.20' as decimal }, { sku: 'PEN-GEL-BL', name: 'Gel pens, blue, 0.5 mm', quantity: 12, unit: 'box', price: '8.60' as decimal }, { sku: 'PEN-GEL-BK', name: 'Gel pens, black, 0.5 mm', quantity: 8, unit: 'box', price: '8.60' as decimal }, { sku: 'PEN-FIN-04', name: 'Fineliners, 10 colours', quantity: 10, unit: 'set', price: '9.80' as decimal }, { sku: 'MRK-WB-4', name: 'Whiteboard markers, 4 colours', quantity: 15, unit: 'set', price: '6.45' as decimal }, { sku: 'MRK-HL-6', name: 'Highlighters, 6 colours', quantity: 10, unit: 'set', price: '5.90' as decimal }, { sku: 'PCL-HB-12', name: 'Pencils HB with eraser', quantity: 6, unit: 'box', price: '3.80' as decimal }, { sku: 'NTB-A5-DOT', name: 'Notebook A5, dotted, 192 pages', quantity: 30, unit: 'pc', price: '7.95' as decimal }, { sku: 'NTB-A4-RUL', name: 'Notebook A4, ruled, 96 pages', quantity: 20, unit: 'pc', price: '4.40' as decimal }, { sku: 'PAD-STK-76', name: 'Sticky notes 76 × 76 mm, 12 pads', quantity: 10, unit: 'pack', price: '9.20' as decimal }, { sku: 'PAD-FLIP', name: 'Flip chart pads, plain, 20 sheets', quantity: 6, unit: 'pack', price: '21.50' as decimal }, { sku: 'FLD-LVR-80', name: 'Lever arch files, 80 mm, blue', quantity: 25, unit: 'pc', price: '3.65' as decimal }, { sku: 'FLD-PKT-A4', name: 'Clear pockets A4, 100 pieces', quantity: 8, unit: 'pack', price: '6.30' as decimal }, { sku: 'FLD-DIV-12', name: 'Dividers A4, 12 tabs', quantity: 15, unit: 'set', price: '2.85' as decimal }, { sku: 'STP-24-6', name: 'Stapler for 30 sheets', quantity: 6, unit: 'pc', price: '12.90' as decimal }, { sku: 'STP-PIN-24', name: 'Staples 24/6, 5000 pieces', quantity: 10, unit: 'box', price: '1.95' as decimal }, { sku: 'PUN-2H-40', name: 'Two-hole punch for 40 sheets', quantity: 3, unit: 'pc', price: '18.40' as decimal }, { sku: 'CLP-BIN-25', name: 'Binder clips 25 mm, 12 pieces', quantity: 12, unit: 'box', price: '2.40' as decimal }, { sku: 'TAP-CLR-19', name: 'Clear tape 19 mm × 33 m, 8 rolls', quantity: 6, unit: 'pack', price: '7.10' as decimal }, { sku: 'TAP-DSP', name: 'Tape dispenser, weighted', quantity: 4, unit: 'pc', price: '11.25' as decimal }, { sku: 'SCI-21', name: 'Scissors 21 cm, soft grip', quantity: 8, unit: 'pc', price: '4.70' as decimal }, { sku: 'CUT-SNAP-18', name: 'Snap-off cutter 18 mm', quantity: 5, unit: 'pc', price: '3.95' as decimal }, { sku: 'RUL-ALU-30', name: 'Aluminium ruler 30 cm', quantity: 10, unit: 'pc', price: '2.95' as decimal }, { sku: 'CAL-DSK-12', name: 'Desk calculator, 12 digits, solar', quantity: 4, unit: 'pc', price: '14.90' as decimal }, { sku: 'TRY-LTR-3', name: 'Letter trays, stackable, 3 pieces', quantity: 6, unit: 'set', price: '15.60' as decimal }, { sku: 'ORG-DSK', name: 'Desk organiser, black mesh', quantity: 6, unit: 'pc', price: '13.40' as decimal }, { sku: 'WBD-120', name: 'Magnetic whiteboard 120 × 90 cm', quantity: 2, unit: 'pc', price: '119.00' as decimal }, { sku: 'WBD-ERS', name: 'Whiteboard eraser, magnetic', quantity: 4, unit: 'pc', price: '4.20' as decimal }, { sku: 'MAG-BTN-20', name: 'Whiteboard magnets, 20 pieces', quantity: 4, unit: 'pack', price: '5.80' as decimal }, { sku: 'CBL-USBC-2', name: 'USB-C cable, 2 m, braided', quantity: 15, unit: 'pc', price: '9.90' as decimal }, { sku: 'HUB-USBC-7', name: 'USB-C hub with 7 ports', quantity: 6, unit: 'pc', price: '39.00' as decimal }, { sku: 'MSE-WL', name: 'Wireless mouse, silent click', quantity: 10, unit: 'pc', price: '22.50' as decimal }, { sku: 'KBD-WL-DE', name: 'Wireless keyboard, German layout', quantity: 6, unit: 'pc', price: '34.90' as decimal }, { sku: 'STD-LAP', name: 'Laptop stand, aluminium', quantity: 6, unit: 'pc', price: '29.00' as decimal }, { sku: 'HDS-USB', name: 'USB headset with microphone', quantity: 8, unit: 'pc', price: '44.50' as decimal }, { sku: 'LMP-LED', name: 'LED desk lamp, dimmable', quantity: 4, unit: 'pc', price: '36.80' as decimal }, { sku: 'BAT-AA-24', name: 'Batteries AA, 24 pieces', quantity: 3, unit: 'pack', price: '11.90' as decimal }, { sku: 'TON-K-2', name: 'Toner cartridge, black, 3000 pages', quantity: 4, unit: 'pc', price: '64.00' as decimal }, { sku: 'TON-C-1', name: 'Toner cartridge, cyan, 2300 pages', quantity: 2, unit: 'pc', price: '71.50' as decimal }, { sku: 'TON-M-1', name: 'Toner cartridge, magenta, 2300 pages', quantity: 2, unit: 'pc', price: '71.50' as decimal }, { sku: 'TON-Y-1', name: 'Toner cartridge, yellow, 2300 pages', quantity: 2, unit: 'pc', price: '71.50' as decimal }, { sku: 'CLN-WIPE', name: 'Screen cleaning wipes, 100 pieces', quantity: 6, unit: 'pack', price: '6.90' as decimal }, { sku: 'BOX-ARCH', name: 'Archive boxes, 10 pieces', quantity: 5, unit: 'pack', price: '17.80' as decimal }, { sku: 'BAG-SHRED', name: 'Shredder bags, 50 pieces', quantity: 2, unit: 'pack', price: '12.60' as decimal }, { sku: 'COF-BEAN-1', name: 'Coffee beans, 1 kg, fair trade', quantity: 8, unit: 'pack', price: '18.90' as decimal }, { sku: 'TEA-ASS-50', name: 'Tea selection, 50 bags', quantity: 6, unit: 'box', price: '7.40' as decimal }, { sku: 'CUP-PAP-50', name: 'Paper cups, 50 pieces', quantity: 10, unit: 'pack', price: '3.20' as decimal }, ]; return { number: '2026-1042', customer: 'C-20417', order: 'PO-7731', issued: Date::at(2026, 10, 1), delivered: Date::at(2026, 9, 29), days: 14, seller: Sample::shop(), buyer: $buyer, items: $items, }; }
// The conference that the tickets are for. public static function event(): Event { return { name: 'Framework Conf 2026', tagline: 'Two days of talks about software that lasts', venue: 'Example Hall', address: '1 Example Street, 10115 Berlin', dates: '12 and 13 November 2026', doors: 'Doors open at 08:30. The first talk starts at 09:30.', site: 'conf.example.com', }; }
// An order of four tickets. One company bought them for four people. public static function order(): Order { Party $buyer = { name: 'Blog GmbH', street: '7 Example Street', postcode: '20095', city: 'Hamburg', country: 'Germany', countryCode: 'DE', vatId: 'DE246813579', email: 'team@example.com' }; return { number: 'FWC-2026-0417', placed: Date::at(2026, 10, 2), buyer: $buyer, attendees: [ { name: 'Ada Lovelace', ticket: 'Conference pass', id: 'FWC26-7K3Q-0412', zone: 'Hall A', seat: 'Row 4, seat 12', days: '12 and 13 November', price: '489.00' as decimal }, { name: 'Grace Hopper', ticket: 'Conference pass and workshop', id: 'FWC26-M2XD-0413', zone: 'Hall A', seat: 'Row 4, seat 13', days: '11 to 13 November', price: '689.00' as decimal }, { name: 'Alan Turing', ticket: 'Conference pass', id: 'FWC26-R8NB-0414', zone: 'Hall A', seat: 'Row 4, seat 14', days: '12 and 13 November', price: '489.00' as decimal }, { name: 'Katherine Johnson', ticket: 'Day pass', id: 'FWC26-T5WE-0415', zone: 'Hall B', seat: 'Free seating', days: '12 November', price: '279.00' as decimal }, ], }; }
// The day the quarterly report was written. public static function reportDate(): Date { return Date::at(2026, 10, 9); }
// The key figures of the quarter, for the tiles on the first page of the report. public static function kpis(): array<Kpi> { return [ { label: 'Revenue', value: '€4.82m', change: '+12.4 %', note: 'Q3 2025: €4.29m' }, { label: 'Orders', value: '38,214', change: '+9.1 %', note: 'Q3 2025: 35,028' }, { label: 'Average order', value: '€126.13', change: '+3.0 %', note: 'Q3 2025: €122.47' }, { label: 'Gross margin', value: '41.3 %', change: '+1.2 points', note: 'Q3 2025: 40.1 %' }, { label: 'New customers', value: '2,940', change: '+18.6 %', note: 'Q3 2025: 2,479' }, { label: 'Return rate', value: '3.1 %', change: '−0.4 points', note: 'Q3 2025: 3.5 %' }, ]; }
// The revenue of the last eight quarters, in thousand euros. public static function quarters(): array<Point> { return [ { name: 'Q4 24', value: 3980 }, { name: 'Q1 25', value: 3410 }, { name: 'Q2 25', value: 3720 }, { name: 'Q3 25', value: 4290 }, { name: 'Q4 25', value: 5110 }, { name: 'Q1 26', value: 3860 }, { name: 'Q2 26', value: 4150 }, { name: 'Q3 26', value: 4820 }, ]; }
// The revenue of each month of the quarter and of the same month last year, in thousand euros. public static function months(): array<Compare> { return [ { name: 'July', value: 1512, last: 1371 }, { name: 'August', value: 1468, last: 1349 }, { name: 'September', value: 1840, last: 1570 }, ]; }
// The orders of each week of the quarter and of the same week last year. public static function weeks(): array<Compare> { array<int> $now = [2810, 2765, 2690, 2742, 2655, 2598, 2710, 2875, 3020, 3190, 3305, 3402, 3452]; array<int> $last = [2620, 2580, 2490, 2540, 2470, 2410, 2500, 2650, 2760, 2900, 3010, 3080, 3018]; array<Compare> $weeks = []; for (int $week = 0; $week < 13; $week++) { $weeks[] = { name: 'W' . ($week + 27), value: $now[$week], last: $last[$week] }; } return $weeks; }
// The revenue of each region this quarter and in the same quarter last year, in thousand euros. public static function regions(): array<Compare> { return [ { name: 'Germany', value: 2410, last: 2190 }, { name: 'Austria', value: 512, last: 455 }, { name: 'Switzerland', value: 468, last: 430 }, { name: 'Netherlands', value: 395, last: 341 }, { name: 'France', value: 352, last: 318 }, { name: 'Italy', value: 241, last: 201 }, { name: 'Spain', value: 186, last: 150 }, { name: 'Poland', value: 142, last: 108 }, { name: 'Nordic countries', value: 81, last: 62 }, { name: 'Other countries', value: 33, last: 35 }, ]; }
// The products with the most revenue this quarter. The revenue is in euros, and the margin in percent. public static function products(): array<Product> { return [ { line: 'Paper', name: 'Copy paper A4, 80 g/m²', units: 61240, revenue: 303138, margin: 22 }, { line: 'Print', name: 'Toner cartridge, black', units: 3410, revenue: 218240, margin: 31 }, { line: 'Tech', name: 'USB headset with microphone', units: 3920, revenue: 174440, margin: 44 }, { line: 'Print', name: 'Toner cartridges, colour', units: 2280, revenue: 163020, margin: 33 }, { line: 'Tech', name: 'USB-C hub with 7 ports', units: 3870, revenue: 150930, margin: 47 }, { line: 'Desk', name: 'Magnetic whiteboard 120 × 90 cm', units: 1180, revenue: 140420, margin: 38 }, { line: 'Tech', name: 'Wireless keyboard', units: 3880, revenue: 135412, margin: 42 }, { line: 'Writing', name: 'Notebook A5, dotted', units: 16540, revenue: 131493, margin: 55 }, { line: 'Tech', name: 'Wireless mouse, silent click', units: 5710, revenue: 128475, margin: 46 }, { line: 'Desk', name: 'LED desk lamp, dimmable', units: 3260, revenue: 119968, margin: 41 }, { line: 'Kitchen', name: 'Coffee beans, 1 kg, fair trade', units: 6150, revenue: 116235, margin: 28 }, { line: 'Desk', name: 'Laptop stand, aluminium', units: 3790, revenue: 109910, margin: 49 }, { line: 'Writing', name: 'Gel pens, 0.5 mm', units: 11920, revenue: 102512, margin: 52 }, { line: 'Paper', name: 'Presentation paper A4, 120 g/m²', units: 8640, revenue: 98496, margin: 34 }, { line: 'Filing', name: 'Lever arch files, 80 mm', units: 24310, revenue: 88732, margin: 39 }, { line: 'Writing', name: 'Fineliners, 10 colours', units: 8790, revenue: 86142, margin: 51 }, { line: 'Paper', name: 'Sticky notes, 12 pads', units: 9150, revenue: 84180, margin: 48 }, { line: 'Paper', name: 'Copy paper A3, 80 g/m²', units: 7420, revenue: 80878, margin: 24 }, { line: 'Writing', name: 'Whiteboard markers, 4 colours', units: 11630, revenue: 75014, margin: 46 }, { line: 'Paper', name: 'Flip chart pads, 20 sheets', units: 3410, revenue: 73315, margin: 37 }, { line: 'Desk', name: 'Desk organiser, mesh', units: 5320, revenue: 71288, margin: 44 }, { line: 'Filing', name: 'Archive boxes, 10 pieces', units: 3980, revenue: 70844, margin: 35 }, { line: 'Paper', name: 'Address labels, 2400 labels', units: 4210, revenue: 68202, margin: 43 }, { line: 'Desk', name: 'Letter trays, stackable', units: 4290, revenue: 66924, margin: 40 }, { line: 'Writing', name: 'Highlighters, 6 colours', units: 10870, revenue: 64133, margin: 50 }, { line: 'Paper', name: 'Envelopes DL with window', units: 2540, revenue: 63246, margin: 29 }, { line: 'Tech', name: 'USB-C cable, 2 m', units: 6230, revenue: 61677, margin: 58 }, { line: 'Desk', name: 'Desk calculator, 12 digits', units: 3960, revenue: 59004, margin: 36 }, { line: 'Paper', name: 'Envelopes C4, self-seal', units: 2980, revenue: 55875, margin: 30 }, { line: 'Desk', name: 'Stapler for 30 sheets', units: 4110, revenue: 53019, margin: 42 }, { line: 'Kitchen', name: 'Tea selection, 50 bags', units: 6870, revenue: 50838, margin: 33 }, { line: 'Writing', name: 'Notebook A4, ruled', units: 11120, revenue: 48928, margin: 47 }, { line: 'Filing', name: 'Clear pockets A4, 100 pieces', units: 7340, revenue: 46242, margin: 41 }, { line: 'Desk', name: 'Two-hole punch for 40 sheets', units: 2410, revenue: 44344, margin: 39 }, { line: 'Tech', name: 'Batteries AA, 24 pieces', units: 3620, revenue: 43078, margin: 26 }, { line: 'Desk', name: 'Tape dispenser, weighted', units: 3540, revenue: 39825, margin: 45 }, { line: 'Desk', name: 'Scissors 21 cm, soft grip', units: 7980, revenue: 37506, margin: 53 }, { line: 'Filing', name: 'Dividers A4, 12 tabs', units: 12470, revenue: 35540, margin: 49 }, { line: 'Tech', name: 'Screen cleaning wipes', units: 4980, revenue: 34362, margin: 57 }, { line: 'Kitchen', name: 'Paper cups, 50 pieces', units: 10160, revenue: 32512, margin: 31 }, { line: 'Desk', name: 'Clear tape, 8 rolls', units: 4430, revenue: 31453, margin: 44 }, { line: 'Filing', name: 'Shredder bags, 50 pieces', units: 2310, revenue: 29106, margin: 34 }, { line: 'Desk', name: 'Snap-off cutter 18 mm', units: 6890, revenue: 27216, margin: 52 }, { line: 'Desk', name: 'Aluminium ruler 30 cm', units: 8640, revenue: 25488, margin: 55 }, { line: 'Desk', name: 'Binder clips, 12 pieces', units: 9930, revenue: 23832, margin: 51 }, { line: 'Writing', name: 'Pencils HB, 12 pieces', units: 5870, revenue: 22306, margin: 48 }, { line: 'Desk', name: 'Whiteboard magnets, 20 pieces', units: 3610, revenue: 20938, margin: 50 }, { line: 'Desk', name: 'Staples 24/6, 5000 pieces', units: 9840, revenue: 19188, margin: 46 }, ]; }}<?nvsnamespace Paperwork;
use Core\Html\Markup;use Novis\Image\Barcode;use Novis\Image\QrCode;use Novis\Pdf\Document;use Novis\Pdf\Pages;use Novis\Pdf\Rendered;
// The tickets of one order. Each ticket is its own PDF file, so each person can get their own ticket.// The buyer gets one file with a summary of the order and all the tickets.final class Tickets{ // Returns the file for the buyer: the summary of the order, then one page for each ticket. public static function order(): tainted bytes { var $order = Sample::order(); array<Pages> $parts = [Pages::of(Tickets::summary()->bytes)]; foreach ($order->attendees as Sample::Attendee $attendee) { $parts[] = Pages::of(Tickets::ticket($attendee)->bytes); } // `Pages::merge` puts the pages of all the files into one file, in this order. return Pages::merge($parts); }
// Renders the ticket of one person. public static function ticket(Sample::Attendee $attendee): Rendered { var $event = Sample::event(); var $order = Sample::order(); string $price = Brand::money($attendee->price); string $title = "Ticket {$attendee->id}"; // The QR code and the barcode both contain the ticket number. A scanner at the entrance reads either one. string $qr = QrCode::svg($attendee->id, { margin: 0 }); string $barcode = Barcode::svg($attendee->id, Barcode::Symbology::Code128, { height: 40, margin: 0 }); var $html = html`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{$title}</title><?= Brand::css() ?><?= Tickets::css() ?></head><body><div class="card"> <div class="banner"> <p class="kicker">{$event->dates}</p> <h1>{$event->name}</h1> <p>{$event->tagline}</p> </div> <div class="who"> <div class="label">Attendee</div> <p class="name">{$attendee->name}</p> <p class="type">{$attendee->ticket}</p> </div> <div class="fact first"><div class="label">Valid on</div>{$attendee->days}</div> <div class="fact"><div class="label">Venue</div>{$event->venue}</div> <div class="fact"><div class="label">Seat</div>{$attendee->zone}, {$attendee->seat}</div> <div class="fact first second"><div class="label">Order</div>{$order->number}</div> <div class="fact second"><div class="label">Bought by</div>{$order->buyer->name}</div> <div class="fact second"><div class="label">Price</div>{$price}</div> <div class="small">{$event->doors} {$event->venue}, {$event->address}. This ticket is for one person, and it is checked once at the entrance.</div> <div class="stub"> <div class="label">Admit one</div> <img class="qr" src="qr.svg" alt="QR code of the ticket number"> <p class="id">{$attendee->id}</p> <img class="barcode" src="barcode.svg" alt="Barcode of the ticket number"> <p class="seat">{$attendee->zone}<br>{$attendee->seat}</p> </div></div></body></html>`; return Document::fromHtml($html) ->withAsset('qr.svg', $qr as bytes) ->withAsset('barcode.svg', $barcode as bytes) ->withCreationTime(Tickets::created()) ->render(); }
// Renders the summary of the order: who bought the tickets, each ticket and its price, and the total. public static function summary(): Rendered { var $order = Sample::order(); var $event = Sample::event(); decimal $total = '0.00' as decimal; var $rows = html``; foreach ($order->attendees as Sample::Attendee $attendee) { $total = $total + $attendee->price; string $price = Brand::money($attendee->price); $rows = $rows + html`<tr><td><b>{$attendee->name}</b></td><td>{$attendee->ticket}</td><td class="mono">{$attendee->id}</td><td class="num">{$price}</td></tr>`; } // The prices include VAT of 19 %. This is the VAT part of the total. string $vat = Brand::money(Core\Decimal::divideRounded($total * ('19' as decimal), '119' as decimal, 2, Core\RoundMode::HalfUp)); string $sum = Brand::money($total); string $placed = $order->placed->format('d MMMM yyyy'); string $title = "Order {$order->number}"; var $html = html`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{$title}</title><?= Brand::css() ?><?= Tickets::css() ?></head><body><div class="summary"> <div class="banner"> <p class="kicker">Your order</p> <h1>{$event->name}</h1> <p>{$event->dates} · {$event->venue}, {$event->address}</p> </div> <div class="order"> <div><div class="label">Order number</div>{$order->number}</div> <div><div class="label">Ordered on</div>{$placed}</div> <div><div class="label">Bought by</div>{$order->buyer->name}, {$order->buyer->city}</div> </div> <table class="lines"> <thead><tr><th>Attendee</th><th>Ticket</th><th>Ticket number</th><th class="num">Price</th></tr></thead> <tbody>{$rows} </tbody> <tfoot> <tr class="total"><td colspan="3">Total, paid by card</td><td class="num">{$sum}</td></tr> <tr class="vat"><td colspan="3">This includes VAT of 19 %</td><td class="num">{$vat}</td></tr> </tfoot> </table> <p class="small">Each ticket is on its own page. Print the pages, or send each person their page. A scanner at the entrance reads the QR code or the barcode.</p></div></body></html>`; return Document::fromHtml($html)->withCreationTime(Tickets::created())->render(); }
// The time of the order is the creation time of each file, so the same order always gives the same files. private static function created(): Core\Time\Instant { return Core\Time\Instant::fromIso(Sample::order()->placed->format('yyyy-MM-dd') . 'T10:30:00Z'); }
private static function css(): Markup { return html`<style>@page { size: A5 landscape; margin: 9mm; }.banner { background-image: linear-gradient(120deg, #1d3557 0%, #23577a 50%, #2a9d8f 100%); color: #ffffff; padding: 6mm 8mm 5mm 8mm; border-radius: 8pt 0 0 0; }.banner h1 { color: #ffffff; font-size: 21pt; margin: 1mm 0 1.5mm 0; }.banner p { margin: 0; color: #d6e6f0; }.banner .kicker { font-size: 7.5pt; font-weight: bold; letter-spacing: 0.16em; text-transform: uppercase; color: #9fe0d6; }
.card { display: grid; grid-template-columns: 1fr 1fr 1fr 52mm; grid-template-rows: auto auto auto auto 1fr; height: 130mm; }.card .banner { grid-column: 1 / 4; grid-row: 1; }.who { grid-column: 1 / 4; grid-row: 2; padding: 6mm 8mm 3mm 8mm; border-left: 0.75pt solid var(--line); }.who .name { font-size: 22pt; font-weight: bold; color: var(--brand); margin: 1mm 0 1mm 0; }.who .type { font-size: 10pt; font-weight: bold; color: var(--accent); margin: 0; }.fact { grid-row: 3; padding: 3mm 8mm 3mm 8mm; font-size: 10pt; font-weight: bold; color: var(--ink); }.fact.second { grid-row: 4; padding-bottom: 5mm; font-size: 9pt; color: var(--muted); }.fact.first { border-left: 0.75pt solid var(--line); }.fact .label { margin-bottom: 1.5mm; }.card .small { grid-column: 1 / 4; grid-row: 5; padding: 4mm 8mm 5mm 8mm; font-size: 7.5pt; color: var(--muted); border-top: 0.75pt solid var(--line); border-left: 0.75pt solid var(--line); border-bottom: 0.75pt solid var(--line); border-radius: 0 0 0 8pt; }.stub { grid-column: 4; grid-row: 1 / 6; text-align: center; padding: 7mm 6mm 5mm 6mm; background: var(--paper); border: 1.2pt dashed #9aa5b4; border-radius: 0 8pt 8pt 0; }.stub .label { margin-bottom: 4mm; }.stub .qr { display: block; width: 34mm; height: 34mm; margin: 0 auto; }.stub .id { font-family: "Liberation Mono", monospace; font-size: 8.5pt; font-weight: bold; color: var(--brand); margin: 3mm 0 6mm 0; }.stub .barcode { display: block; width: 40mm; height: 12mm; margin: 0 auto; }.stub .seat { margin-top: 8mm; padding-top: 4mm; border-top: 0.75pt solid var(--line); font-size: 9pt; font-weight: bold; color: var(--brand); }
.summary .banner { border-radius: 8pt 8pt 0 0; }.order { display: grid; grid-template-columns: 1fr 1fr 1.4fr; padding: 4mm 8mm; background: var(--paper); font-weight: bold; color: var(--brand); border-radius: 0 0 8pt 8pt; margin-bottom: 6mm; }.order .label { margin-bottom: 1mm; }table.lines { width: 100%; border-collapse: collapse; }.lines th { text-align: left; font-size: 7pt; font-weight: bold; letter-spacing: 0.06em; text-transform: uppercase; color: var(--brand); padding: 4pt 6pt; border-bottom: 1.5pt solid var(--brand); }.lines th.num { text-align: right; }.lines td { padding: 5pt 6pt; border-bottom: 0.5pt solid var(--line); }.lines .mono { font-size: 8pt; color: var(--muted); }.num { text-align: right; white-space: nowrap; }.lines tr.total td { font-weight: bold; font-size: 11pt; color: var(--brand); border-bottom: none; padding-top: 8pt; }.lines tr.vat td { color: var(--muted); border-bottom: none; padding-top: 0; }.summary .small { margin-top: 5mm; font-size: 8pt; color: var(--muted); }</style>`; }}<?nvsnamespace Paperwork;
use Core\Arr;use Core\Str;use Core\Test;use Novis\Pdf\Reader;
// Tests for the tickets. The file of the order has the summary on page 1 and one ticket on each page after it.final class TicketsTest{ #[Test] public function theOrderHasOnePageForEachTicket(): void { var $reader = Reader::open(Tickets::order()); Test::assertEquals($reader->pageCount, Arr::count(Sample::order()->attendees) + 1); Test::assertTrue(Str::contains($reader->text(1), 'FWC-2026-0417')); }
#[Test] public function eachTicketPageHasItsAttendee(): void { var $reader = Reader::open(Tickets::order()); uint $page = 1; foreach (Sample::order()->attendees as Sample::Attendee $attendee) { $page++; Test::assertTrue(Str::contains($reader->text($page), $attendee->name)); Test::assertTrue(Str::contains($reader->text($page), $attendee->id)); } }
#[Test] public function nothingIsDroppedOrCutOff(): void { array<Novis\Pdf\Rendered> $files = [Tickets::summary()]; foreach (Sample::order()->attendees as Sample::Attendee $attendee) { $files[] = Tickets::ticket($attendee); } foreach ($files as Novis\Pdf\Rendered $file) { Test::assertEquals($file->pageCount, 1); Test::assertCount($file->dropped, 0); Test::assertCount($file->missingGlyphs, 0); Test::assertCount($file->overflows, 0); } }}<?nvsnamespace Paperwork;
use Core\Decimal;use Core\RoundMode;
// The sums of an invoice. The PDF and the electronic invoice both use these, so they always show the same total.final class Totals{ public function constructor( public readonly decimal $net, public readonly decimal $vat, public readonly decimal $total, ) {}
// The VAT rate in percent. All items on the sample invoice have the standard German rate. public static function rate(): decimal { return '19' as decimal; }
// The amount of one line: the quantity times the price of one unit. public static function line(Sample::Item $item): decimal { return $item->price * ($item->quantity as decimal); }
// Adds up the lines and the VAT. The VAT is rounded to whole cents once, on the sum of the lines. public static function of(array<Sample::Item> $items): Totals { decimal $net = '0.00' as decimal; foreach ($items as Sample::Item $item) { $net = $net + Totals::line($item); } decimal $vat = Decimal::divideRounded($net * Totals::rate(), 100, 2, RoundMode::HalfUp); return new Totals($net, $vat, $net + $vat); }
// Adds up the amounts that `data-mark` gives the rows of a page. public static function sum(array<string> $amounts): decimal { decimal $sum = '0.00' as decimal; foreach ($amounts as string $amount) { $sum = $sum + (($amount as ?decimal) ?? '0' as decimal); } return $sum; }}<svg xmlns="http://www.w3.org/2000/svg" width="240" height="64" viewBox="0 0 240 64"> <title>Shop</title> <rect width="64" height="64" rx="15" fill="#1d3557"/> <path d="M25 27v-5a7 7 0 0 1 14 0v5" fill="none" stroke="#5ec4b6" stroke-width="4" stroke-linecap="round"/> <rect x="17" y="26" width="30" height="25" rx="4" fill="#ffffff"/> <circle cx="32" cy="38.5" r="3.5" fill="#2a9d8f"/> <text x="78" y="46" font-family="Liberation Sans" font-size="42" font-weight="700" letter-spacing="-1.5" fill="#1d3557">shop</text> <circle cx="184" cy="42" r="5" fill="#2a9d8f"/></svg># Paperwork
A small web app written in Novis. It makes three PDF documents, the way a business needs them:
- an invoice over three pages, with a QR code for the payment and the electronic invoice inside,- a confidential quarterly report with a password, a table of contents and charts,- the event tickets of one order, with a QR code and a barcode on each ticket.
Run these commands in this folder:
```shnvs serve public/index.nvs # open http://127.0.0.1:8143/nvs test . # runs the tests```
In a clone of the repository, `bun nv app paperwork` starts the app from any folder.
The password of the report is `novis`.
The page [Example apps: Paperwork](https://novis-lang.org/guides/example-apps/paperwork/) explains each file.Get it running
Section titled “Get it running”Install Novis first. Then download only the folder apps/paperwork of the Novis
repository. A sparse clone (a clone that checks out only the folders you name) does this:
git clone --depth 1 --filter=blob:none --sparse https://github.com/novis-lang/novis.gitcd novisgit sparse-checkout set apps/paperworkcd apps/paperworkStart the server from the folder apps/paperwork:
nvs serve public/index.nvsOpen http://127.0.0.1:8143/ in your browser. The home page has a link to each document. You can
also open each address directly:
http://127.0.0.1:8143/invoice.pdfhttp://127.0.0.1:8143/report.pdfhttp://127.0.0.1:8143/tickets.pdf
The app renders the document again for each request. It writes no file.
Run the tests
Section titled “Run the tests”nvs test .nvs test . reads every .nvs file in the folder as one program and runs each #[Test] method.
The tests open each finished PDF file with Novis\Pdf\Reader and check the text on its pages:
Paperwork\AppTest ✓ theHomePageLinksEachDocument 0.7 ms ✓ eachDocumentIsSentAsAPdf 589.4 ms ✓ anUnknownPathIsNotFound 0.3 ms ✓ aWrongMethodIsNotAllowed 0.2 ms Paperwork\InvoiceTest ✓ theTotalsAddUp 0.5 ms ✓ theLastPageShowsTheTotal 172.7 ms ✓ theCarriedForwardAmountIsOnPageOne 177.3 ms ✓ theXmlHasTheSameNumberAndTotal 130.5 ms ✓ nothingIsDroppedOrCutOff 116.2 ms ✓ twoRendersGiveTheSameFile 263.6 ms Paperwork\ReportTest ✓ theEncryptedReportCannotBeReadWithoutThePassword 261.0 ms ✓ theContentsGiveThePageOfEachChapter 230.0 ms ✓ theHeaderShowsTheChapter 256.9 ms ✓ theLongTableRepeatsItsHeader 183.2 ms ✓ nothingIsDroppedOrCutOff 207.5 ms Paperwork\TicketsTest ✓ theOrderHasOnePageForEachTicket 165.4 ms ✓ eachTicketPageHasItsAttendee 297.2 ms ✓ nothingIsDroppedOrCutOff 248.1 ms
0 failed, 18 passed, 0 skipped, 0 flaky in 3305 msWhat each file does
Section titled “What each file does”paperwork/ nvs.toml the configuration: the port, and the app may read its logo and no other file assets/ logo.svg the logo that the three documents show public/ index.nvs the entry file: every request starts here src/ App.nvs the routes, and the method that sends a PDF file AppTest.nvs sends requests to the app and checks the responses Brand.nvs the logo, the colours and the money format of all three documents Chart.nvs draws the charts of the report as SVG images FacturX.nvs writes the XML of the electronic invoice Gate.nvs decides which routes may run, and shows the error pages Home.nvs the HTML pages: a link to each document, and the error pages Invoice.nvs the invoice InvoiceTest.nvs tests the totals, the pages and the XML of the invoice Report.nvs the quarterly report ReportTest.nvs tests the password, the contents and the tables of the report Sample.nvs the data that the documents show Tickets.nvs the tickets, and the summary of the order TicketsTest.nvs tests the pages of the tickets Totals.nvs the sums of the invoice, for the PDF and for the XMLnvs.toml has two sections. [server] listen sets the port of the server to 8143. The other
example apps use other ports, so you can run them at the same time. [capabilities.fs] allows the
app to read the file assets/logo.svg. The app cannot read any other file, and it cannot write a
file.
public/index.nvs calls Core\Router::dispatch(new Paperwork\Gate()). dispatch finds the route
that matches the request and calls its method.
src/App.nvs has one method for each route. send() sets the header
content-disposition: inline, so the browser shows the PDF file. Then it sends the bytes with Core\Response::sendBytes.
src/Gate.nvs is the gate, and dispatch calls it for every request. allows runs before each
route method. refused shows a page when no route can handle the request, such as a path with no
route (404) or a wrong HTTP method (405). failed shows a page when a route method throws an error (500). dispatch sets the
status code first, so the gate only shows the page.
Invoice.nvs, Report.nvs and Tickets.nvs each build the HTML of their document with an html
template, which escapes every value. Document::fromHtml reads that HTML. Each method call after it
adds one thing to the document, and render() returns the finished file.
Each document sets its creation time with withCreationTime(). The same data then always gives the same file,
byte for byte. The test twoRendersGiveTheSameFile checks this.
Sample.nvs has the data of the three documents. A real app reads it from its database.
What each document uses
Section titled “What each document uses”The invoice:
Document::fromHtmlreads the HTML and the CSS of the invoice.withAssetadds the logo and the QR code as SVG images. The HTML shows them with<img src="logo.svg">.withHeaderandwithFooterbuild the top and the bottom of each page. Each gets aPage, which has the page number and the number of pages.withSlotsfills the rows “Carried forward” and “Brought forward” on each page. Each row of items has adata-markattribute with its amount.Page::marksreturns the amounts on one page.Page::marksUpToreturns the amounts on this page and on every page before it.withStandardwithDocument::Standard::PdfA3bmakes a file for an archive.withInvoiceXmlputs the Factur-X XML into the file.withCreationTimesets the creation time.QrCode::giroCodewrites the text of a SEPA bank transfer.QrCode::svgdraws that text as a QR code.
The report:
withPasswordencrypts the file with a password.withStandardwithDocument::Standard::PdfUa1makes an accessible file. Each chart has analttext, which a screen reader reads.Page::stringreturns the name of the chapter for the header. Each chapter heading saves its text with the CSS propertystring-set.- The cover is on a page named
cover, from the CSS rule@page cover. The header checks$page->name, and the cover gets no header. - The table of contents uses the CSS function
target-counter(). It gives the page number of each chapter. withAssetadds the two charts.Chart.nvsdraws each chart as SVG, so the PDF file has it as a vector drawing.
The tickets:
Document::fromHtmlandrendermake one PDF file for each ticket, and one for the summary.Pages::ofreads each file.Pages::mergejoins them into one file, in order.QrCode::svgandBarcode::svgdraw the two codes of each ticket. The barcode usesBarcode::Symbology::Code128.
The tests:
Reader::openopens a finished file.textreturns the text of one page.invoiceXmlreturns the XML inside the invoice.Renderedhas the bytes of the file, its number of pages and itsoverflows.overflowslists the content that did not fit on its page. The tests check that this list is empty.
Start your own document from it
Section titled “Start your own document from it”- Copy the folder
apps/paperworkand give it the name of your app. - Choose a namespace for your app, for example
Shop. Changenamespace Paperwork;in each file undersrc/, and theautoloadline andPaperwork\Gateinpublic/index.nvs. - Keep the document that is closest to yours, for example
Invoice.nvs, and its test. Delete the other documents, their tests and their routes insrc/App.nvs. - Replace
Sample.nvswith your own data. Then change the HTML and the CSS. Runnvs test .after each change. - Replace
assets/logo.svgwith your logo. If the file name changes, change it innvs.tomltoo.
The home page of this app shows the password of the report, so you can open the file. A real app gets the password from the person who requests the report.
Read more
Section titled “Read more”Novis\Pdf\Documentlists every method that builds a PDF file.- Notes is an example app with SQLite, HTML pages and a JSON API.
