PPPHP

Documents: Invoice, Ledger & PDF

A Document page is a blank, paper-sized sheet (A4, Letter, Legal, A5, A3) that you design freely in the Designer — a letterhead, rules, a line-items table with totals, notes, signatures — and then print or download as a real PDF. Bind it to a table and it opens for one record (Invoice #42, a customer’s statement, a ledger page), reading that record everywhere with :master.<field>. Built for accounts & audit apps: invoices, tax invoices, receipts, delivery notes, ledgers, statements of account and reports.

Where to find it. In the Designer sidebar click + New custom page, choose Page kind → Document, pick the table it is about (or Standalone), and name it (e.g. Invoice). Or on a standalone page pick the Document starter layout.
See them listed under Pages. Once a document is bound to a table it is generated per table like any other page — generated/<table>/<slug>.php — so it now appears on that table’s Pages screen under Document pages, alongside List, Add, Edit and View. That panel shows the paper, whether the document auto-numbers, how many copies it prints and whether it is watermarked, protected or e-mailable, and it lets you switch a document off without deleting its design — it is simply left out of the next build and its buttons disappear from the List and View pages. Documents with no saved switch stay on, so nothing you built before changed.
A document is not a View page. It is tempting to think of an invoice as “the view page for the invoices table”, but a View page renders one record’s fields. A document renders that record and its line items, with subtotal and grand total, on real paper geometry — plus a gap-free number, the amount in words, optional watermark, PDF permissions, named copies and e-mail delivery. Use a View page when a row is something people read on screen; use a document when one row is a piece of paper.

Contents

How it works

  1. You create a Document page. The Designer canvas becomes a real paper sheet at the chosen size — no navbar, no sidebar — and you drop components onto it exactly like any other page.
  2. You bind it to a table (Properties → Document → About one record of). The built page then opens as …/<page>.php?id=<record>, loads that record (under login + Row-Level Security) and pins it as :master for every component.
  3. The built page has a toolbar with Print (browser) and Download PDF (server, mPDF), and every bound record’s View page gets a Documents button that opens it.

The paper canvas

Properties → Paper: Size (A4, Letter, Legal, A5, A3), Orientation (portrait / landscape) and Margin. The canvas shows the sheet at true proportions; the build emits the matching @page rule so print and PDF use the same box. Everything inside the margins is yours.

Binding a document to a record

Properties → Document → About one record of: pick the table. Record parameter is the URL key (default id). Leave it unbound for a static document (a price list, a notice).

Bind an Invoice document to your invoices table, a Statement to customers, a Delivery note to orders. One table can have several documents.

Reading the record: :master.<field>

On a bound document the current record is available to every data component through SQL Variables as :master.<column> — in a Table Card’s SQL or WHERE, a Live Value, a chart, a Master-Detail grid. Values are safely quoted for you.

-- The line items of THIS invoice (Table Card → Custom SQL)
SELECT description AS Description, qty AS Qty, rate AS Rate, qty * rate AS Amount
FROM invoice_items
WHERE invoice_id = :master.id
-- The customer block for THIS invoice
SELECT name, address, phone, pan FROM customers WHERE id = :master.customer_id

Opening it — the Documents button

Once a document is bound to a table, that table’s View page shows a Documents button per document (labelled with the document’s name). It opens the sheet for the record being viewed in a new tab: generated/<table>/<page>.php?id=<record>. You can also link to that URL from a Custom Button.

Print vs Download PDF

ButtonHowBest for
PrintThe browser’s own print dialog, using the sheet’s @page size & margins (choose “Save as PDF” there too).Pixel-perfect output of exactly what you see, including complex grid layouts.
Download PDFThe server renders the same sheet with mPDF (pure PHP, bundled — works on shared hosting) and streams a file. Same URL with &format=pdf.A real, selectable-text PDF that is identical on every device, ideal for emailing, archiving and automation. Full Unicode — Nepali / Devanagari renders as real text.
Your styling comes through. The server PDF uses the same theme as the screen: theme colours (borders, row stripes, accents) are resolved to real colours and bold text stays bold — PDF engines know neither CSS variables nor weights like 800, so PPPHP converts them for you. Soft shadows are dropped (paper is flat).
PDF engines don’t know CSS Grid — PPPHP handles it for you. In the server PDF a Cell Grid is rendered as an equivalent table (same rows, columns, merges, widths and cell styling), so letterheads, meta blocks and signature rows come out exactly as designed. Responsive Size & Layout spans on other components become proportional widths. Only genuinely free-form arrangements can differ — for those, Print → Save as PDF is pixel-perfect.

Ready-made layouts

You rarely need to start from a blank sheet. In + New custom page choose Page kind Document and pick a Start from layout — the sheet is pre-built with a Letterhead, title, meta block, Line Items and the usual footer so you only fill in table names and columns:

Start fromWhat you get
InvoiceLetterhead, INVOICE title, Bill-to / Invoice-meta cells, Line Items with Subtotal & Grand total, amount in words, terms + signature.
Tax InvoiceAs Invoice, with Tax / VAT 13 % on, the buyer’s PAN/VAT line and the seller’s Tax ID in the letterhead.
ReceiptA compact “Received with thanks” sheet — payer, amount, amount in words, mode of payment, signature.
Delivery NoteLine Items with Rate and Amount switched off (quantities only) and a received-by block.
LedgerParty ledger: Date / Particulars / Debit / Credit / Balance with a running balance and closing figures.
StatementStatement of account for a period — opening balance, transactions, closing balance, ageing note.
ReportA titled report sheet — letterhead, title, intro text, a data Table Card with totals and page numbers (switch Paper → Orientation to landscape for wide tables).

Every starter is ordinary components on an ordinary sheet — move, restyle or delete anything afterwards.

The Letterhead component

Components → Documents → Letterhead. One drop gives you the company header, pre-filled from your app’s Style → Brand (name and logo) so every document matches. Fill or override:

PropertyWhat it does
LayoutLogo left (classic), Logo right, Centered, Stacked (logo above text).
Logo / Logo widthBlank = the Style brand logo. Click Upload to add a PNG / JPG / SVG / WebP (stored in Custom Files → img/, shipped with the app), Pick to choose one already uploaded, or paste a URL. A logo file that is missing is simply left out — never a broken-image box, never an empty column. Width in px (a 300–600 px source prints razor-sharp).
Without a logoShow the app’s initials badge (new letterheads) — when there is no logo image, the same letter mark as your app’s header (Task Tracker → TT, Northwind → NO) in your theme colour (or the Accent colour), on screen, in print and in the PDF. Nothing — text only keeps just the name; letterheads made before this option keep that look.
Company name / Tagline / Name sizeBlank name = the app name. Tagline sits under it; size Small / Medium / Large.
Address, Phone, Email, WebsiteThe contact lines (address keeps its line breaks).
Tax ID label / Tax IDe.g. PAN No. / VAT Reg. No. and the number — printed as its own line.
Accent colourColour of the company name (and the rule, unless set separately).
Rule under the letterhead / colour / thicknessThe horizontal rule that closes the header.

Because the letterhead is a component you can also drop it on Print pages and reports — and style it like anything else (fonts, borders, background). The logo is embedded into the server PDF from your app files; no external URL is ever fetched.

The Line Items + Totals component

Components → Documents → Line Items. The items table every commercial document needs, with all the arithmetic done on the server. Pick the rows, map the columns, switch on what you need:

GroupProperties
SourceTable — a detail table + Filter (WHERE) such as invoice_id = :master.id + Order by. Row-Level Security and your table WHERE events are applied, exactly as on list pages. SQL — your own SELECT (read-only; all SQL Variables available).
ColumnsDescription / Qty / Rate / Amount / Unit column names. Leave Amount column blank to compute qty × rate.
ShowSerial #, Unit, Rate, Amount column & totals (off = a delivery note), plus every column label.
NumbersCurrency prefix (Rs. , $), decimals, qty decimals.
TotalsSubtotal → Discount (None / Percent % / Fixed amount) → Tax / VAT (Percent % of the discounted subtotal) → Round off (the grand total is rounded to the nearest whole unit) → Grand total. Every label is editable.
Amount in wordsPrints the grand total in words in English (lakh / crore), English (million / billion) or Nepali (नेपाली), with your currency word (Rupees / रुपैयाँ / Dollars) and sub-unit.

Worked example — Tax Invoice at VAT 13 %: items 2 × 1,000 and 1 × 1,100 → Subtotal 3,100.00 → Discount 5 % −155.00 → VAT 13 % +382.85 → Grand total 3,327.85. In words (lakh style): Three Thousand Three Hundred Twenty Seven Rupees and Eighty Five Paisa Only; in Nepali: तीन हजार तीन सय सत्ताइस रुपैयाँ पचासी पैसा मात्र.

Delivery note: switch off Rate column and Amount column & totals — you get Serial / Description / Qty / Unit only. Ledger-style: use SQL source with Debit/Credit columns mapped to Qty/Rate and totals off, or simply a Table Card (see the Ledger example below).

Rows are capped at 500 per document and split across pages automatically without breaking a row. The totals block always stays together at the end of the table.

Footer text & page numbers

In Page → Paper set a Footer text and tick Page numbers. The footer repeats on every printed and PDF page; in the text you may use {PAGENO} (current page) and {nbpg} (total pages), e.g. Page {PAGENO} of {nbpg} · Generated by Sunrise Traders. Leave the text blank with Page numbers on for a plain “Page 1 of 3”.

Documents from the List

Every table that has a bound Document page gets it in two more places, automatically:

Bulk output is rendered by the same page as the on-screen document (same guards, events, Row-Level Security and field decryption), one record at a time, up to 200 per batch. A record you may not see is silently skipped — it can never leak into someone else’s PDF.

E-mailing a document

When the app has an e-mail server configured (Misc → Email), the document toolbar shows E-mail. It opens a small form with To, Subject and Message — pre-filled from the page’s E-mail properties — and sends the PDF as an attachment (Invoice-INV-2026-00042.pdf).

Property (Page → E-mail)What it does
Recipient columnThe bound table’s e-mail column. Pre-fills To and enables E-mail to each record in bulk. Blank = the user types the address.
Subject / MessageDefaults with tokens: {{invoice_no}}, :master.customer_name, {{today}}. Blank subject = “Invoice #42”.
Keep a copy of every sent PDFStores the exact PDF that was sent in the archive (see below) — an audit-grade record of what the customer received.

Sends fire the usual global.email.beforeSendEmail / afterSendEmail / onEmailFailed events and are logged with recipient, user and time. Failed sends never silently succeed.

Archive & history

Archive saves a PDF copy of the document as it is right now in the app's private document store (access-denied to the web; served only through the app after re-checking the record’s Row-Level Security). History ▾ lists every archive and e-mail of this record’s document — who, when, to whom, with a download link for archived copies. Selection bar → Documents ▾ can archive many records at once (via the API, see developers).

Auto-numbering

Page → Numbering: pick the bound table’s number column (e.g. invoice_no). The first time the document is opened for a record whose column is empty, the next number is allocated and written to the record — every Letterhead, Line Items, QR and :master.invoice_no on the sheet sees it immediately. Numbers are allocated inside a database transaction, so two users generating at the same instant get two different numbers, with no gaps.

PropertyExample
Prefix / SuffixINV-{Y}- → INV-2026-00042 · tokens {Y} {y} {m} {d} {period}
Digits (pad)5 → 00042
Start at1 (or continue from your old system: 1001)
RestartNever · Every year · Every month · Every day — each period keeps its own counter.

Prefer to number when the record is saved rather than when the document is opened? Use pp_next_number() in a beforeAddSave event — it joins the save's own transaction, so if the save is cancelled or fails, the number is given back and your sequence stays gap-free. Nepali fiscal years: pass your own period (e.g. 2083/84).

// Events → invoices → Page Events → Before Add Save
$data['invoice_no'] = pp_next_number('invoice', ['prefix' => 'INV-{Y}-', 'pad' => 5, 'reset' => 'yearly']);
// → INV-2026-00042; works the same on MySQL, PostgreSQL, SQL Server and SQLite

Watermark & PDF protection

Canvas layout — free placement

Page → Layout → Layout mode: Canvas turns the sheet into a free canvas: every top-level component sits at an exact X / Y / Width / Height in millimetres (Properties → Position & size). Drag a component anywhere, drag its corner to resize, use the arrow keys to nudge by 1 mm (Shift = 5 mm). A dotted 5 mm grid helps alignment.

Page Break & QR codes

Every image property in the Designer (Letterhead → Logo, the Image component → Source) has the same three buttons:

ButtonWhat happens
UploadSends the file to Custom Files → img/ of this project (max 4 MB; PNG, JPG, GIF, WebP, SVG). The property is set to custom/img/<file> and the file ships inside every build.
PickShows the images already in Custom Files — one click selects.
×Clears the property; a Letterhead then falls back to the app brand logo from Style.
How images reach the PDF. The server PDF engine has no web browser, so app-relative images (custom/img/logo.png, uploads) are embedded straight from the file on disk at full resolution — logos come out as crisp as the source. Remote URLs are fetched; a missing file is skipped silently. For the sharpest print use a PNG/SVG at least 300 px wide, or an SVG.

PDF quality: fonts, sizes, running header, copies

Text in the PDF is real vector type (embedded fonts) — it stays sharp at any zoom and is selectable/searchable. Tables, rules and the Cell Grid are drawn as vector lines. The Paper group gives you the remaining knobs:

PropertyUse it for
Document fontDejaVu Sans (clean default) · DejaVu Serif (classic ledgers) · Condensed (wide tables) · Mono (statements) · Free Sans / Free Serif (most natural Devanagari). All embed fully and cover Nepali / Hindi.
Base font size8–12 pt. 9 pt fits ~35 item rows per A4 page; 11 pt for letters and certificates.
Header textRepeated top-right on every PDF page — e.g. Invoice {{invoice_no}} · continued. Tokens resolve per record; {PAGENO} works too.
Footer text / Page numbersBottom of every page (print and PDF).
CopiesOriginal, Duplicate, Triplicate → the PDF repeats the document once per label with the label printed at the top — the usual VAT-invoice set in one download (also in bulk merged PDFs and e-mails). Blank = single copy.

Negative amounts (discounts, credits) print as – Rs. 137.58; totals are right-aligned in their own column; rows never split across pages and the totals block stays together.

Date & time stamp

Page → Paper → Date & time stamp prints the moment the document was generated — on screen, in print and on every PDF page (running header or footer). Pick the calendar and whether the time is shown:

CalendarPrints
EnglishWednesday, 2 September 2026 · 6:45 PM
Nepali (BS)बुधबार, १७ भदौ २०८३ · साँझ ६:४५ — Devanagari digits, Nepali month and weekday, part of day (बिहान / दिउँसो / साँझ / राति)
Nepali in Latin scriptWednesday, 17 Bhadra 2083 · 6:45 PM
English + NepaliBoth, separated by a bar — the usual choice for official Nepali documents

Tokens & filters

Anywhere a document takes text — Text, Heading, Letterhead lines, QR / Barcode values, e-mail subject, watermark, header/footer, stamp label — you can merge record and clock values. A filter after | formats the value:

TokenResult
{{invoice_no}} · :master.invoice_noThe bound record’s column
{{invoice_date|bs}}Nepali date: मङ्गलबार, १ जेठ २०४७ (add the time when the column has one)
{{invoice_date|bs-en}}Tuesday, 1 Jestha 2047
{{invoice_date|ad}}Tuesday, 15 May 1990 · |date → 1990-05-15 · |time → 6:45 PM
{{total|words}} · {{total|words-ne}}Three Thousand … Rupees … Only · तीन हजार … रुपैयाँ … मात्र
{{total|ne}}Devanagari digits: ३,३२७.८५
{{customer|upper}} · |lowerCase change
{{today}} · {{now}}2026-09-02 · 2026-09-02 18:45 (document time zone)
{{today_ad}} · {{now_ad}}Wednesday, 2 September 2026 · with time
{{today_bs}} · {{now_bs}} · {{today_bs_en}}बुधबार, १७ भदौ २०८३ · with time · Latin script
:userid · :usernameThe signed-in user

Example Text block on an invoice: Date: {{invoice_date|bs}} ({{invoice_date|ad}}) · Amount: {{total|ne}} — {{total|words-ne}}.

Signature block, Barcode & Nepali numerals

Recipes — step by step

A VAT tax invoice with three copies

  1. + New custom page → Document → bind invoices → Start from Tax Invoice (VAT) → name Tax Invoice.
  2. Select the Letterhead → Logo → Upload your logo; fill address, phone, VAT No..
  3. Select Line Items → Source Table invoice_items, Filter invoice_id = :master.id; map Description / Qty / Rate; VAT 13 %; Amount in words Nepali or English (lakh).
  4. Page → Numbering: column invoice_no, prefix INV-{Y}-, digits 5, restart yearly.
  5. Page → Paper: Copies Original, Duplicate, Triplicate; Page numbers on; Date & time stamp in the footer, calendar English + Nepali. Page → Watermark: :master.status (prints PAID / DRAFT from the record).
  6. Optional, fully Nepali: Line Items → Numerals ०–९, Amount in words Nepali; a Text block मिति: {{invoice_date|bs}}; a Signature block with your seal image at the bottom-right; a Barcode {{invoice_no}} for the file copy.
  7. Page → E-mail: Recipient column customer_email, Subject Tax Invoice {{invoice_no}}. Build.
  8. Use it: Invoices list → tick rows → Documents ▾ → Tax Invoice → One merged PDF, or open one invoice → E-mail.

A fee receipt (school / clinic)

  1. Document bound to payments → Start from Payment Receipt.
  2. Text: Received with thanks from {{student_name}} the sum of {{amount}}; Line Items off (or a single row); Amount in words on.
  3. Numbering column receipt_no, prefix RCPT-; Copies Office copy, Customer copy; QR value https://your-app/verify/{{receipt_no}}.

A certificate on pre-printed paper (Canvas)

  1. Document bound to students, Paper A4 landscape, Layout mode Canvas.
  2. Drop a Heading ({{full_name}}) and drag it to X 40 / Y 95 mm, width 217; a Text block for the citation; a QR at bottom-right (X 250, Y 160, W 30).
  3. Set Margin 10mm so positions match the pre-printed frame; print a test page and nudge with the arrow keys (1 mm; Shift = 5 mm).

A monthly statement of account

  1. Document bound to customers → Start from Statement of Account; Table Card with the running-balance SQL from the Ledger example; Footer totals for Debit/Credit.
  2. Document font DejaVu Mono (aligned figures), Header text {{name}} · Statement · continued, Copies blank.
  3. From the customers List: select all matching → Documents ▾ → Statement → E-mail to each record (Recipient column email). Each customer receives only their own statement.

For developers

Everything above is also available to your Events, Custom Buttons and scheduled tasks through the generated app’s helpers:

// A document's PDF bytes (null when the record is hidden by RLS / missing)
$pdf = pp_doc_pdf('custom_invoice', $id);

// Many records → one merged PDF
$pdf = pp_doc_pdf_merged('custom_invoice', [12, 13, 14]);

// E-mail it (recipient defaults to the document's Recipient column)
$r = pp_doc_email('custom_invoice', $id, 'buyer@example.com', 'Your invoice', 'Thanks for your order.');
if (!$r['success']) error_log($r['message']);

// Keep a copy in the archive (returns the archive row id)
pp_doc_archive('custom_invoice', $id);

// Numbering — e.g. in tables.invoices.page.beforeAddSave:
$data['invoice_no'] = pp_next_number('invoice', ['prefix' => 'INV-{Y}-', 'pad' => 5, 'reset' => 'yearly']);
$preview = pp_peek_number('invoice', ['prefix' => 'INV-{Y}-', 'pad' => 5, 'reset' => 'yearly']);   // no allocation

// A QR code anywhere (Custom HTML, e-mails, PDFs)
echo '<img src="' . pp_qr('https://example.com/pay/42', ['size' => 120]) . '">';

// Expand document tokens yourself
echo pp_doc_text('Invoice {{invoice_no}} for :master.customer_name');

The HTTP endpoint behind the buttons is api/documents.php (POST JSON or form; actions merged, zip, email, archive, history; GET action=download&archive=ID). It requires the session, the CSRF token, view permission on the table and re-applies Row-Level Security to every record — the client never chooses the table, paper, watermark or recipient column; those come from the build-time registry app/documents.php.

Example — an Invoice

  1. + New custom page → Page kind Document → table invoices → name Invoice.
  2. Letterhead: drop the Letterhead component (Components → Documents). It is already filled with your app’s brand name and logo; add the address, phone, e-mail and PAN/VAT No. in its properties.
  3. A Heading “TAX INVOICE” and a Divider under it.
  4. Bill to & meta: a Table Card (Custom SQL) reading the customer via :master.customer_id, and a Text block for Invoice No / Date / Due date (or Live Values bound to the invoice).
  5. Line items: drop Line Items, Source Table → invoice_items, Filter invoice_id = :master.id, map the Description / Qty / Rate columns, set Tax / VAT to 13 % and switch on Show amount in words.
  6. A Divider, then a Text block for terms and an authorised-signature line.
  7. Build. Open any invoice’s View page → Documents → Invoice → Print or Download PDF.

Example — a Ledger / Statement of account

Bind a document to customers. Use a Table Card (Custom SQL) with a running balance — the totals row gives the closing figures:

SELECT t.txn_date AS Date, t.particulars AS Particulars,
       t.debit AS Debit, t.credit AS Credit,
       SUM(t.debit - t.credit) OVER (ORDER BY t.txn_date, t.id) AS Balance
FROM ledger t
WHERE t.customer_id = :master.id
ORDER BY t.txn_date, t.id

(On MySQL 5.7 use a correlated sub-select for the balance.) Add Footer totals for Debit and Credit.

Laying out the sheet

Security

Every property

PropertyWhat it does
Page kind → DocumentMakes the page a chromeless paper sheet (set when you create it).
Paper: Size / Orientation / MarginThe sheet box used by the canvas, print and PDF.
Document: About one record ofThe table this document is about; opens as ?id=… and exposes :master.*.
Document: Record parameterThe URL key carrying the record id (default id).
Paper: Footer text / Page numbersA running footer on every page; {PAGENO} / {nbpg} tokens.
Paper: Header text / Document font / Base font size / CopiesRunning header, PDF typeface and size, and copy labels (Original, Duplicate…).
Paper: Date & time stamp / Calendar / Include time / Stamp label / Time zoneGeneration stamp in the header or footer — English, Nepali (BS), Latin-script Nepali or both.
Start from (on create)A ready-made layout — Invoice, Tax Invoice, Receipt, Delivery Note, Ledger, Statement, Report.
Layout: Layout modeFlow (12-column grid) or Canvas (free placement in mm).
Numbering: Column / Prefix / Suffix / Digits / Start / RestartGap-free auto-numbering written to the record on first open.
Watermark: Text / Opacity / Colour / Also on screenDiagonal watermark on PDF (and screen/print). Tokens allowed.
PDF protection: Encrypt / Readers may / Open passwordEncrypted PDF with reader permissions.
E-mail: Recipient column / Subject / Message / Keep copiesDefaults for the E-mail button and bulk e-mail; archive of sent PDFs.
OutputPrint (browser) and Download PDF (server mPDF) — always both.
Advanced: Custom CSS / JSPer-document styling and behaviour, like any page.

Notes & gotchas

What’s next

Shipped: the paper + record-binding foundation, mPDF output, Letterhead and Line Items, ready-made layouts, running footers and page numbers, PDF-faithful Cell Grids, Documents on the List (row + bulk merged/ZIP/e-mail), e-mail with PDF attachment, archive & history, gap-free auto-numbering, watermark & PDF protection, the Canvas layout, Page Break and offline QR codes. Coming next: scheduled generation (e.g. monthly statements e-mailed by cron.php), signature/stamp images and a template gallery. See also Print & PDF pages, SQL Variables, Email, Live Value and the Component Guide.