# -*- coding: utf-8 -*- """把「网页」和「WPS 表格固定区域」转换成 PDF(全程不弹窗、不打印)。 两条通道 -------- 1. 网页 : Edge/Chrome 无头模式 --print-to-pdf (等价于在浏览器里按 Ctrl+P 选"另存为 PDF",但无对话框) 2. 表格 : WPS COM 自动化(KET.Application / Excel.Application) 设置 PrintArea = "A1:F20" 后 ExportAsFixedFormat 导出 PDF 产物可直接交给 tools/printer_client.py print --input xxx.pdf 走 IPP 直连打印。 用法 ---- # 网页 -> PDF python tools/doc2pdf.py web --url "https://example.com/report" --out out.pdf python tools/doc2pdf.py web --html page.html --out out.pdf --landscape # WPS 表格固定区域 -> PDF python tools/doc2pdf.py sheet --file book.xlsx --sheet Sheet1 --range "A1:F20" --out out.pdf python tools/doc2pdf.py sheet --file book.xlsx --auto-area --out out.pdf """ from __future__ import annotations import argparse import os import subprocess import sys import tempfile import time from pathlib import Path EDGE_CANDIDATES = [ r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", r"C:\Program Files\Microsoft\Edge\Application\msedge.exe", r"C:\Program Files\Google\Chrome\Application\chrome.exe", r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", ] # --------------------------------------------------------------------------- # # 1) 网页 -> PDF # --------------------------------------------------------------------------- # def find_browser() -> str: for p in EDGE_CANDIDATES: if Path(p).exists(): return p raise RuntimeError("未找到 Edge/Chrome,可执行文件不在预期路径") def web_to_pdf(url: str | None = None, html: str | None = None, out: str = "out.pdf", landscape: bool = False, margin: float = 10.0, scale: float = 1.0, no_header_footer: bool = True, timeout: int = 90) -> str: """用无头浏览器把网页打印成 PDF。不弹任何窗口。""" browser = find_browser() out_path = Path(out).resolve() out_path.parent.mkdir(parents=True, exist_ok=True) if url is None: if html is None: raise ValueError("url 与 html 必须给一个") p = Path(html).resolve() if not p.exists(): raise FileNotFoundError(p) url = p.as_uri() profile = Path(tempfile.gettempdir()) / "doc2pdf-profile" cmd = [ browser, "--headless=new", "--disable-gpu", "--no-first-run", "--no-default-browser-check", f"--user-data-dir={profile}", "--print-to-pdf-no-header" if no_header_footer else "--no-pdf-header-footer", f"--print-to-pdf={out_path}", ] if landscape: cmd.append("--print-to-pdf-landscape") cmd.append(url) t0 = time.time() proc = subprocess.run(cmd, capture_output=True, timeout=timeout, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) if not out_path.exists() or out_path.stat().st_size == 0: raise RuntimeError(f"生成失败 rc={proc.returncode}\n" f"{proc.stderr.decode('utf-8', 'replace')[:800]}") print(f"[web] {out_path} {out_path.stat().st_size/1024:.1f} KB " f"{time.time()-t0:.1f}s") return str(out_path) # --------------------------------------------------------------------------- # # 2) WPS / Excel 表格固定区域 -> PDF # --------------------------------------------------------------------------- # def _com_app(prog_ids: list[str]): """按优先级尝试 ProgID,返回 (app, 使用的 progid)。""" import win32com.client as win32 last = None for pid in prog_ids: try: app = win32.DispatchEx(pid) return app, pid except Exception as e: # noqa: BLE001 last = e raise RuntimeError(f"无法启动表格 COM(试过 {prog_ids}):{last}") def sheet_to_pdf(file: str, sheet: str | None = None, rng: str | None = None, out: str = "out.pdf", auto_area: bool = False, landscape: bool = False, fit_one_page: bool = True, print_title_rows: str | None = None) -> str: """用 WPS 表格 COM 把指定区域导出为 PDF(不打印、不弹窗)。""" src = Path(file).resolve() if not src.exists(): raise FileNotFoundError(src) out_path = Path(out).resolve() out_path.parent.mkdir(parents=True, exist_ok=True) app, pid = _com_app(["KET.Application", "Ket.Application", "Excel.Application"]) print(f"[sheet] 使用 COM: {pid}") app.Visible = False app.DisplayAlerts = False wb = None try: wb = app.Workbooks.Open(str(src)) ws = wb.Worksheets(sheet) if sheet else wb.ActiveSheet if auto_area: rng = ws.UsedRange.Address(False, False).replace("$", "") print(f"[sheet] 自动区域 = {rng}") if rng: ws.PageSetup.PrintArea = rng.replace(" ", "") if print_title_rows: ws.PageSetup.PrintTitleRows = print_title_rows if landscape: ws.PageSetup.Orientation = 2 # xlLandscape if fit_one_page: ws.PageSetup.Zoom = False ws.PageSetup.FitToPagesWide = 1 ws.PageSetup.FitToPagesTall = 1 # 0 = xlTypePDF,只导出不送打印机 ws.ExportAsFixedFormat(0, str(out_path)) finally: if wb is not None: try: wb.Close(SaveChanges=False) except Exception: # noqa: BLE001 pass try: app.Quit() except Exception: # noqa: BLE001 pass if not out_path.exists() or out_path.stat().st_size == 0: raise RuntimeError("导出 PDF 失败") print(f"[sheet] {out_path} {out_path.stat().st_size/1024:.1f} KB 区域={rng}") return str(out_path) # --------------------------------------------------------------------------- # # CLI # --------------------------------------------------------------------------- # def main() -> int: ap = argparse.ArgumentParser(description="网页/WPS表格 -> PDF(不打印)") sub = ap.add_subparsers(dest="cmd", required=True) w = sub.add_parser("web", help="网页转 PDF") w.add_argument("--url") w.add_argument("--html") w.add_argument("--out", default="out.pdf") w.add_argument("--landscape", action="store_true") s = sub.add_parser("sheet", help="WPS 表格区域转 PDF") s.add_argument("--file", required=True) s.add_argument("--sheet") s.add_argument("--range", dest="rng") s.add_argument("--auto-area", action="store_true") s.add_argument("--print-title-rows", default=None, help='如 "$1:$1"') s.add_argument("--landscape", action="store_true") s.add_argument("--no-fit", action="store_true", help="不强制缩放到一页") s.add_argument("--out", default="out.pdf") a = ap.parse_args() try: if a.cmd == "web": web_to_pdf(url=a.url, html=a.html, out=a.out, landscape=a.landscape) else: sheet_to_pdf(a.file, sheet=a.sheet, rng=a.rng, out=a.out, auto_area=a.auto_area, landscape=a.landscape, fit_one_page=not a.no_fit, print_title_rows=a.print_title_rows) except Exception as e: # noqa: BLE001 print(f"失败: {type(e).__name__}: {e}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())