Odoo 打印 A4 紙時內容不從紙張頂端開始,核心是系統默認紙張格式的上邊距、頁眉間距、QWeb 布局結構、wkhtmltopdf 渲染規則共同疊加的結果,和普通瀏覽器打印原理不同。
一、核心原因(Odoo 特有)
默認紙張格式的上邊距(最主要)
Odoo 內置 A4 紙張格式(report.paperformat)默認上邊距(margin_top)約 40mm,頁眉間距(header_spacing)約 35mm。這是系統預設的安全值,內容從該邊距下方開始渲染,而非物理紙頂。
頁眉與內容的雙層間距
Odoo 報表分三層:頁眉(header)→ 頁眉間距(header_spacing)→ 正文(page)。默認 35mm 的header_spacing專門預留頁眉與正文的間隔,進一步推高正文位置。
QWeb 布局模板的固定結構
報表模板(如web.external_layout)強制包含header、page、footer區塊,即使隱藏頁眉,布局仍會保留頁眉容器的占位空間。
wkhtmltopdf 渲染限制
Odoo 用wkhtmltopdf將 HTML 轉 PDF,它會嚴格遵循 Odoo 紙張格式的邊距參數,且多數打印機有物理不可打印邊距(約 3–5mm),無法完全消除頂部空白。
報表模板自身的 CSS 邊距
模板中body或page容器可能有默認margin-top,與系統邊距疊加。
二、快速解決:調整紙張格式(后臺操作)
1. 進入紙張格式設置(需開啟調試模式)
開啟開發者模式(設置 → 激活開發者模式)。
進入:設置 → 技術 → 報告 → 紙張格式。
找到默認的A4格式,或新建自定義格式。
2. 修改關鍵參數(直接生效)
上邊距(margin_top):從 40mm 改為0–5mm(建議 5mm 兼容打印機)。
頁眉間距(header_spacing):從 35mm 改為0(無頁眉時)。
頁眉線(header_line):取消勾選(隱藏頁眉分隔線)。
保存后,重啟 Odoo 服務使設置生效。
3. 綁定到指定報表(可選)
在紙張格式的關聯報表字段,選擇要應用的報表(如銷售訂單、發票),避免影響全局。
三、前端定制:QWeb 模板優化(徹底可控)
1. 自定義紙張格式(XML)
在模塊中創建新紙張格式,覆蓋默認值:
xml
<record id="report_paperformat_a4_tight" model="report.paperformat">
<field name="name">A4 緊湊(無邊距)</field>
<field name="format">A4</field>
<field name="margin_top">5</field> <!-- 頂部5mm -->
<field name="margin_bottom">10</field>
<field name="margin_left">10</field>
<field name="margin_right">10</field>
<field name="header_spacing">0</field> <!-- 無頁眉間距 -->
<field name="header_line" eval="False"/>
<field name="dpi">90</field>
</record>
2. 報表模板綁定新格式
在報表動作(ir.actions.report)中指定紙張格式:
xml
<record id="action_report_saleorder" model="ir.actions.report">
<field name="name">銷售訂單</field>
<field name="model">sale.order</field>
<field name="report_name">sale.report_saleorder</field>
<field name="paperformat_id" ref="your_module.report_paperformat_a4_tight"/>
</record>
3. 清除模板內邊距(CSS)
在報表模板中加入打印樣式,清除容器默認邊距:
xml
<template id="report_saleorder_document">
<t t-call="web.html_container">
<t t-foreach="docs" t-as="doc">
<div class="page" style="margin-top: 0 !important; padding-top: 0 !important;">
<!-- 報表內容 -->
</div>
</t>
</t>
<style type="text/css" media="print">
@page { margin: 0; }
body { margin: 0; padding: 0; }
.page { margin-top: 0 !important; }
</style>
</template>
四、常見問題排查
頂部仍有空白:檢查wkhtmltopdf版本(建議 0.12.5+),低版本可能不兼容邊距設置。
頁眉被裁剪:若保留頁眉,margin_top需≥頁眉高度,header_spacing≥5mm。
內容溢出:調整margin_top后,適當縮小內容縮放比例(Odoo 打印預覽中設置)。
五、總結
內容不從頂端開始 = Odoo 默認 margin_top(40mm)+ header_spacing(35mm)+ 布局占位 + 打印機物理邊距。
最快修復:后臺將 A4 格式的margin_top 設為 5mm、header_spacing 設為 0。
徹底可控:自定義紙張格式 + 報表模板綁定 + CSS 清除內邊距。