# Report templates (.ncr XML)

A report template is an XML file, usually `.ncr` (older ones `.xml`), written by NCReport Designer and read by the
engine. You can write and edit templates by hand, but **the reader skips unknown elements and attributes silently**: a
typo is never an error, it just does nothing. Use only the names below, and preview the result.

Guide: [Specification](https://docs.ncreport.org/ncreport/2.36/spec/specification.html),
[Expressions](https://docs.ncreport.org/ncreport/2.36/advanced/expressions.html),
[Variables](https://docs.ncreport.org/ncreport/2.36/advanced/variables.html),
[Data sources](https://docs.ncreport.org/ncreport/2.36/advanced/datasources.html).

## Skeleton

```xml
<?xml version="1.0" encoding="UTF-8"?>
<NCReport version="2.36.0" name="Orders" type="report">       <!-- type: report | textdoc | label -->
  <options>…</options>
  <datasources><datasource id="orders" type="sql" …>SELECT …</datasource></datasources>
  <variables><variable id="total" funcType="sum" scope="report" initValue="0">amount</variable></variables>
  <scripts><script id="isBig">$D{orders.amount} &gt; 1000</script></scripts>
  <pageheader id="PH" height="10">ITEMS</pageheader>
  <pagefooter id="PF" height="8">ITEMS</pagefooter>
  <reportheader id="RH" height="20">ITEMS</reportheader>
  <reportfooter id="RF" height="10">ITEMS</reportfooter>
  <details>
    <detail id="Detail1" height="5" datasource="orders">
      <items>ITEMS</items>
      <groups>
        <group id="byCustomer" groupExp="customer" resetVariables="custTotal">
          <groupheader id="GH_byCustomer" height="6">ITEMS</groupheader>
          <groupfooter id="GF_byCustomer" height="6">ITEMS</groupfooter>
        </group>
      </groups>
    </detail>
  </details>
</NCReport>
```

Structure rules:

- The root `version` must be `"2.0"` or higher (compared as a string); use the NCReport version.
- `<datasources>` must come **before** `<details>`: a detail looks up its data source while it is read.
- Page, report and group headers and footers hold items **directly**. A `<detail>` holds them in `<items>` and its
  groups in `<groups>`. Items placed directly under `<detail>`, or wrapped in `<items>` anywhere else, are lost.
- Several `<detail>` elements may follow each other; each runs over its own data source.
- Groups nest in the order listed, the first being the outermost.
- All geometry is in **millimetres** relative to the section (`posX posY width height`); fonts are in points;
  colors are `#RRGGBB`.

## Options

Each option is a child element of `<options>` whose text is the value:

```xml
<options>
  <encoding>UTF-8</encoding>
  <language>00</language>                       <!-- 00 = default; e.g. 00,de,hu for translated labels -->
  <orientation>portrait</orientation>           <!-- anything other than "portrait" means landscape -->
  <pagesize width="210.000" height="297.000">A4</pagesize>
  <topmargin>15</topmargin><bottommargin>15</bottommargin>
  <leftmargin>20</leftmargin><rightmargin>20</rightmargin>
  <fontname>Arial</fontname>
  <fontsize>10</fontsize>                       <!-- integer: "10.5" is read as 0 -->
  <doublePass>true</doublePass>                 <!-- $V{pagecount}; also needs a <pagefooter> -->
</options>
```

- Put `<orientation>` **before** `<pagesize>`. A known paper name (A0–A9, B0–B10, C5, COMM10E, DLE, EXECUTIVE,
  FOLIO, LEDGER, LEGAL, LETTER, TABLOID) ignores `width`/`height`; use `CUSTOM` for your own size.
- Option booleans count only the text `true`; `<doublePass>1</doublePass>` is **false**.
- Others: `backcolor`, `zoneSpacing`, `zoneBreak`, `subReportOnNewPage`, `subReportResetPageNo`, `dataTrimming`,
  `tocGen`, `fullPage`, `emptyValue`, `outputBaseName`, `htmlBodyStyle`, `htmlHead`, and for `type="label"`:
  `labelDirection`, `labelColumnCount`, `labelRowCount`, `labelWidth`, `labelHeight`, `labelHGap`, `labelVGap`.
  `columns` and `columnspace` are stored but do nothing.

## Data sources

```xml
<datasource id="orders" type="sql" source="static" openRole="begin" connection="internal" connID="default">
  SELECT id, customer, amount FROM orders WHERE year = $P{year} ORDER BY customer
</datasource>
```

| `type` | Data comes from | Type-specific attributes |
| --- | --- | --- |
| `sql` | A Qt SQL connection | `connection` (`internal` = a connection your application opened, `external` = the template's own), `connID` (connection name; empty or `default` = Qt's default connection), and for external: `driver host database user password port` |
| `txt` | Delimited text | `columnDelimiter` (`tab` default, `comma`, `semicolon`, `space`, `vbar`, `custom` + `customDelimChar`), `hasColumnHeader`, `encoding` |
| `xml` | NCReport data XML | — |
| `list` | `NCReport::addStringList(list, id)` | `listID`, `columnDelimiter` |
| `model` | `NCReport::addItemModel(model, id)` | `modelID`, `useFormatRoles` |
| `custom` | A C++ `NCReportDataSource` subclass added by the application | — |

Any other `type` (`itemmodel`, `stringlist`, `parameter`, …) is a hard "Invalid datasource type" error.

Common attributes: `id` (case-sensitive), `source` (`static` = the element text is the query or data, `file`,
`http`, `parameter` = the text is a parameter ID), `openRole` (`begin`, `child`, `group`, `sub`), `parentID`,
`allowEmpty`, `primaryKeyColumn`, `enabled`.

- A detail iterates over its `datasource`. A data source used by no detail supplies only its first row.
- SQL text may contain `$P{}` (and `$D{}` of a parent) references; they are substituted as text before the query
  runs, so quote string parameters yourself: `WHERE name = '$P{name}'`.
- Prefer `connection="internal"` and let the application open the database; then the template holds no password.

**Parent–child data (data relations):** the child has `openRole="child" parentID="orders"` and a query like
`… WHERE order_id = $D{orders.id}`. The detail must be bound to the **root parent** data source, fields use the
`ds.column` form, and there is one group level per data level (e.g. `groupExp="orders.id"`). Relations work for SQL
and model data sources only. Hide empty children with `printWhen="!$D{items.isEmpty()}"`.

## Items

Item tags: `label`, `field`, `text` (rich text/HTML/Markdown), `line`, `rectangle`, `ellipse`, `image`, `barcode`,
`crosstab`, `table` (table view), `graph` (custom item drawn by C++). There are no `html`, `tableview`, `subreport` or
`custom` tags.

Common attributes: `id`, `zValue`, `posX`, `posY`, `width`, `height`, `printWhen`, `pageBreakAfter`, `autoHeight`,
`canBreak`, `zoneID`, `dynPosX`, `dynPosY`, `dynWidth`, `dynHeight`; fonts: `fontName`, `fontSize`, `fontWeight`
(`light normal demibold bold black`), `fontItalic`, `fontUnderline`; `alignment` is an integer of Qt flags
(Left 1, Right 2, HCenter 4, Justify 8, Top 32, Bottom 64, VCenter 128, e.g. `33` = left+top, `34` = right+top);
pen and brush: `lineColor`, `lineStyle` (`solid dash dot dashdot dashdotdot none`), `lineWidth` (mm), `fillColor`,
`fillStyle` (`no solid …`). Item booleans accept `true` or `1`.

### label

```xml
<label id="L1" posX="0" posY="0" width="40" height="5" fontSize="12" fontWeight="bold" alignment="33">Invoice</label>
```

Also `forecolor`, `backcolor`, `bgMode` (`tr` = transparent), `rotation` (90 or 270 only), `wordbreak`, `elide`
(`none left mid right`). With `tr="true"` (translations) or `cf="true"` (conditional format) the text **must** be in
child elements: `<tr lang="00">Invoice</tr><tr lang="de">Rechnung</tr><cf>…</cf>`; bare text is then ignored.

### field

A field shows a value. `ftype` says where the value comes from and the element text says which one:

| `ftype` | Element text | Example |
| --- | --- | --- |
| `ds` | Column name, `[dsID.]column`, **without** `$D{}` | `<field ftype="ds" type="txt">orders.customer</field>` |
| `par` | Parameter ID | `<field ftype="par" type="txt">username</field>` |
| `var` | Variable ID | `<field ftype="var" type="num">total</field>` |
| `sys` | System variable name | `<field ftype="sys" type="num" arg="Page %1">pageno</field>` |
| `tpl` | Text with `$D{} $P{} $V{}` references | `<field ftype="tpl" type="txt">Page $V{pageno} of $V{pagecount}</field>` |
| `exp` | A whole script, **no** `<% %>` | `<field ftype="exp" type="txt">$D{qty} &gt; 0 ? "In stock" : "Out"</field>` |

The Designer also writes the matching `resource` (`datasource param var sysvar tpl exp`); `ftype` wins.
`type` is the data type: `txt num date datetime time bool img`.

Formatting: numbers need `formatting="true"` before `format` (`f e g`, `C` = currency with `localized`),
`precision`, `numwidth`, `localized`, `blankifzero` apply. Dates use `dateFormat` with QDate patterns
(`yyyy-MM-dd`, `MMMM`). `arg` wraps the value with a `QString::arg()` template. `hideRepeated` hides a value equal to
the previous row's (fields without `printWhen` only).

### text

Rich text. `resource="static"` with XML-escaped HTML as the text, or `datasource`, `file`, `url`. `template="true"`
substitutes `$D{}` references and `<% %>` scripts. `markdown="true"` treats the content as Markdown. To flow across
pages it needs `canBreak="true" autoHeight="true"` on the item, `autoHeight="true"` on its section and
`<zoneBreak>true</zoneBreak>` in the options.

### line, rectangle, ellipse

`line` uses `fromX fromY toX toY` (mm) instead of position and size. `rectangle` has `roundX roundY`.
Data-driven style: `dynFillColor`, `dynLineColor`, `dynLineWidth`; data-driven geometry with the `dyn*` attributes,
e.g. `dynWidth="&lt;%$D{amount}/10%&gt;"`.

### image

`resource`: `static` (Base64 in the text), `file`, `datasource`, `filefromds`, `url`, `urlfromds`, `param`.
`format`: `bin`, `b64`, `svg`. `aspectRatio`: `keep`, `expand`, `ignore`.

### barcode

```xml
<barcode id="B1" posX="0" posY="0" width="30" height="30" barcodeType="58" resource="datasource" showText="false">orders.url</barcode>
```

`barcodeType` is the Zint symbology number: 13 EAN (default), 20 Code 128, 58 QR Code, 71 Data Matrix, 55 PDF417;
the full table is in the guide's Barcodes chapter. Static value in `code`; dynamic value with `resource`
`datasource`, `param`, `tpl` or `exp` and the text. Zint options go in `opt1 opt2 opt3`, `secure`, `primary`;
`vers`, `cols`, `mode`, `scale` and `fontSize` have no effect.

### crosstab and table

Complex; copy the attribute set from a Designer-made template or the specification rather than writing it from memory.

## Expressions

References are replaced by their value **as text, before** any script runs:

| Reference | Value |
| --- | --- |
| `$D{ds.column}` | Column of the current row (`$D{column}` = the detail's data source) |
| `$D{ds.rowCount()}`, `isEmpty()`, `isNotEmpty()`, `isAvailable()` | Data source functions |
| `$P{name}` | Parameter from `NCReport::addParameter()` |
| `$V{name}` | User or system variable |
| `$F{fieldID}` | Displayed value of a field |
| `$S{scriptID}` | Result of a script in `<scripts>` |

Invalid references print `#DATA#`, `#PARAM#` or `#VAR#`.

- `<% … %>` embeds a script in templates, rich text, variables, `groupExp` and `dyn*` attributes. In XML, write it
  escaped: `&lt;% … %&gt;`. Escape `<`, `>` and `&` in all attribute values and texts.
- Scripts are ECMAScript, run by QJSEngine (always with Qt 6; QtScript on old Qt 5 builds). The value of the last
  statement is the result: `if ($D{qty} > 0) "yes"; else "no";`.
- **Quote string values** in scripts: `"$D{orders.status}" == "paid"`. Numbers need no quotes.
- `printWhen` on items and sections: a reference or script that gives true or false, e.g.
  `printWhen="$D{amount} &gt; 0"`, `printWhen="$V{pageno} &gt; 1"`, `printWhen="$S{isBig}"`.
- Conditional format (`cf="true"` with a `<cf>` child): one `property:value` per line, e.g.
  `color:{$D{amount} < 0 ? "#c00000" : "#000000"}`. Properties: `color`, `background-color`, `font-family`,
  `font-bold`, `font-italic`, `font-weight`, `font-underline`, `font-size`, `font-strikeout`, `letter-spacing`,
  `capitalization`.

## Variables

```xml
<variable id="custTotal" funcType="sum" scope="group" initValue="0">amount</variable>
```

- `funcType`: `count`, `sum`, `average`, `std`, `min`, `max` (not `avg`).
- `scope`: `report`, `page`, `group`. A group-scope variable is reset **only** when a group lists it in
  `resetVariables`.
- The text is a **bare column name** (`amount` or `orders.amount`), not `$D{amount}`; or a script
  `&lt;%$D{qty}*$D{price}%&gt;`.
- In a group footer the value includes the group's last row; the reset happens after the footer. For grand totals in
  the report footer use a `report` scope variable.

System variables (`$V{…}` or `ftype="sys"`, case-sensitive): `pageno`, `pagecount` (only with
`<doublePass>true</doublePass>` **and** a `<pagefooter>` section, which may be empty: `<pagefooter id="PF" height="5"/>`;
without a page footer the pages are not counted), `currentrow` (0-based), `reportno`, `reportcount`, `currentcopy`, `date`, `time`,
`datetime`, `appname`, `appversion`, `qtversion`, `os`, `lang`.

## Groups

```xml
<group id="byMonth" groupExp="$MONTH{order_date}" resetVariables="monthTotal" reprintHeader="true" startsOnNewPage="false">
```

`groupExp` is a **bare column name** (`customer`, `orders.customer`), `%CONST` (one group around all rows, for a
summary footer), a script `&lt;% … %&gt;`, or `$YEAR{col}`, `$MONTH{col}`, `$WEEK{col}`, `$DAY{col}`.
`groupExp="$D{customer}"` does **not** work (an example in the specification shows it; the group never breaks).
The data must be sorted by the group expression, e.g. by `ORDER BY` in the query.

Other attributes: `resetVariables` (comma-separated), `reprintHeader`, `startsOnNewPage`, `pageBreakExp`,
`resetPageNo`.

## Sections

Attributes of any section: `id`, `height` (mm), `autoHeight`, `printWhen`, `startsOnNewPage`, `hideIfBlank`,
`orphanedTolerance`, `anchorToPageFooter`, `altBackRowMode` (`odd`, `even`) with `altBackRowColor`, and on a detail
`pageBreakExp` and `repeatExp`.

## A complete small template

A static tab-separated data source, a monthly group with a header and footer, a group total and a parameter
(from the examples shipped with NCReport; the data rows are separated by tab characters):

```xml
<?xml version="1.0" encoding="UTF-8"?>
<NCReport version="2.13.2" name="Untitled" type="report">
    <options>
        <encoding>UTF-8</encoding>
        <language>00</language>
        <orientation>portrait</orientation>
        <pagesize width="210.000" height="297.000">A4</pagesize>
        <topmargin>15</topmargin>
        <bottommargin>15</bottommargin>
        <leftmargin>20</leftmargin>
        <rightmargin>20</rightmargin>
        <fontname>Ubuntu</fontname>
        <fontsize>10</fontsize>
    </options>
    <datasources>
        <datasource id="DataSource1" allowEmpty="true" type="txt" openRole="begin" source="static" columnDelimiter="tab" encoding="UTF-8">1654	2014-08-01
2554	2014-08-05
4520	2014-09-03
1280	2014-09-12</datasource>
    </datasources>
    <variables>
        <variable id="total" type="num" funcType="sum" scope="group" initValue="0">col0</variable>
    </variables>
    <pageheader id="PH" height="7.938">
        <label id="PQM57" zValue="0" posX="0.000" posY="0.000" width="61.912" height="5.027" fontName="Ubuntu" fontSize="12" fontWeight="bold" alignment="1">Sales grouped by month</label>
        <field id="VSB9B" zValue="1" posX="87.312" posY="0.000" width="82.550" height="4.762" resource="param" fontName="Ubuntu" fontSize="10" alignment="34" forecolor="#000000" type="txt" ftype="par">username</field>
    </pageheader>
    <pagefooter id="PF" height="9.525"/>
    <details>
        <detail id="Detail1" height="5.292" datasource="DataSource1">
            <items>
                <field id="VSB9C" zValue="0" posX="34.925" posY="0.000" width="31.750" height="4.762" resource="datasource" fontName="Ubuntu" fontSize="10" alignment="34" type="num" ftype="ds" formatting="true" numwidth="0" format="f" precision="2" localized="true">col0</field>
                <field id="UNBCE" zValue="1" posX="0.000" posY="0.000" width="31.750" height="4.762" resource="datasource" fontName="Ubuntu" fontSize="10" alignment="1" type="txt" ftype="ds">col1</field>
            </items>
            <groups>
                <group id="Group0" groupExp="$MONTH{col1}" resetVariables="total" reprintHeader="false" startsOnNewPage="false">
                    <groupheader id="GH_Group0" height="5.821">
                        <label id="7UHBR" zValue="0" posX="0.000" posY="0.000" width="12.700" height="4.762" fontName="Ubuntu" fontSize="10" alignment="1">Month:</label>
                        <field id="8FD9X" zValue="1" posX="12.700" posY="0.000" width="31.750" height="4.762" resource="datasource" fontName="Ubuntu" fontSize="10" fontWeight="bold" alignment="1" type="date" ftype="ds" dateFormat="MMMM">col1</field>
                    </groupheader>
                    <groupfooter id="GF_Group0" height="8.467">
                        <field id="0R2HF" zValue="0" posX="34.925" posY="3.175" width="31.750" height="4.762" resource="var" fontName="Ubuntu" fontSize="10" fontWeight="bold" alignment="34" type="num" ftype="var" formatting="true" numwidth="0" format="f" precision="2" localized="true">total</field>
                        <line id="KPYYQ" zValue="1" lineColor="#000000" lineStyle="solid" lineWidth="0.100" fromX="0.000" fromY="1.587" toX="68.263" toY="1.587"/>
                    </groupfooter>
                </group>
            </groups>
        </detail>
    </details>
</NCReport>
```

The source package ships many more in `reports/`; copy from one that does what you need.
