Files
37duAutomation/libs/printkit/printkit/sheet.py
T
puddy 94e73a29c5 feat(sdk): 新增 erpsdk 0.1.5 与 printkit 0.1.0
- erpsdk:金蝶云星空(K3Cloud)WebAPI 通用 SDK——账套/组织/AppSecret 登录、
  会话复用、单据查询与读写(Save/Submit/Audit/删除/下推/分配/工作流审批)、
  分组维护、即时库存、报表取数(分页),内置新旧两套 ERP 站点
- printkit:网络打印机直连(IPP over TLS,无驱动无弹窗)——内置 EPSON
  L6570/L565,PDF/图片格式化、Excel·WPS 表格按列过滤排版分页、
  Validate-Job 干跑校验、设备能力预检与参数降级
- 均按 SDK 形态供给:sdk.json / api.json / pyproject.toml / _selftest.py
2026-11-16 11:27:33 +08:00

429 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""Excel / WPS 工作表 → 矢量 PDF(自己排版,不依赖 WPS 导出)。
为什么要自己排版
----------------
现场 WPS 12.1 的 ``ExportAsFixedFormat`` 有排版 bug:内容流里
``0.05 0 0 -0.05 Tm`` 配 ``220 Tf``(字号正常 ≈11pt),但单元格裁剪框只有
``8.5 x 2.3pt``,整表被压到原尺寸的 1/6,且与 PrintArea / Zoom / PrintQuality
全部无关。所以这里直接读单元格值与样式、自己画表格,输出稳定可控。
依赖:``openpyxl``(读 xlsx)、``pymupdf``(出 PDF)。
"""
from __future__ import annotations
import datetime as _dt
import math
import re
from io import BytesIO
from pathlib import Path
try:
import pymupdf as _mu
except ImportError: # pragma: no cover
import fitz as _mu
from .errors import PrintKitError
FONT_CANDIDATES = [
(r"C:\Windows\Fonts\msyh.ttc", r"C:\Windows\Fonts\msyhbd.ttc"),
(r"C:\Windows\Fonts\simsun.ttc", r"C:\Windows\Fonts\simhei.ttf"),
]
A4_W, A4_H = 595.28, 841.89
ERR_RE = re.compile(r"^#(REF!|N/A|VALUE!|DIV/0!|NAME\?|NULL!|NUM!|GETTING_DATA)$", re.I)
ERR_WORDS = {"错误", "error", "#error"}
CLOSERS = "))】]},,。.、;;::!!??%"
NUM_RE = re.compile(r"^-?[\d,]+(\.\d+)?%?$")
# --------------------------------------------------------------------------- #
# 取值与过滤
# --------------------------------------------------------------------------- #
def fmt_value(v) -> str:
"""单元格值 → 可打印文本。"""
if v is None:
return ""
if isinstance(v, _dt.datetime):
return v.strftime("%Y-%m-%d") if (v.hour, v.minute) == (0, 0) else v.strftime("%Y-%m-%d %H:%M")
if isinstance(v, _dt.date):
return v.strftime("%Y-%m-%d")
if isinstance(v, bool):
return "是" if v else "否"
if isinstance(v, float):
return str(int(v)) if v.is_integer() else f"{v:g}"
return str(v)
def is_bad(v) -> bool:
"""空 / 0 / Excel 错误值 / 文本"错误" → 视为无效行。"""
if v is None:
return True
if isinstance(v, str):
s = v.strip()
return s == "" or s == "0" or bool(ERR_RE.match(s)) or s.lower() in ERR_WORDS
if isinstance(v, (int, float)) and not isinstance(v, bool):
return v == 0
return False
def find_column(ws, key: str, header_row: int) -> int:
"""按字段名(第 1 行)/ 中文标题(header_row)/ 列字母定位列号。"""
from openpyxl.utils import column_index_from_string
if key and re.fullmatch(r"[A-Za-z]{1,3}", key):
return column_index_from_string(key.upper())
for r in (1, header_row):
for c in range(1, ws.max_column + 1):
v = ws.cell(row=r, column=c).value
if v is not None and str(v).strip() == key:
return c
for r in (1, header_row):
for c in range(1, ws.max_column + 1):
v = ws.cell(row=r, column=c).value
if v is not None and key.lower() in str(v).lower():
return c
raise PrintKitError(f"工作表里找不到列 {key!r}")
# --------------------------------------------------------------------------- #
# 排版
# --------------------------------------------------------------------------- #
class TablePDF:
def __init__(self, title: str = "", fontsize: float = 9.0,
margin: float = 42.0, landscape: bool = False):
regular, bold = self._pick_fonts()
self.font_r = _mu.Font(fontfile=regular) if regular else _mu.Font("china-s")
self.font_b = _mu.Font(fontfile=bold) if bold else self.font_r
self.fontfile_r, self.fontfile_b = regular, bold
self.title = title
self.fs = fontsize
self.margin = margin
self.doc = _mu.open()
self.W, self.H = (A4_H, A4_W) if landscape else (A4_W, A4_H)
self.page = None
self.y = 0.0
self.page_no = 0
self.cont = True
self._new_page()
@staticmethod
def _pick_fonts() -> tuple[str | None, str | None]:
for reg, bold in FONT_CANDIDATES:
if Path(reg).exists():
return reg, (bold if Path(bold).exists() else reg)
return None, None
def _new_page(self):
self.page = self.doc.new_page(width=self.W, height=self.H)
if self.fontfile_r:
self.page.insert_font(fontname="cjk", fontfile=self.fontfile_r)
if self.fontfile_b:
self.page.insert_font(fontname="cjkb", fontfile=self.fontfile_b)
self.page_no += 1
self.y = self.margin
if self.title:
self.page.insert_text((self.margin, self.y + 14), self.title,
fontname="cjkb", fontsize=self.fs + 5)
self.y += 34
def _measure(self, text: str, bold: bool = False, size: float | None = None) -> float:
f = self.font_b if bold else self.font_r
return f.text_length(text, fontsize=size or self.fs)
def _wrap(self, text: str, width: float, bold: bool = False,
size: float | None = None) -> list[str]:
if not text:
return [""]
size = size or self.fs
lines, cur = [], ""
for ch in text:
if self._measure(cur + ch, bold, size) <= width:
cur += ch
continue
if cur and ch in CLOSERS: # 禁则:收尾标点不另起一行
lines.append(cur + ch)
cur = ""
continue
if cur and ch not in " ":
m = re.search(r"[A-Za-z0-9_#%\.\-]+$", cur)
if m and ch.isalnum(): # 英文单词不硬拆
keep = cur[:m.start()]
if keep:
lines.append(keep)
cur = cur[m.start():] + ch
continue
lines.append(cur)
cur = "" if ch == " " else ch
lines.append(cur)
return lines or [""]
def table(self, header_rows: list[list[str]], rows: list[list[str]],
total_row: list[str] | None = None):
avail = self.W - 2 * self.margin
n = len(header_rows[0])
fs = self.fs
pad = 3.0
# 英文字段行放不下就自动缩字号(不低于 6pt)
fs_key = max(6.0, fs * 0.86)
cap = max(120.0, avail / n * 2.2)
floor = max(34.0, min(56.0, avail / n * 0.55))
def natural(key_size: float) -> list[float]:
out = []
for i in range(n):
w = 0.0
for bi, hr in enumerate(header_rows):
sz = key_size if bi == 0 else fs
w = max(w, self._measure(hr[i], bold=True, size=sz) + 12)
for r in rows[:400]:
w = max(w, self._measure(r[i], size=fs) + 12)
out.append(min(w, cap))
return out
def fit(nat: list[float]) -> list[float]:
w = [x * avail / (sum(nat) or 1.0) for x in nat]
for _ in range(5):
low = [i for i, x in enumerate(w) if x < floor]
if not low:
break
if len(low) == n:
return [avail / n] * n
rest = avail - floor * len(low)
high = [i for i in range(n) if i not in low]
htot = sum(w[i] for i in high) or 1.0
for i in high:
w[i] = w[i] * rest / htot
for i in low:
w[i] = floor
if all(w[i] >= floor for i in high):
break
return w
nat = natural(fs_key)
while sum(nat) > avail and fs_key > 6.0:
fs_key *= 0.94
nat = natural(fs_key)
widths = fit(nat)
lh = fs * 1.45
bottom = self.H - self.margin - 14
title_h = 34.0 if self.title else 0.0
bands = []
for bi, hr in enumerate(header_rows):
sz = fs_key if bi == 0 else fs
wrapped = [self._wrap(hr[i], widths[i] - 2 * pad, bold=True, size=sz) for i in range(n)]
bands.append((wrapped, max(len(x) for x in wrapped) * sz * 1.45 + 2 * pad, sz))
header_h = sum(h for _, h, _ in bands)
max_lines = max(1, int((bottom - (self.margin + title_h) - header_h) // lh) - 1)
prepared = []
for row in rows:
cells = [self._wrap(row[i], widths[i] - 2 * pad) for i in range(n)]
over = [j for j in range(n) if len(cells[j]) > max_lines]
if over:
cells = [c[:max_lines] for c in cells]
for j in over:
cells[j][-1] += "…"
prepared.append((cells, max(len(c) for c in cells) * lh + 2 * pad))
aligns = []
for i in range(n):
vals = [r[i].strip() for r in rows if r[i].strip()]
aligns.append("right" if vals and all(NUM_RE.match(v) for v in vals) else "left")
regions: list[list] = []
open_region: list = [None]
def start_region():
if open_region[0] is None:
open_region[0] = [self.page.number, self.y, None]
def close_region():
if open_region[0] is not None:
open_region[0][2] = self.y
regions.append(open_region[0])
open_region[0] = None
def page_break():
close_region()
self._new_page()
def draw_header():
if self.y + header_h > bottom:
page_break()
start_region()
y0 = self.y
for bi, (wrapped, h, sz) in enumerate(bands):
self.page.draw_rect(_mu.Rect(self.margin, y0, self.margin + avail, y0 + h),
color=None,
fill=(0.87, 0.87, 0.87) if bi == 0 else (0.94, 0.94, 0.94))
x = self.margin
for i in range(n):
ty = y0 + pad + sz
for ln in wrapped[i]:
self.page.insert_text((x + pad, ty), ln, fontname="cjkb", fontsize=sz)
ty += sz * 1.45
x += widths[i]
y0 += h
self.page.draw_line(_mu.Point(self.margin, y0),
_mu.Point(self.margin + avail, y0), color=(0, 0, 0), width=0.6)
self.y = y0
def draw_row(cells, h, bold=False):
x = self.margin
for i in range(n):
ty = self.y + pad + fs
for ln in cells[i]:
tx = x + pad
if aligns[i] == "right":
tx = x + widths[i] - pad - self._measure(ln, bold, fs)
self.page.insert_text((tx, ty), ln,
fontname="cjkb" if bold else "cjk", fontsize=fs)
ty += lh
x += widths[i]
self.page.draw_line(_mu.Point(self.margin, self.y + h),
_mu.Point(self.margin + avail, self.y + h),
color=(0, 0, 0), width=1.2 if bold else 0.6)
self.y += h
draw_header()
for ri, (cells, h) in enumerate(prepared):
if self.y + h > bottom:
page_break()
draw_header()
if ri % 2 == 1:
self.page.draw_rect(_mu.Rect(self.margin, self.y, self.margin + avail, self.y + h),
color=None, fill=(0.965, 0.965, 0.965))
draw_row(cells, h)
if total_row:
tc = [self._wrap(total_row[i], widths[i] - 2 * pad, bold=True) for i in range(n)]
th = max(len(c) for c in tc) * lh + 2 * pad
if self.y + th > bottom:
page_break()
draw_header()
self.page.draw_rect(_mu.Rect(self.margin, self.y, self.margin + avail, self.y + th),
color=None, fill=(0.90, 0.90, 0.90))
draw_row(tc, th, bold=True)
close_region()
# 每页补竖线与外框
for pno, top, bot in regions:
pg = self.doc[pno]
x = self.margin
for i in range(n - 1):
x += widths[i]
pg.draw_line(_mu.Point(x, top), _mu.Point(x, bot), color=(0, 0, 0), width=0.6)
pg.draw_rect(_mu.Rect(self.margin, top, self.margin + avail, bot),
color=(0, 0, 0), width=0.8)
def footer(self, text: str):
for i, p in enumerate(self.doc):
t = text.replace("{page}", str(i + 1)).replace("{total}", str(len(self.doc)))
if self.cont and i > 0:
t = "(续)" + t
p.insert_text((self.W / 2 - self._measure(t) / 2, self.H - 22), t,
fontname="cjk", fontsize=8, color=(0.35, 0.35, 0.35))
def to_bytes(self) -> bytes:
buf = BytesIO()
try:
self.doc.subset_fonts() # 只嵌用到的字形,否则整份 ttc 会进去(几十 MB)
except Exception: # noqa: BLE001
pass
self.doc.save(buf, garbage=4, deflate=True)
self.doc.close()
return buf.getvalue()
# --------------------------------------------------------------------------- #
# 对外入口
# --------------------------------------------------------------------------- #
def read_rows(src, sheet: str | None = None, col: str | None = None,
header_row: int = 2, key_row: int | None = 1,
drop_bad: bool = True) -> tuple[list[list[str]], list[list[str]]]:
"""读取工作表,返回 (表头行列表, 数据行列表)。"""
import openpyxl
path = Path(src)
if not path.exists():
raise PrintKitError(f"文件不存在: {path}")
try:
wb = openpyxl.load_workbook(path, data_only=True)
except Exception as e: # noqa: BLE001
raise PrintKitError(f"打开工作簿失败: {e}") from e
try:
if sheet:
if sheet not in wb.sheetnames:
raise PrintKitError(f"没有工作表 {sheet!r},可选: {wb.sheetnames}")
ws = wb[sheet]
else:
ws = wb.active
ci = find_column(ws, col, header_row) if col else None
hr_list = sorted({r for r in (key_row, header_row) if r and r >= 1})
header_rows = []
for r in hr_list:
line = [fmt_value(ws.cell(row=r, column=c).value) for c in range(1, ws.max_column + 1)]
header_rows.append([v if v.strip() else f"列{c}"
for c, v in enumerate(line, 1)])
rows = []
for r in range(max(hr_list) + 1, ws.max_row + 1):
if ci and drop_bad and is_bad(ws.cell(row=r, column=ci).value):
continue
vals = [fmt_value(ws.cell(row=r, column=c).value) for c in range(1, ws.max_column + 1)]
if not any(v.strip() for v in vals):
continue
rows.append(vals)
return header_rows, rows
finally:
wb.close()
def total_of(rows: list[list[str]], ncol: int) -> list[str]:
"""数字列求和,生成合计行。"""
row = ["合计"] + [""] * (ncol - 1)
for i in range(1, ncol):
nums, ok = [], True
for r in rows:
sv = r[i].strip().replace(",", "")
if sv == "":
continue
try:
nums.append(float(sv))
except ValueError:
ok = False
break
if ok and nums:
s = sum(nums)
has_dec = any("." in r[i] for r in rows)
row[i] = f"{s:,.2f}" if has_dec else f"{int(round(s)):,}"
return row
def render_table(header_rows: list[list[str]], rows: list[list[str]],
title: str = "", total: bool = False, landscape: bool = False,
fontsize: float = 9.0) -> bytes:
pdf = TablePDF(title=title, fontsize=fontsize, landscape=landscape)
pdf.table(header_rows, rows,
total_row=total_of(rows, len(header_rows[0])) if total and rows else None)
pdf.footer(f"共 {len(rows)} 行 · 第 {{page}} / {{total}} 页")
return pdf.to_bytes()
def build_pdf(src, sheet: str | None = None, col: str | None = None,
header_row: int = 2, key_row: int | None = 1, title: str = "",
drop_bad: bool = True, total: bool = False,
landscape: bool = False, fontsize: float = 9.0) -> bytes:
"""Excel/WPS → 矢量 PDF 字节流(不落盘、不打印)。"""
header_rows, rows = read_rows(src, sheet, col, header_row, key_row, drop_bad)
return render_table(header_rows, rows, title=title or (sheet or ""),
total=total, landscape=landscape, fontsize=fontsize)