"""pandoc 产物后处理:公文版式(A4、页边距)、目录域注入、页脚页码、 表格列宽与边框、文档属性,最后重新打包。 用法: postprocess.py <解压后的 docx 目录> <输出 docx 路径> 说明:不依赖 pandoc 的 --toc(它会把目录插到红头之前),本脚本在 标题块(GovTitleSub)之后注入目录域,Word 打开时自动更新。 """ import os import re import sys import zipfile import unicodedata from xml.etree import ElementTree as ET if len(sys.argv) != 3: raise SystemExit('用法: postprocess.py <解压后的 docx 目录> <输出 docx 路径>') SRC = sys.argv[1] OUT = sys.argv[2] # 公文版心:A4 210×297mm,上 37mm、下 35mm、左 28mm、右 26mm PG_W, PG_H = 11906, 16838 MAR_TOP, MAR_BOTTOM, MAR_LEFT, MAR_RIGHT = 2098, 1984, 1587, 1474 TEXT_WIDTH = PG_W - MAR_LEFT - MAR_RIGHT # 8845 twips doc = open(f'{SRC}/word/document.xml', encoding='utf-8').read() # ---------- 0. 公文格式落成直接格式 ---------- # Word/WPS 会继承样式,但 QuickLook、部分在线阅读器只认直接格式。 # 关键段落(红头、发文字号、红线、标题、落款、正文)同时写一份直接格式, # 保证任何渲染器下版式一致。 def _rpr(font_ascii, font_ea, sz, color='000000', bold=False): b = '' if bold else '' return (f'' f'{b}' f'') RPR_FS = _rpr('Times New Roman', '仿宋', 32) RPR_HT = _rpr('Arial', '黑体', 32) RPR_KT = _rpr('Times New Roman', '楷体', 32) RPR_H3 = _rpr('Times New Roman', '仿宋', 32, bold=True) RPR_SBT_RED = _rpr('Times New Roman', '方正小标宋简体', 56, color='FF0000') RPR_SBT = _rpr('Times New Roman', '方正小标宋简体', 44) RPR_MONO = ('' '') SP = lambda before, after, line, rule: ( f'') IND0 = '' IND2 = '' P_FMT = { # styleId -> (pPr 追加片段, run rPr) 'GovRedHead': (SP(480, 60, 720, 'exact') + IND0 + '', RPR_SBT_RED), 'GovDocNo': (SP(120, 0, 480, 'exact') + IND0 + '', RPR_FS), 'GovRedRule': ('' + SP(0, 360, 240, 'exact') + IND0 + '', ''), 'GovTitle': (SP(240, 120, 660, 'exact') + IND0 + '', RPR_SBT), 'GovTitleSub': (SP(0, 360, 560, 'exact') + IND0 + '', RPR_FS), 'GovSignOff': ('' '' '', RPR_FS), 'FirstParagraph': (SP(0, 0, 560, 'exact') + IND2 + '', RPR_FS), 'BodyText': (SP(0, 0, 560, 'exact') + IND2 + '', RPR_FS), 'Heading1': (SP(360, 240, 560, 'exact') + IND0 + '' '', RPR_HT), 'Heading2': (SP(240, 120, 560, 'exact') + IND0 + '' '', RPR_KT), 'Heading3': (SP(180, 60, 560, 'exact') + IND0 + '' '', RPR_H3), 'SourceCode': ('' '' '', RPR_MONO), } PSTYLE_RE = re.compile(r'') def format_para(para): m = PSTYLE_RE.search(para) if not m or m.group(1) not in P_FMT: return para extra, rpr = P_FMT[m.group(1)] style_id = m.group(1) # 保留列表编号,重建 pPr(子元素按 schema 顺序排列) ppr_m = re.search(r'(.*?)', para, re.S) num = '' if ppr_m: nm = re.search(r'.*?', ppr_m.group(1), re.S) num = nm.group(0) if nm else '' new_ppr = (f'{num}{extra}') if ppr_m: para = para[:ppr_m.start()] + new_ppr + para[ppr_m.end():] else: para = para.replace('', '' + new_ppr, 1) def fix_run(mm): run = mm.group(0) run = re.sub(r'.*?|', '', run, count=1, flags=re.S) i = run.index('>') + 1 # 或 之后 return run[:i] + rpr + run[i:] return re.sub(r'.*?', fix_run, para, flags=re.S) paras = re.findall(r'.*?', doc, re.S) for p in paras: np_ = format_para(p) if np_ != p: doc = doc.replace(p, np_, 1) print('直接格式段落数:', len(paras)) # ---------- 1. 目录域:插在标题副标题之后 ---------- TOC = ('' '目 录' '' '' '' '' '' ' TOC \\o "1-2" \\h \\z \\u ' '' '(打开文档后按 F9 更新目录)' '' '') m = re.search(r'(?:(?!).)*?w:val="GovTitleSub".*?', doc, re.S) assert m, '未找到 GovTitleSub 段落,无法定位目录位置' doc = doc[:m.end()] + TOC + doc[m.end():] # ---------- 2. 正文首章另起一页 ---------- h1 = re.search(r'', doc) assert h1, 'Heading1 段落未匹配' doc = (doc[:h1.end()] + '' + doc[h1.end():]) # ---------- 3. 页面设置 ---------- sect = re.search(r'.*?', doc, re.S) assert sect, 'sectPr 未找到' doc = doc.replace(sect.group(0), '' f'' f'' '' '') # ---------- 4. 表格:按内容实测宽度重排队宽 + 显式边框/底纹 ---------- TBL_BORDERS = ('' '' '' '' '' '' '' '') TBL_CELL_MAR = ('' '' '') SHADING = '' CHAR_W = 95 # 9.5pt 下半角字符宽度(twips) CELL_PAD = 240 # 单元格左右边距合计 MIN_COL = 700 # 单列最小宽度 def text_width(s): """按字符显示宽度估算,CJK 记 2 个半角单位。""" units = sum(2 if unicodedata.east_asian_width(c) in ('W', 'F') else 1 for c in s) return units * CHAR_W def cell_texts(row): out = [] for tc in re.findall(r'.*?', row, re.S): txt = ''.join(re.findall(r']*)?>(.*?)', tc, re.S)) out.append(txt) return out def fix_row(row, widths, is_header): """给每个单元格写死 tcW,并给表头行加底纹。""" parts = re.split(r'(?=)', row) out, idx = [], 0 for p in parts: if p.startswith(''): c = min(idx, len(widths) - 1) idx += 1 pr = (f'' + (SHADING if is_header else '') + '') p = re.sub(r'|.*?', pr, p, count=1, flags=re.S) if '' not in p: p = p.replace('', '' + pr, 1) out.append(p) return ''.join(out) def fix_table(m): tbl = m.group(0) rows = re.findall(r'.*?', tbl, re.S) ncol = max((len(cell_texts(r)) for r in rows), default=0) if not ncol: return tbl # 每列自然宽度 = 该列最长内容(按换行切段)的显示宽度; # 同时记录最长不可断词(无空格)的宽度,作为该列的下限,避免日期/字段名被挤断 nat = [MIN_COL] * ncol floor = [MIN_COL] * ncol for r in rows: for c, txt in enumerate(cell_texts(r)[:ncol]): wmax = max((text_width(p) for p in txt.split('\n')), default=0) nat[c] = max(nat[c], wmax + CELL_PAD) tokens = [tk for tk in re.split(r'\s+', txt) if tk] if tokens: tw = max(text_width(tk) for tk in tokens) + CELL_PAD floor[c] = max(floor[c], min(tw, 1400)) total = sum(nat) w = [max(floor[c], int(nat[c] * TEXT_WIDTH / total)) for c in range(ncol)] # 收敛到正文宽度:差额优先由最宽的一列承担,必要时再逐列让出 diff = sum(w) - TEXT_WIDTH for _ in range(ncol + 2): if diff == 0: break if diff > 0: slack = [(w[i] - floor[i], i) for i in range(ncol) if w[i] > floor[i]] if not slack: # 所有列都到下限,仍超宽:按比例压缩,保证总宽等于版心 scale = TEXT_WIDTH / sum(w) w = [max(int(x * scale), 400) for x in w] break c = max(slack)[1] step = min(diff, w[c] - floor[c]) w[c] -= step diff -= step else: c = max(range(ncol), key=lambda i: w[i]) w[c] -= diff diff = 0 grid = '' + ''.join(f'' for x in w) + '' tbl = re.sub(r'.*?', grid, tbl, flags=re.S) def rewrite_pr(mm): rest = re.sub(r']*/>|.*?|.*?', '', mm.group(1), flags=re.S) return ('' + TBL_BORDERS + TBL_CELL_MAR + rest + f'' '') tbl = re.sub(r'(.*?)', rewrite_pr, tbl, count=1, flags=re.S) # 表头:有 tblHeader 标记的行,以及没有标记时的首行 row_idx = [0] def rewrite_row(mm): row = mm.group(0) row_idx[0] += 1 is_header = '.*?', rewrite_row, tbl, flags=re.S) # 单元格内文字固定 9.5pt(sz=19),不依赖样式继承 SZ = '' RPR = f'{SZ}' def fix_run(mm): run = mm.group(0) if '' in run: return run.replace('', f'{SZ}', 1) if '' in run: return run.replace('', RPR, 1) return '' + RPR + run[len(''):] tbl = re.sub(r'.*?', fix_run, tbl, flags=re.S) return tbl doc, n_tbl = re.subn(r'.*?', fix_table, doc, flags=re.S) print('表格处理数:', n_tbl) open(f'{SRC}/word/document.xml', 'w', encoding='utf-8').write(doc) # ---------- 5. 页脚:公文页码「— n —」 ---------- footer = ('\n' '' '' '' '' '' '— ' '' ' PAGE ' '' '1' '' '' ' —' '') open(f'{SRC}/word/footer1.xml', 'w', encoding='utf-8').write(footer) rp = f'{SRC}/word/_rels/document.xml.rels' rels = open(rp, encoding='utf-8').read() if 'footer1.xml' not in rels: rels = rels.replace('', '') open(rp, 'w', encoding='utf-8').write(rels) ctp = f'{SRC}/[Content_Types].xml' ct = open(ctp, encoding='utf-8').read() if 'footer1.xml' not in ct: ct = ct.replace('', '') open(ctp, 'w', encoding='utf-8').write(ct) # ---------- 6. 文档属性 ---------- cp = f'{SRC}/docProps/core.xml' core = open(cp, encoding='utf-8').read() core = re.sub(r'.*?', '赤峰市住房和城乡建设局', core) core = re.sub(r'.*?', '赤峰市智慧停车管理平台下级平台数据接入规范 V1.0' '下级平台数据接入接口规范', core) open(cp, 'w', encoding='utf-8').write(core) # ---------- 7. XML 良构校验 ---------- bad = [] for root, _, files in os.walk(SRC): for f in files: if f.endswith(('.xml', '.rels')): fp = os.path.join(root, f) try: ET.parse(fp) except Exception as e: bad.append((fp, str(e))) if bad: raise SystemExit(f'XML 解析失败: {bad}') # ---------- 8. 打包 ---------- if os.path.exists(OUT): os.remove(OUT) with zipfile.ZipFile(OUT, 'w', zipfile.ZIP_DEFLATED) as z: z.write(f'{SRC}/[Content_Types].xml', '[Content_Types].xml') for root, _, files in os.walk(SRC): for f in files: fp = os.path.join(root, f) arc = os.path.relpath(fp, SRC) if arc == '[Content_Types].xml': continue z.write(fp, arc) print('生成完成:', OUT, os.path.getsize(OUT), 'bytes')