第 7 章 模板格式參考

Last Updated: 2026-10-25 02:54 Views: 9

第 7 章 模板格式參考

7.1 概覽與儲存

一個模板 = 一個 JSON 文件 + 資源檔案目錄(UTF-8,無二進位 內嵌,圖片等資源放旁邊路徑引用):

~/.wxprint/templates/<id>/
├── template.json      # 模板主文档(本规范)
├── waybill-scan.png   # 背景扫描底图(设计期参考)
└── stamp.png          # 模板自带图片资源
維度 套印模板(overlay) HTML 模板(html)
定位方式 元素絕對定位,毫米座標 文件流排版(HTML+CSS)
適用 預印單據套印、面單、標籤、票據 報表、對帳單、說明書
資料代入 元素內 {{變數}} Twig 模板({{ }} / {% for %})
分頁 每記錄一頁(按模板頁定義) 按頁高自動切片 + 分頁類別

模板三種來源:本地目錄(server 啟動掃描註冊)、POST /api/templates 上傳、列印時 URL 擷取(4.5 節)。

7.2 頂層欄位

欄位 類型 必填 說明
id string ✓ 模板唯一識別碼(目錄名),^[a-z0-9][a-z0-9._-]{0,63}$
name string ✓ 顯示名稱
kind string ✓ "overlay" / "html"
version int ✓ 格式版本,當前 1
page object ✓ 頁面定義(7.3 節)
background object 底圖與校準(7.9 節,僅 overlay)
elements array ✓ 元素清單(7.4 起,僅 overlay)
entry / assets string / array HTML 模板入口與資源(7.8 節)
calibration_offset object 模板級套印微調 {x, y} mm(疊加在印表機校準之上)
meta object 自由擴充(作者/備註/業務標識)

7.3 頁面定義 page

欄位 類型 預設 說明
width_mm / height_mm number — 實體紙寬/高,任意值(連續紙定長單據如 100×93.5;height_mm: 0 = 自適應內容高度,僅 overlay)
orientation string portrait portrait / landscape(交換寬高的便捷宣告)
continuous bool false 連續走紙:頁間無間隙,輸出層按自訂紙張大小走紙
margin_mm object 0 {top, bottom, left, right}:overlay 僅作設計器安全區提示;html 為內容盒邊距(頁面保持整頁)
size string — HTML 模板紙張預設("A4" 等,與 width/height 二選一)

座標系:原點 = 列印紙左上角實體頂點;x 向右、y 向下;單位 毫米,最多兩位小數(0.01mm 精度)。精度鏈路:模板座標 → ×72/25.4 → PDF pt(精確有理換算)→ 1:1 不縮放輸出 → 機械誤差 由印表機校準吸收(7.10 節)。

7.4 元素通用欄位

所有元素共有的欄位:

欄位 類型 預設 說明
type string ✓ text / line / rect / image / barcode / qrcode / table / chart
x, y, w, h number ✓ 元素框(mm)
rotate number 0 旋轉角度(度,順時針,繞框中心——斜排文字如銀行回單)
id string — 元素識別碼(錨點/引用用);無 id 按索引引用
scope string body page-header / page-footer(每頁重複繪製)、first-page / last-page(僅首頁/末頁)

7.5 text 文字

{ "type": "text", "x": 42.5, "y": 60.0, "w": 60, "h": 6,
  "text": "{{sender.name}} 收,{{sender.phone}}",
  "font": { "family": "", "size_pt": 10, "weight": 400, "italic": false,
            "color": "#000000", "letter_spacing_em": 0, "line_height": 1.2 },
  "align": "left", "valign": "top", "origin": "top-left", "overflow": "shrink" }
欄位 類型 預設 說明
text string ✓ 內容:變數 + 過濾器 + 字面常值;\n 換行
font.family string "" 空 = 系統預設字型堆疊(與 HTML 管線同堆疊);可寫備選清單
font.size_pt number 10 字級(磅——印刷慣例,mm 座標與 pt 字級並存是套印行業習慣)
font.weight int 400 字重;700 = 粗體
font.italic / font.underline bool false 斜體 / 底線
font.color string "#000000" 前景色 #rrggbb
font.background string null 背景色 #rrggbb;null = 透明(不繪製背景)
font.letter_spacing_em number 0 字距(em 倍數)
font.line_height number 1.2 行高倍數(overflow: wrap 時生效)
align string left left / center / right(框內水平)
valign string top top / middle / bottom(框內垂直)
origin string top-left top-left = y 是框頂邊;baseline = y 是首行文字基線——貼齊表格線時字精確落在線內,不受字級行高微調影響(發票金額欄、憑證格子)
overflow string shrink shrink(建議,二分法縮小字級至放得下,可設最小字級)/ clip / wrap

7.6 變數與過濾器

  • 語法 {{path}};點路徑 {{a.b.c}},陣列索引 {{items.0.qty}}。
  • 過濾器鏈 {{v|f1|f2:arg}}:
過濾器 範例 說明
date {{created_at\|date:"Y-m-d H:i"}} PHP/Twig 格式符(Y m d H i s),時間戳或 ISO 字串入
number {{amount\|number:2}} 小數位 + 千分位;負參 = 僅小數位
upper / lower {{name\|upper}} 大小寫
default {{remark\|default:"--"}} 空值保底
truncate {{addr\|truncate:20}} 超長截斷加 …
pad {{no\|pad:8}} 左補零到固定位(單號常用)
  • 內建頁碼變數 {{page}} / {{pages}}(當前頁/總頁數):僅 scope: page-header/page-footer 元素內有效。
  • 缺失變數:渲染為空字串並在作業 warnings 中列出(4.7 節)。
  • 套印文字不做 HTML 跳脫(非 HTML 語境);HTML 管線預設跳脫、 |raw 放行。

7.7 line / rect / image / table / chart

{ "type": "line", "x": 10, "y": 55, "w": 190, "h": 0,
  "stroke_mm": 0.3, "color": "#000000", "dash": [2, 1] }
{ "type": "rect", "x": 10, "y": 15, "w": 190, "h": 35,
  "stroke_mm": 0.3, "fill": null, "corner_mm": 1 }
{ "type": "image", "x": 5, "y": 5, "w": 20, "h": 20,
  "src": "stamp.png", "fit": "contain" }
{ "type": "table", "x": 10, "y": 100, "w": 190,
  "columns": [
    { "header": "品名", "key": "name", "width": 0.5, "align": "left" },
    { "header": "数量", "key": "qty", "width": 0.2, "align": "right" } ],
  "rows": "{{items}}", "row_height_mm": 6, "header_rows": 1,
  "grid": { "stroke_mm": 0.2, "color": "#000000" },
  "font": { "size_pt": 9 } }
元素 欄位要點
line stroke_mm 線寬、color、dash 虛線模式(如 [2,1])
rect stroke_mm 邊框、fill 填色(null = 透明)、corner_mm 圓角、邊框色
image src:模板資源相對路徑 / http(s) / data: URL(列印期擷取受大小/逾時限制);fit:contain 等比例 / stretch 延展
table columns[].width 為欄寬佔比(合計=1±0.001);rows 綁定陣列;儲存格支援變數與過濾器;斑馬紋 odd_color/even_color;v1 固定列高不跨頁(超列截斷 + warning),跨頁長表格用 HTML 管線
chart kind:bar/hbar/line/pie/funnel/gauge/radar/scatter/histogram/candlestick/parallel/polar_bar/theme_river(13 種);categories/series 資料綁定;show_legend/title/theme

7.8 barcode / qrcode 與 HTML 模板

條碼與 QR Code:

{ "type": "barcode", "symbology": "code128", "x": 10, "y": 20, "w": 80, "h": 12,
  "content": "{{order.no}}", "show_text": true, "text_size_pt": 7 }
{ "type": "qrcode", "x": 170, "y": 20, "size": 22, "content": "{{order.url}}",
  "ec_level": "M", "quiet_zone_mm": 2 }
欄位 說明
symbology code128 / ean13 / ean8 / code39 / itf14 / upca;向量路徑繪製,無點陣圖鋸齒
w / h(條碼)、size(QR Code) 目標實體尺寸(mm);模組寬度自動取整到裝置像素避免條碼模糊
ec_level QR Code 錯誤修正:L(7%) / M(15%) / Q(25%) / H(30%)
quiet_zone_mm QR Code 靜區邊距

HTML 模板(kind: "html"):

{ "id": "monthly-report", "kind": "html", "entry": "report.html.twig",
  "engine": "twig",
  "assets": ["styles.css", "logo.png"],
  "page": { "size": "A4", "margin_mm": { "top": 15, "bottom": 15,
            "left": 12, "right": 12 } },
  "sample_data": "sample.json" }
  • entry 為 Twig 模板:{{ }} 插值、{% for %} / {% if %} 控制、常用過濾器(date、number_format、nl2br、raw、 escape)與 include 函式。資料載入全部在伺服器端完成, 模板內無任何 JS(<script> 一律忽略)。
  • 分頁控制:CSS 類別 .wxprint-page-break(元素前強制斷頁)、 .wxprint-avoid-break(列級防孤行)。
  • CSS 支援現代子集:盒模型、表格、flex、float、字型/顏色/背景、 斑馬紋等;不支援 @page 分頁媒體(用分頁類別)。

7.9 底圖校準(設計期)

底圖僅在設計器內提供”描紅”參考;校準建立像素→毫米映射後, 拖放座標直接就是實體毫米。三種模式按掃描品質遞進:

模式 輸入 換算 適用
physical-size 掃描圖實際實體寬/高 mm 等比例 px_per_mm = img_px_w / width_mm 無歪斜的規整掃描
reference 圖上一條已知實體長度的線段(兩點) px_per_mm = 兩點像素距 / 已知 mm 有已知尺寸參考物
affine-3pt ≥3 個點及其實體 mm 座標 解 2D 仿射 6 參數(>3 點最小平方法) 歪斜/透視掃描矯正
"background": {
  "image": "waybill-scan.png",
  "calibration": { "type": "affine-3pt", "points": [
    { "px": [18, 22],   "mm": [0, 0] },
    { "px": [2010, 25], "mm": [209.8, 0.3] },
    { "px": [21, 2831], "mm": [0.2, 296.5] } ] },
  "opacity": 0.6, "print": false }

print: false(預設)= 套印語義,底圖不列印;true 僅用於 打樣校對。校準結果連同原始輸入存入模板,執行期不需要底圖參與。

7.10 印表機校準(執行期)

每台印表機校準(吸收機械重複性 ±0.1~0.3mm 的系統性偏差):

~/.wxprint/calibration/<printer>.json
{ "offset_mm": { "x": 0.35, "y": -0.20 }, "scale": { "x": 1.0002, "y": 1.0002 } }

來源:POST /api/printers/{name}/calibration-page 列印校準頁(十字 規線 + mm 標尺網格)→ 量測偏差 → PUT /api/printers/{name}/ calibration 寫入(端點見 4.10 節)。渲染前對全部元素座標 p' = offset + scale·p。

渲染疊加順序:模板座標 → 印表機校準(全域)→ 模板級 calibration_offset({x, y} mm,個別單據對特定機的微調)。

7.11 校驗規則(上傳/註冊時執行)

  • id 命名規則(^[a-z0-9][a-z0-9._-]{0,63}$);
  • 語義檢查(Template::warnings):座標/尺寸合法性、欄寬合計、 未命中變數等,以 warning 清單隨註冊回應與作業回傳(不阻斷);
  • id 非法或目錄建立失敗回傳 E_TEMPLATE_INVALID。

7.12 完整範例(快遞面單,連續紙)

{
  "id": "sf-waybill-100x93",
  "name": "顺丰面单 100×93.5 连续纸",
  "kind": "overlay",
  "version": 1,
  "page": { "width_mm": 100, "height_mm": 93.5, "continuous": true },
  "background": {
    "image": "scan.png",
    "calibration": { "type": "physical-size", "width_mm": 100, "height_mm": 93.5 },
    "print": false },
  "elements": [
    { "type": "barcode", "symbology": "code128", "x": 8, "y": 6, "w": 60, "h": 10,
      "content": "{{waybill_no}}", "show_text": false },
    { "type": "qrcode", "x": 74, "y": 4, "size": 18, "content": "{{pickup_url}}",
      "ec_level": "M" },
    { "type": "text", "x": 8, "y": 20, "w": 40, "h": 5, "origin": "baseline",
      "text": "{{receiver.name}}  {{receiver.phone}}",
      "font": { "size_pt": 9, "weight": 700 } },
    { "type": "text", "x": 8, "y": 26, "w": 84, "h": 10, "overflow": "shrink",
      "text": "{{receiver.province}}{{receiver.city}}{{receiver.district}}{{receiver.addr}}",
      "font": { "size_pt": 9 } },
    { "type": "table", "x": 8, "y": 40, "w": 84, "row_height_mm": 5.5,
      "header_rows": 1,
      "columns": [
        { "header": "物品", "key": "name", "width": 0.6 },
        { "header": "数量", "key": "qty", "width": 0.2, "align": "right" },
        { "header": "保价", "key": "insured", "width": 0.2, "align": "right" } ],
      "rows": "{{items}}" },
    { "type": "text", "x": 8, "y": 88, "w": 50, "h": 4, "origin": "baseline",
      "text": "{{printed_at|date:\"Y-m-d H:i\"}} 寄件 {{sender.name}}",
      "font": { "size_pt": 7 } }
  ]
}
← Previous Article 第 6 章 命令式腳本 API 參考 Next Article → 第 8 章 列印設計器

Comments

No comments yet