Tutorial: PDF layouts and documents
pgkiln makes PDFs in three ways, all drawn on the server without an extra print server:
| You want | Use |
|---|---|
| A report as a PDF list, with your paper, logo, header and footer | a report layout |
| A letter, invoice or sheet for one record, designed by you | a document template |
| A query's rows as a file (PDF, Excel, CSV …) from a button, without designing anything | a report query |
This tutorial does the first two in the Tasks app of the Tasks tutorial (page 1 My tasks, page 2 the task form) and ends with mailing and storing a document. Run examples/tasks-app.sql if you don't have it yet. The reference for every setting is chapter 16.
Step 1: the report as a PDF
Without doing anything, every interactive report can already print. Run the app, open My tasks and choose Actions → Download PDF. You get the rows as on screen (with the search, filters and sort you applied), a title, the column headings on every page and page n of m in the footer. Row level security applies: ann prints only her tasks.
Step 2: a report layout
Now make it look like yours. Open Shared Components → Report layouts → Create:
| Setting | Value |
|---|---|
| Name | TASKS_PRINT |
| Default | on (every report of the app uses it, unless it names another) |
| Paper / orientation | A4 / portrait |
| Font size / margins | 10 / 15 |
| Title | &REPORT_TITLE. |
| Header | Printed by &APP_USER. on &DATE. |
| Footer | &APP_NAME. · internal |
| Stretch to the page width | on |
| Heading color / stripes | #e8ecf2 / #f7f7f7 |
| Logo | a PNG or JPEG, printed at the top right of the first page |
Preview PDF shows the layout with sample data, so you can tune it before any report uses it. The texts take substitutions: &REPORT_TITLE., &APP_NAME., &APP_USER., &DATE., &TIMESTAMP., page items (&P1_STATUS.) and text messages (&APP_TEXT$NAME.).
The same in SQL:
insert into meta.report_layout (app_id, name, is_default, paper, orientation, font_size, margin_mm,
header, footer, full_width, stripe_color)
select id, 'TASKS_PRINT', true, 'A4', 'portrait', 10, 15,
'Printed by &APP_USER. on &DATE.', '&APP_NAME. · internal', true, '#f7f7f7'
from meta.app where alias = 'tasks';Download the PDF again: it has the new header, footer and colors.
Step 3: choose the columns to print
On paper you may want other columns than on screen, in another order. The report region's settings take a pdf object: the layout, the columns (including columns hidden on screen), widths in millimetres and alignment.
{
"pdf": {
"layout": "TASKS_PRINT",
"columns": ["title", "priority", "due_date"],
"widths": { "title": 100 },
"align": { "priority": "center" }
}
}Naming a layout here is only needed when the report should use another layout than the default one.
Step 4: a document template for one task
A report layout prints a list. For a document you design, such as a task sheet with a signature line, create a document template under Shared Components → Document templates → Create:
| Field | Value |
|---|---|
| Name | TASK_SHEET |
| Title | Task sheet |
| Report layout | TASKS_PRINT (paper, margins, logo and footer come from it) |
| File name | task-&P2_ID. (.pdf is added) |
Data (SQL): a SELECT with the page's items as binds. It runs as the application's database role, so grants and row level security apply: nobody prints someone else's task.
select t.id, t.title, initcap(t.priority) as priority, t.due_date, t.done, t.done_at, t.owner,
(select count(*)::int from tasks.task o where o.owner = t.owner and not o.done) as open_count
from tasks.task t
where t.id = :P2_ID::intTemplate (HTML): a subset of HTML with {{tags}} for the query's columns:
<img src="logo" align="right" width="30mm">
<h1>Task {{id}}</h1>
<p class="muted">{{owner}} · printed on {{TODAY|date}} by {{APP_USER}}</p>
<table>
<tr><th width="30%">Title</th><td>{{title}}</td></tr>
<tr><th>Priority</th><td>{{priority}}</td></tr>
<tr><th>Due</th><td>{{due_date|date|default:-}}</td></tr>
<tr><th>Status</th><td>{{#done}}Done on {{done_at|datetime}}{{/done}}{{^done}}Open{{/done}}</td></tr>
</table>
<p>{{owner}} has {{open_count}} open tasks.</p>
<p> </p>
<table class="plain">
<tr><td>Signed: ____________________</td><td align="right">Date: ____________</td></tr>
</table>The tags in short:
| Tag | Meaning |
|---|---|
{{title}} | a value, always HTML-escaped |
{{due_date|date}}, {{amount|number:2}} | filters: date, datetime, number[:decimals], upper, lower, default:text |
{{#done}}…{{/done}} | shown when the value is true or not empty; repeated for each item of a list |
{{^done}}…{{/done}} | shown when the value is false, empty or an empty list |
{{APP_USER}}, {{APP_NAME}}, {{TODAY}}, {{NOW}} | built in |
<img src="logo"> is the layout's logo. class="page-break" on a div starts a new page, and a table's header rows repeat on every page it runs over.
Preview PDF under the template asks for item values (P2_ID=1) and draws it as the application's role, in a transaction that is rolled back. The tags are checked when you save.
Step 5: a Print button
On page 2 add a button in the form region:
| Property | Value |
|---|---|
| Name | PRINT |
| Label | Print |
| Action | document |
| Document template | TASK_SHEET (Behaviour group) |
| Server-side condition | item_not_null P2_ID |
The button downloads the PDF filled with the page's values as they were loaded or last saved, so save a changed task before printing it. The condition hides it for a new task, which has nothing to print; to grey it out instead, see the conditions tutorial.
Any link can download it too: ?doc=TASK_SHEET on the page's URL (with the items' checksum like every link). The page's access rules apply, and the template's own Authorization on top: give it a scheme to let only some users print (buttons per role).
Step 6: a list with lines from one query
A document often needs a header and lines, like an invoice. Let the query return the lines as a json_agg column; the template repeats them. A Tasks overview for the signed-in user:
select meta.app_user() as who,
(select count(*)::int from tasks.task where not done) as open_count,
(select json_agg(json_build_object('title', title, 'priority', initcap(priority), 'due', due_date)
order by due_date nulls last)
from tasks.task where not done) as open_tasks<h1>Open tasks of {{who}}</h1>
{{#open_count}}
<table>
<thead><tr><th>#</th><th width="60%">Title</th><th>Priority</th><th>Due</th></tr></thead>
{{#open_tasks}}<tr><td>{{@index}}</td><td>{{title}}</td><td>{{priority}}</td><td>{{due|date|default:-}}</td></tr>{{/open_tasks}}
</table>
{{/open_count}}
{{^open_count}}<p class="muted">Nothing open. Nice work!</p>{{/open_count}}A section on a list repeats for each item, so the table is wrapped in the count ({{#open_count}}), not in the list itself. Save it as TASKS_OVERVIEW and add a document button for it on page 1. (Without a json column, all rows of the query are available as {{#rows}}…{{/rows}}.)
Step 7: mail it, or keep a copy
A document template is not only a download:
- As an e-mail attachment. A Send e-mail process attaches it with
"attachments": {"document": "TASK_SHEET", "items": {"P2_ID": "&P2_ID."}}; from SQL usemeta.document_pdf('TASK_SHEET', jsonb_build_object('P2_ID', 1))withmeta.add_mail_attachment(Sending e-mail). - As a file to keep.
meta.document_temp_file('TASK_SHEET', jsonb_build_object('P2_ID', :P2_ID), 'task-' || :P2_ID)in a process returns the id of a temporary file; from the next process on it is a PDF you can insert into a table of your own (chapter 16).
Fonts and limits
The built-in PDF fonts cover Western European languages; other characters print as ?. For other scripts set PDF_FONT and PDF_FONT_BOLD to TrueType fonts (DejaVu Sans, Noto Sans), which are embedded. A report PDF holds at most PDF_MAX_ROWS rows (default 5000).
The HR example has all of this: the layout HR_DIRECTORY for the Directory (examples/hr/hr_07_layouts.sql), the EMPLOYEE_SHEET template with a Print button on page 3 (examples/hr/hr_09_documents.sql) and Keep a copy (examples/hr/hr_109_document_temp_file.sql).