- 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
249 lines
11 KiB
Python
249 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""IPP 打印客户端(插件调用入口)。
|
||
|
||
契约
|
||
----
|
||
- 不读命令行参数、不 ``sys.exit``、不 ``print``:诊断信息走 ``log`` 回调;
|
||
- 异常统一为 :class:`printkit.errors.PrintKitError` 子类;
|
||
- 不做业务判断(打什么、什么时候打由插件决定)。
|
||
|
||
典型用法::
|
||
|
||
from printkit import Printer
|
||
|
||
p = Printer("l565") # 或 Printer("172.30.40.254") / Printer()
|
||
p.print("单据.pdf") # PDF / PNG / JPG 都可以
|
||
p.print_sheet("台账.xlsx", sheet="单子传递打印", filter_col="FRECTUNIT#Name")
|
||
p.validate("单据.pdf") # 只校验,不出纸
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import time
|
||
from pathlib import Path
|
||
|
||
from . import ipp, registry
|
||
from .errors import IppError, PrintKitError, UnsupportedFormat
|
||
from .registry import PrinterInfo
|
||
|
||
MSG_ENCODER = "printkit"
|
||
|
||
|
||
class Printer:
|
||
"""一台打印机的会话对象(无连接状态,可反复复用)。"""
|
||
|
||
def __init__(self, target: str | None = None, *, timeout: float = 30.0,
|
||
log=None, info: PrinterInfo | None = None):
|
||
self.info = info or registry.resolve(target)
|
||
self.timeout = timeout
|
||
self.log = log
|
||
self._caps: dict | None = None
|
||
self._req_id = 0
|
||
|
||
# --- 基础信息 ---------------------------------------------------------- #
|
||
@property
|
||
def uri(self) -> str:
|
||
return self.info.uri
|
||
|
||
@property
|
||
def id(self) -> str:
|
||
return self.info.id
|
||
|
||
def __repr__(self) -> str:
|
||
return f"<Printer {self.info.id} {self.uri}>"
|
||
|
||
def _say(self, msg: str) -> None:
|
||
if self.log:
|
||
self.log(msg)
|
||
|
||
# --- 协议层 ------------------------------------------------------------ #
|
||
def _request(self, op: int, operation_attrs=None, job_attrs=None,
|
||
document: bytes = b"", doc_format: str | None = None):
|
||
self._req_id += 1
|
||
ops = list(operation_attrs or ())
|
||
if doc_format:
|
||
ops.append(ipp.attr(ipp.T_MIME, b"document-format", doc_format))
|
||
body = ipp.build_request(op, self.uri, ops, job_attrs, self._req_id)
|
||
code, payload = ipp.post(self.info.ip, self.info.port, self.info.path,
|
||
body, document, secure=self.info.secure,
|
||
timeout=self.timeout)
|
||
if code and code != 200:
|
||
raise IppError(code, f"HTTP {code}", f"op 0x{op:04X}")
|
||
status, attrs = ipp.parse_response(payload)
|
||
return status, ipp.flatten(attrs)
|
||
|
||
def caps(self, refresh: bool = False) -> dict:
|
||
"""设备能力(首次走一次 Get-Printer-Attributes,之后缓存)。"""
|
||
if self._caps is None or refresh:
|
||
status, attrs = self._request(
|
||
ipp.OP_GET_PRINTER_ATTRIBUTES,
|
||
[ipp.attr(ipp.T_KEYWORD, b"requested-attributes", b"all")])
|
||
if status not in ipp.SUCCESS_CODES:
|
||
raise IppError(status, ipp.STATUS_TEXT.get(status, "?"), "Get-Printer-Attributes")
|
||
self._caps = attrs
|
||
return self._caps
|
||
|
||
def state(self) -> dict:
|
||
"""设备状态摘要。"""
|
||
c = self.caps()
|
||
s = (c.get("printer-state") or [0])[0]
|
||
return {
|
||
"state": {3: "idle", 4: "processing", 5: "stopped"}.get(s, str(s)),
|
||
"reasons": c.get("printer-state-reasons") or [],
|
||
"accepting": bool((c.get("printer-is-accepting-jobs") or [False])[0]),
|
||
"queued": (c.get("queued-job-count") or [0])[0],
|
||
"model": (c.get("printer-make-and-model") or [""])[0],
|
||
}
|
||
|
||
def supports(self, key: str, value: str) -> bool:
|
||
"""某能力项是否支持,例如 ``supports("sides-supported", "two-sided-long-edge")``。"""
|
||
return value in (self.caps().get(key) or [])
|
||
|
||
# --- 参数降级 ---------------------------------------------------------- #
|
||
def _adjust(self, opts: dict) -> dict:
|
||
"""剔除设备不支持的参数。
|
||
|
||
实测这两台 EPSON 即使带 ``ipp-attribute-fidelity=true`` 也**不报错**,
|
||
只会静默忽略,所以必须在客户端侧先判断,否则会"以为打了双面"。
|
||
"""
|
||
c = self.caps()
|
||
|
||
def drop(key, cap_key, value, hint: str):
|
||
if value and cap_key in c and value not in c[cap_key]:
|
||
self._say(f"[printkit] {self.info.id} 不支持 {key}={value}(支持 {c[cap_key]}),{hint}")
|
||
return None
|
||
return value
|
||
|
||
opts["sides"] = drop("sides", "sides-supported", opts.get("sides"), "已改为单面")
|
||
opts["media"] = drop("media", "media-supported", opts.get("media"), "已改用默认纸张")
|
||
opts["color"] = drop("color", "print-color-mode-supported", opts.get("color"), "已改用默认色彩")
|
||
return opts
|
||
|
||
def _check_format(self, doc_format: str) -> None:
|
||
c = self.caps()
|
||
fmts = c.get("document-format-supported")
|
||
if fmts and doc_format not in fmts:
|
||
raise UnsupportedFormat(
|
||
f"{self.info.id} 不支持 {doc_format},仅支持 {fmts}")
|
||
|
||
# --- 作业 -------------------------------------------------------------- #
|
||
def print_job(self, document: bytes, doc_format: str = "image/jpeg",
|
||
job_name: str = "printkit", **opts) -> dict:
|
||
"""提交一个原始作业(字节流)。真正出纸。"""
|
||
self._check_format(doc_format)
|
||
opts = self._adjust(opts)
|
||
job_attrs = [ipp.attr(ipp.T_NAME, b"job-name", job_name.encode("utf-8"))]
|
||
job_attrs += _job_options(**opts)
|
||
status, attrs = self._request(ipp.OP_PRINT_JOB, [], job_attrs,
|
||
document=document, doc_format=doc_format)
|
||
return _job_result(self, "Print-Job", status, attrs, len(document))
|
||
|
||
def validate_job(self, document: bytes, doc_format: str = "image/jpeg",
|
||
job_name: str = "printkit-validate", **opts) -> dict:
|
||
"""Validate-Job:协议规定"只校验不打印",用于联调与预检。"""
|
||
self._check_format(doc_format)
|
||
opts = self._adjust(opts)
|
||
job_attrs = [ipp.attr(ipp.T_NAME, b"job-name", job_name.encode("utf-8"))]
|
||
job_attrs += _job_options(**opts)
|
||
status, attrs = self._request(ipp.OP_VALIDATE_JOB, [], job_attrs,
|
||
document=document, doc_format=doc_format)
|
||
return _job_result(self, "Validate-Job", status, attrs, len(document))
|
||
|
||
# --- 高层:文档 → 打印 -------------------------------------------------- #
|
||
def print(self, src, *, dpi: int = 300, job_name: str = "printkit",
|
||
dry_run: bool = False, **opts) -> dict:
|
||
"""打印 PDF / 图片(多页自动逐页提交)。
|
||
|
||
:param dry_run: True 时走 Validate-Job,只校验不出纸
|
||
:returns: ``{"pages": [每页结果], "ok": bool}``
|
||
"""
|
||
from .render import to_jpegs
|
||
|
||
pages = to_jpegs(src, dpi=dpi)
|
||
self._say(f"[printkit] {Path(str(src)).name if not isinstance(src, (bytes, bytearray)) else '<bytes>'}"
|
||
f" -> {len(pages)} 页 @ {dpi}dpi")
|
||
results = []
|
||
for i, pg in enumerate(pages, 1):
|
||
name = f"{job_name}-p{i}"
|
||
if dry_run:
|
||
results.append(self.validate_job(pg, "image/jpeg", name, **opts))
|
||
else:
|
||
results.append(self.print_job(pg, "image/jpeg", name, **opts))
|
||
return {"pages": results, "ok": all(r["ok"] for r in results)}
|
||
|
||
def validate(self, src, *, dpi: int = 300, **opts) -> dict:
|
||
"""只校验首屏,不打印。"""
|
||
return self.print(src, dpi=dpi, dry_run=True, **opts)
|
||
|
||
def print_sheet(self, src, *, sheet: str | None = None,
|
||
filter_col: str | None = None, header_row: int = 2,
|
||
key_row: int | None = 1, title: str = "",
|
||
total: bool = False, keep_bad: bool = False,
|
||
dpi: int = 300, dry_run: bool = False, **opts) -> dict:
|
||
"""Excel/WPS 工作表 → 矢量 PDF → 打印(可选按列过滤)。"""
|
||
from . import sheet as _sheet
|
||
|
||
pdf = _sheet.build_pdf(
|
||
src, sheet=sheet, col=filter_col, header_row=header_row,
|
||
key_row=key_row, title=title, drop_bad=not keep_bad, total=total)
|
||
return self.print(pdf, dpi=dpi, dry_run=dry_run, **opts)
|
||
|
||
# --- 作业查询 ---------------------------------------------------------- #
|
||
def jobs(self, which: str = "completed", limit: int = 10) -> list[dict]:
|
||
status, attrs = self._request(ipp.OP_GET_JOBS, [
|
||
ipp.attr(ipp.T_KEYWORD, b"which-jobs", which.encode()),
|
||
ipp.attr(ipp.T_INTEGER, b"limit", limit),
|
||
])
|
||
if status not in ipp.SUCCESS_CODES:
|
||
raise IppError(status, ipp.STATUS_TEXT.get(status, "?"), "Get-Jobs")
|
||
ids = attrs.get("job-id") or []
|
||
states = attrs.get("job-state") or []
|
||
uris = attrs.get("job-uri") or []
|
||
return [{"id": ids[i] if i < len(ids) else None,
|
||
"state": states[i] if i < len(states) else None,
|
||
"uri": uris[i] if i < len(uris) else None}
|
||
for i in range(max(len(ids), len(states), len(uris)))]
|
||
|
||
def wait_idle(self, timeout: float = 120.0, interval: float = 2.0) -> bool:
|
||
"""等待队列清空(打印完成后返回 True,超时 False)。"""
|
||
deadline = time.time() + timeout
|
||
while time.time() < deadline:
|
||
st = self.state()
|
||
if st["state"] == "idle" and st["queued"] == 0:
|
||
return True
|
||
time.sleep(interval)
|
||
return False
|
||
|
||
|
||
def _job_options(media=None, sides=None, color=None, copies=None,
|
||
quality=None, scaling=None) -> list[bytes]:
|
||
out: list[bytes] = []
|
||
if media:
|
||
out.append(ipp.attr(ipp.T_KEYWORD, b"media", media))
|
||
if sides:
|
||
out.append(ipp.attr(ipp.T_KEYWORD, b"sides", sides))
|
||
if color:
|
||
out.append(ipp.attr(ipp.T_KEYWORD, b"print-color-mode", color))
|
||
if copies and copies > 1:
|
||
out.append(ipp.attr(ipp.T_INTEGER, b"copies", copies))
|
||
if quality:
|
||
out.append(ipp.attr(ipp.T_INTEGER, b"print-quality", quality))
|
||
if scaling:
|
||
out.append(ipp.attr(ipp.T_KEYWORD, b"print-scaling", scaling))
|
||
return out
|
||
|
||
|
||
def _job_result(printer: Printer, op: str, status: int, attrs: dict, nbytes: int) -> dict:
|
||
text = ipp.STATUS_TEXT.get(status, f"0x{status:04X}")
|
||
ok = status in ipp.SUCCESS_CODES
|
||
if status not in ipp.SUCCESS_CODES:
|
||
raise IppError(status, text, op)
|
||
printer._say(f"[printkit] {op} {printer.info.id} -> {text} ({nbytes}B)")
|
||
return {"ok": ok, "status": text, "status_code": status,
|
||
"bytes": nbytes, "job_id": (attrs.get("job-id") or [None])[0],
|
||
"job_uri": (attrs.get("job-uri") or [None])[0], "attrs": attrs}
|
||
|
||
|
||
def default_printer(**kw) -> Printer:
|
||
return Printer(None, **kw)
|