80 lines
2.2 KiB
Python
80 lines
2.2 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""报表水印配置解析(对齐 JNPF preview 行为)"""
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
from datetime import datetime
|
|
from typing import Any, Dict, Optional
|
|
|
|
|
|
DEFAULT_WATERMARK_CONFIG: Dict[str, Any] = {
|
|
"content": "内部使用",
|
|
"fontSize": 32,
|
|
"color": "#B8B8B8",
|
|
"bold": False,
|
|
"italic": False,
|
|
"direction": "ltr",
|
|
"x": 80,
|
|
"y": 200,
|
|
"repeat": True,
|
|
"spacingX": 200,
|
|
"spacingY": 200,
|
|
"rotate": -45,
|
|
"opacity": 0.2,
|
|
"showTime": False,
|
|
"timeFormat": "yyyy-MM-dd",
|
|
}
|
|
|
|
|
|
def _format_watermark_time(fmt: str, now: Optional[datetime] = None) -> str:
|
|
dt = now or datetime.now()
|
|
mapping = {
|
|
"yyyy": "%Y",
|
|
"yyyy-MM": "%Y-%m",
|
|
"yyyy-MM-dd": "%Y-%m-%d",
|
|
"yyyy-MM-dd HH:mm": "%Y-%m-%d %H:%M",
|
|
"yyyy-MM-dd HH:mm:ss": "%Y-%m-%d %H:%M:%S",
|
|
}
|
|
py_fmt = mapping.get(fmt or "yyyy-MM-dd", "%Y-%m-%d")
|
|
return dt.strftime(py_fmt)
|
|
|
|
|
|
def resolve_watermark_config(
|
|
raw_config: Any,
|
|
*,
|
|
template_name: str = "",
|
|
now: Optional[datetime] = None,
|
|
) -> Dict[str, Any]:
|
|
"""合并默认项、填充 content,并按 showTime 追加时间文本。"""
|
|
base = copy.deepcopy(DEFAULT_WATERMARK_CONFIG)
|
|
if isinstance(raw_config, dict):
|
|
base.update({k: v for k, v in raw_config.items() if v is not None})
|
|
if not str(base.get("content") or "").strip():
|
|
base["content"] = template_name or DEFAULT_WATERMARK_CONFIG["content"]
|
|
if base.get("showTime"):
|
|
time_text = _format_watermark_time(str(base.get("timeFormat") or "yyyy-MM-dd"), now)
|
|
content = str(base.get("content") or "").strip()
|
|
base["content"] = f"{content} {time_text}".strip()
|
|
return base
|
|
|
|
|
|
def build_watermark_payload(
|
|
allow_watermark: bool,
|
|
raw_config: Any,
|
|
*,
|
|
template_name: str = "",
|
|
now: Optional[datetime] = None,
|
|
) -> Dict[str, Any]:
|
|
"""返回前端 Univer / 打印共用的 { show, config }。"""
|
|
if not allow_watermark:
|
|
return {"show": False, "config": {}}
|
|
return {
|
|
"show": True,
|
|
"config": resolve_watermark_config(
|
|
raw_config,
|
|
template_name=template_name,
|
|
now=now,
|
|
),
|
|
}
|