ObjectStackObjectStack

Print pages — printing a record to a PDF file

Declare print on a record page, then download a record's PDF from the print service, rendered in headless Chromium as the requesting user

A print page is an ordinary page with one more key, print. The console draws it on screen as before and, when a user prints, puts only that page on paper: the sheet size, margins, page numbers and repeated header and footer come from the print declaration, mapped to print CSS by the console.

@objectstack/service-print prints the same page on the server. It renders the record's print page in headless Chromium, as the requesting user, and hands the PDF back as a download. A print stores nothing: no file, and no attachment on the record. Keeping a PDF on the record is a separate, explicit act — an upload to the record's attachments, or an action of the app's own.

Declare the print page

A print page is a kind: 'full' record page whose blocks are all from the printable subset (PRINTABLE_PAGE_COMPONENT_TYPES in @objectstack/spec/ui; os validate refuses anything else).

import { definePage } from '@objectstack/spec/ui';

export const InvoiceDocumentPage = definePage({
  name: 'invoice_document',
  label: 'Invoice',
  type: 'record',
  object: 'invoice',
  kind: 'full',             // not isDefault: the invoice keeps its own working record page
  print: { paperSize: 'A4', orientation: 'portrait', repeatHeader: true, pageNumbers: true },
  regions: [
    { name: 'header', components: [{ type: 'element:text', properties: { content: 'ACME Ltd' } }] },
    { name: 'main', components: [{ type: 'record:details' }] },
  ],
});

A record prints on any record page of its object that declares print, so an object keeps its everyday record page and adds one or more documents beside it (an invoice, a delivery note, a quote). The server renders the page the request names on the console's own routes: the object's default record page (isDefault: true) on the record route, …/OBJECT/record/ID, and any other print page on the named record-page route, …/OBJECT/record/ID/page/PAGE. A page that is not a record page of the object (type: 'record' with that object), or that declares no print, is refused rather than printed as some other page.

A user can print a print page without the service. When the record page bound to a record declares print, the record view shows a Print button that opens the browser's print preview of that page; saving a PDF there is the browser's own "Save as PDF". A print page that is not the object's default opens for the same record at /apps/APP/OBJECT/record/ID/page/PAGE, with the same button. PAGE must be a record page bound to OBJECT: any other name shows "Page not found", never the default page, so that URL never puts a different document on paper. (Printing from the browser, print is also accepted on a home or app page; the service prints record pages only.)

The console mounts a print stylesheet for a page that declares print, and only for it. Every rule sits inside @media print, so the page on screen is unchanged and is itself the preview. Only the print page reaches paper: the console chrome and the record view's own panels are hidden, and the page runs onto as many sheets as it needs.

KeyOn paper
paperSize (A4, A5, Letter, Legal), orientation@page { size }; A4 portrait when omitted
marginsThe @page margin, one side per key, in millimetres; a side left out keeps the console default
pageNumbers"page / pages" in the bottom-right margin box
repeatHeader, repeatFooterThe page's header / footer region repeated on every sheet
repeatTableHeadersA table's column headings repeated on every sheet it runs onto; on when omitted
avoidBreakInsidebreak-inside: avoid on each block of a region

On a print page whose sections may break between sheets, author one record:details block per section: avoidBreakInside keeps each block whole on one sheet when it fits, so a block holding several sections moves to the next sheet as one piece.

Leave avoidBreakInside off on a print page whose detail table can run past one sheet, such as a record:line_items table on a quote or invoice with many lines. A table is one block, so with the key on, a table that does not fit the rest of the first sheet moves whole to the next sheet even when it cannot fit any single sheet, and is broken there. The first sheet is then left with only the blocks above the table and a blank lower part, and the document can take one sheet more: measured on an A4 invoice page, a 21-line table printed on 3 sheets with the key on and 2 with it off. With the key off, the table starts under the blocks above it and runs on, with its column headings repeated on each sheet (repeatTableHeaders).

Blocks print whole:

  • record:line_items loads at most its row cap (limit, 500 when unset). On a print page, when the child object has more lines than that, the block draws the cap's lines and a note naming the cap and, when the server reports one, the total, so a printed copy never drops lines silently.
  • A collapsible record:details section draws open, and a section prints every declared field, empty ones included, with no "Show N empty fields" row. A section's hideEmpty still hides what it hides.

Compose the print service

The service is composed explicitly; a deployment that does not list it never loads a browser driver.

import { PrintServicePlugin } from '@objectstack/service-print';

export default defineStack({
  // …
  plugins: [new PrintServicePlugin()],
});

The engine is headless Chromium, in one of two placements. Configure exactly one, plus the URL the browser loads the console from:

SettingPlugin optionWhat it is
OS_PRINT_CHROMIUM_PATHchromiumPathLocal placement: a Chromium executable on this host, launched per print.
OS_PRINT_BROWSER_ENDPOINTbrowserEndpointRemote placement: a browser's DevTools WebSocket endpoint (ws:// or wss://), connected per print. For hosts that cannot carry a browser of their own. The requesting user's session cookie travels in the endpoint's frames: use wss:// for a browser off this host, and ws:// only on loopback.
OS_PRINT_CONSOLE_URLconsoleUrlThe console's URL as that browser reaches it, /_console included (http://127.0.0.1:3000/_console). A URL carrying credentials (user:password@) is refused.

A plugin option wins over its variable. At startup the plugin probes the engine — launches the executable or connects to the endpoint — and logs the placement and Chromium version. An engine that is not configured, is configured twice, or does not answer is reported once, at startup, with the setting to fix; every print is then refused until it is. The remote endpoint is never logged beyond its scheme and host, since it may carry a token.

Chinese, Japanese and Korean text prints with whatever fonts the browser's host has: install a CJK font there (for example fonts-noto-cjk), or those characters print as empty boxes.

The service is reached in-process, through the print service:

const print = kernel.getService<IPrintService>('print');

print.status();
// { state: 'ready', placement: 'local', version: '141.0.7390.37' }

const printed = await print.printRecordToPdf(
  { app: 'sales', object: 'invoice', recordId: 'inv_1', page: 'invoice_document' },
  context, // the requesting user's execution context
);
// { pdf: Uint8Array, size, filename: 'INV-0001.pdf', contentType: 'application/pdf' }

With no filename, the PDF is named after the record: its display name — the value of the object's title field (nameField, or the field derived from its fields) — plus .pdf, read from the record as the requesting user reads it. The name is made safe for a file: / \ : * ? " < > | become _, control characters and runs of whitespace become one space, leading dots are dropped, and it is cut to 100 characters. A record with no display value keeps <page>-<recordId>.pdf (invoice_document-inv_1.pdf). A filename in the request is used exactly as given, up to 255 characters; a longer one, or one that is not well-formed text (it holds a lone UTF-16 surrogate), is refused VALIDATION_ERROR / 400 before anything is rendered.

The page is rendered as the requesting user — never as the system — through a short-lived session minted for that user and revoked as soon as the print ends, whether it succeeded or not. A print asks one permission: the user must be able to read the record. A user who may read a record but not edit it prints it as anyone else does; a user who cannot read it is refused, and never learns whether it exists.

PrintServicePlugin also mounts one HTTP route on the kernel's HTTP server, POST /api/v1/print/records, so a user can print the record they are looking at. Its JSON body is the same request, { app, object, recordId, page, filename? }, and it answers 200 with the PDF itself as the body: Content-Type: application/pdf, Content-Disposition: attachment naming the file (an ASCII filename= and the RFC 5987 filename*=UTF-8''… form, so a name such as 报价单.pdf survives), and Cache-Control: no-store. A browser saves it as a download. The print runs as the signed-in caller, exactly as an in-process print with their context does. A refusal is the usual JSON error envelope.

A kernel that owns no HTTP server, such as an environment's kernel behind a shared host, reaches the same route through the runtime dispatcher: it forwards POST /api/v1/print/records to the print service's handlePrintDoor member, which runs the same handler and gives the same answers. A kernel that does not compose PrintServicePlugin answers NOT_IMPLEMENTED / 501 naming @objectstack/service-print. The console shows that refusal as one line in the user's language saying the action needs a service this environment does not have, never the package name. A SERVICE_UNAVAILABLE / 503 keeps the route's own sentence, since it can clear on a retry.

A declared type: 'api' action whose target is this route (the clicked record's id under recordIdParam: 'recordId', and app, object and page in bodyExtra) delivers the PDF: the REST action door relays the route's answer byte for byte, Content-Type and Content-Disposition included, and the console saves it as a download under the name that header gives. A PDF larger than the door's 32 MiB bound is the door's 502. The MCP action door does not carry a file: run_action on such an action answers 502. See Call it over REST.

The route refuses, before it asks the service anything: an anonymous request (UNAUTHENTICATED / 401); a sign-in held by an authentication policy (403 with the policy's own code); a request from an impersonation session — an administrator signed in as the user — (PERMISSION_DENIED / 403: a print signs a session in under the user's name, so it is never made for them by someone else); and a query parameter or a body field outside the request (VALIDATION_ERROR / 400). Every refusal below then reaches the caller with its own code and status; a 5xx answers with the route's own sentence, and the service's text is written to the server log. The route writes no audit row of its own: the print's session sign-in and sign-out are recorded as any sign-in is.

Refusals

Each refusal carries code and status, and every one of them is decided before a session is minted or a browser is started, in this order:

OrderConditioncode / status
1The caller is not a signed-in user acting for themselves (system, agent, service or guest principal; a sign-in held by an authentication policy)PERMISSION_DENIED / 403
2The engine is not ready (status() says why)SERVICE_UNAVAILABLE / 503
3No such pageRESOURCE_NOT_FOUND / 404
3The page is not a record page of the object (type: 'record', that object), or declares no printVALIDATION_ERROR / 400
4The record does not exist, or the caller cannot read itRECORD_NOT_FOUND / 404

An engine that did not answer its last probe is probed once more only after step 4, so no browser is started before every refusal above has had its say.

After those, a print can still fail as the render does: the page not rendering within the 30 s budget (TIMEOUT / 504). A failure to end the session afterwards never replaces the print's own outcome; it is logged, and the session expires on its own within 60 s.

On this page