postprocess.py
15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
"""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 = '<w:b /><w:bCs />' if bold else ''
return (f'<w:rPr><w:rFonts w:ascii="{font_ascii}" w:eastAsia="{font_ea}" '
f'w:hAnsi="{font_ascii}" w:cs="{font_ascii}" w:hint="eastAsia" />'
f'{b}<w:color w:val="{color}" /><w:sz w:val="{sz}" />'
f'<w:szCs w:val="{sz}" /></w:rPr>')
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 = ('<w:rPr><w:rFonts w:ascii="Consolas" w:eastAsia="宋体" w:hAnsi="Consolas" '
'w:cs="Consolas" /><w:color w:val="1A1A1A" /><w:sz w:val="18" />'
'<w:szCs w:val="18" /></w:rPr>')
SP = lambda before, after, line, rule: (
f'<w:spacing w:before="{before}" w:after="{after}" w:line="{line}" w:lineRule="{rule}" />')
IND0 = '<w:ind w:firstLineChars="0" w:firstLine="0" />'
IND2 = '<w:ind w:firstLineChars="200" w:firstLine="640" />'
P_FMT = { # styleId -> (pPr 追加片段, run rPr)
'GovRedHead': (SP(480, 60, 720, 'exact') + IND0 + '<w:jc w:val="center" />', RPR_SBT_RED),
'GovDocNo': (SP(120, 0, 480, 'exact') + IND0 + '<w:jc w:val="center" />', RPR_FS),
'GovRedRule': ('<w:pBdr><w:bottom w:val="single" w:sz="18" w:space="1" w:color="FF0000" /></w:pBdr>'
+ SP(0, 360, 240, 'exact') + IND0 + '<w:jc w:val="center" />',
'<w:rPr><w:sz w:val="12" /><w:szCs w:val="12" /></w:rPr>'),
'GovTitle': (SP(240, 120, 660, 'exact') + IND0 + '<w:jc w:val="center" />', RPR_SBT),
'GovTitleSub': (SP(0, 360, 560, 'exact') + IND0 + '<w:jc w:val="center" />', RPR_FS),
'GovSignOff': ('<w:spacing w:before="120" w:after="0" w:line="560" w:lineRule="exact" />'
'<w:ind w:rightChars="200" w:right="640" w:firstLineChars="0" w:firstLine="0" />'
'<w:jc w:val="right" />', RPR_FS),
'FirstParagraph': (SP(0, 0, 560, 'exact') + IND2 + '<w:jc w:val="both" />', RPR_FS),
'BodyText': (SP(0, 0, 560, 'exact') + IND2 + '<w:jc w:val="both" />', RPR_FS),
'Heading1': (SP(360, 240, 560, 'exact') + IND0 + '<w:jc w:val="left" />'
'<w:outlineLvl w:val="0" />', RPR_HT),
'Heading2': (SP(240, 120, 560, 'exact') + IND0 + '<w:jc w:val="left" />'
'<w:outlineLvl w:val="1" />', RPR_KT),
'Heading3': (SP(180, 60, 560, 'exact') + IND0 + '<w:jc w:val="left" />'
'<w:outlineLvl w:val="2" />', RPR_H3),
'SourceCode': ('<w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto" />'
'<w:ind w:leftChars="0" w:left="120" w:firstLineChars="0" w:firstLine="0" />'
'<w:jc w:val="left" /><w:shd w:val="clear" w:color="auto" w:fill="F5F5F5" />',
RPR_MONO),
}
PSTYLE_RE = re.compile(r'<w:pStyle w:val="([^"]+)"\s*/>')
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'<w:pPr>(.*?)</w:pPr>', para, re.S)
num = ''
if ppr_m:
nm = re.search(r'<w:numPr>.*?</w:numPr>', ppr_m.group(1), re.S)
num = nm.group(0) if nm else ''
new_ppr = (f'<w:pPr><w:pStyle w:val="{style_id}" />{num}{extra}</w:pPr>')
if ppr_m:
para = para[:ppr_m.start()] + new_ppr + para[ppr_m.end():]
else:
para = para.replace('<w:p>', '<w:p>' + new_ppr, 1)
def fix_run(mm):
run = mm.group(0)
run = re.sub(r'<w:rPr>.*?</w:rPr>|<w:rPr\s*/>', '', run, count=1, flags=re.S)
i = run.index('>') + 1 # <w:r> 或 <w:r ...> 之后
return run[:i] + rpr + run[i:]
return re.sub(r'<w:r>.*?</w:r>', fix_run, para, flags=re.S)
paras = re.findall(r'<w:p>.*?</w:p>', 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 = ('<w:p><w:pPr><w:pStyle w:val="TOCHeading" /><w:pageBreakBefore /></w:pPr>'
'<w:r><w:t xml:space="preserve">目 录</w:t></w:r></w:p>'
'<w:sdt><w:sdtPr><w:docPartObj>'
'<w:docPartGallery w:val="Table of Contents" /><w:docPartUnique />'
'</w:docPartObj></w:sdtPr><w:sdtContent>'
'<w:p><w:pPr><w:pStyle w:val="TOC1" /></w:pPr>'
'<w:r><w:fldChar w:fldCharType="begin" w:dirty="true" /></w:r>'
'<w:r><w:instrText xml:space="preserve"> TOC \\o "1-2" \\h \\z \\u </w:instrText></w:r>'
'<w:r><w:fldChar w:fldCharType="separate" /></w:r>'
'<w:r><w:t xml:space="preserve">(打开文档后按 F9 更新目录)</w:t></w:r>'
'<w:r><w:fldChar w:fldCharType="end" /></w:r></w:p>'
'</w:sdtContent></w:sdt>')
m = re.search(r'<w:p>(?:(?!</w:p>).)*?w:val="GovTitleSub".*?</w:p>', doc, re.S)
assert m, '未找到 GovTitleSub 段落,无法定位目录位置'
doc = doc[:m.end()] + TOC + doc[m.end():]
# ---------- 2. 正文首章另起一页 ----------
h1 = re.search(r'<w:p><w:pPr><w:pStyle w:val="Heading1" />', doc)
assert h1, 'Heading1 段落未匹配'
doc = (doc[:h1.end()] + '<w:pageBreakBefore />' + doc[h1.end():])
# ---------- 3. 页面设置 ----------
sect = re.search(r'<w:sectPr>.*?</w:sectPr>', doc, re.S)
assert sect, 'sectPr 未找到'
doc = doc.replace(sect.group(0),
'<w:sectPr><w:footerReference w:type="default" r:id="rIdFooter1" />'
f'<w:pgSz w:w="{PG_W}" w:h="{PG_H}" />'
f'<w:pgMar w:top="{MAR_TOP}" w:right="{MAR_RIGHT}" w:bottom="{MAR_BOTTOM}" '
f'w:left="{MAR_LEFT}" w:header="851" w:footer="992" w:gutter="0" />'
'<w:cols w:space="425" /><w:docGrid w:type="lines" w:linePitch="312" />'
'<w:footnotePr><w:numRestart w:val="eachSect" /></w:footnotePr></w:sectPr>')
# ---------- 4. 表格:按内容实测宽度重排队宽 + 显式边框/底纹 ----------
TBL_BORDERS = ('<w:tblBorders>'
'<w:top w:val="single" w:sz="4" w:space="0" w:color="7F7F7F" />'
'<w:left w:val="single" w:sz="4" w:space="0" w:color="7F7F7F" />'
'<w:bottom w:val="single" w:sz="4" w:space="0" w:color="7F7F7F" />'
'<w:right w:val="single" w:sz="4" w:space="0" w:color="7F7F7F" />'
'<w:insideH w:val="single" w:sz="4" w:space="0" w:color="BFBFBF" />'
'<w:insideV w:val="single" w:sz="4" w:space="0" w:color="BFBFBF" />'
'</w:tblBorders>')
TBL_CELL_MAR = ('<w:tblCellMar>'
'<w:top w:type="dxa" w:w="50" /><w:left w:type="dxa" w:w="90" />'
'<w:bottom w:type="dxa" w:w="50" /><w:right w:type="dxa" w:w="90" /></w:tblCellMar>')
SHADING = '<w:shd w:val="clear" w:color="auto" w:fill="EDEDED" />'
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'<w:tc>.*?</w:tc>', row, re.S):
txt = ''.join(re.findall(r'<w:t(?:\s[^>]*)?>(.*?)</w:t>', tc, re.S))
out.append(txt)
return out
def fix_row(row, widths, is_header):
"""给每个单元格写死 tcW,并给表头行加底纹。"""
parts = re.split(r'(?=<w:tc>)', row)
out, idx = [], 0
for p in parts:
if p.startswith('<w:tc>'):
c = min(idx, len(widths) - 1)
idx += 1
pr = (f'<w:tcPr><w:tcW w:type="dxa" w:w="{widths[c]}" />'
+ (SHADING if is_header else '') + '</w:tcPr>')
p = re.sub(r'<w:tcPr\s*/>|<w:tcPr>.*?</w:tcPr>', pr, p, count=1, flags=re.S)
if '<w:tcPr>' not in p:
p = p.replace('<w:tc>', '<w:tc>' + pr, 1)
out.append(p)
return ''.join(out)
def fix_table(m):
tbl = m.group(0)
rows = re.findall(r'<w:tr>.*?</w:tr>', 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 = '<w:tblGrid>' + ''.join(f'<w:gridCol w:w="{x}" />' for x in w) + '</w:tblGrid>'
tbl = re.sub(r'<w:tblGrid>.*?</w:tblGrid>', grid, tbl, flags=re.S)
def rewrite_pr(mm):
rest = re.sub(r'<w:tblW[^>]*/>|<w:tblBorders>.*?</w:tblBorders>|<w:tblCellMar>.*?</w:tblCellMar>',
'', mm.group(1), flags=re.S)
return ('<w:tblPr>' + TBL_BORDERS + TBL_CELL_MAR + rest
+ f'<w:tblW w:type="dxa" w:w="{TEXT_WIDTH}" />'
'<w:tblLayout w:type="fixed" /></w:tblPr>')
tbl = re.sub(r'<w:tblPr>(.*?)</w:tblPr>', 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 = '<w:tblHeader' in row or row_idx[0] == 1
return fix_row(row, w, is_header)
tbl = re.sub(r'<w:tr>.*?</w:tr>', rewrite_row, tbl, flags=re.S)
# 单元格内文字固定 9.5pt(sz=19),不依赖样式继承
SZ = '<w:sz w:val="19" /><w:szCs w:val="19" />'
RPR = f'<w:rPr>{SZ}</w:rPr>'
def fix_run(mm):
run = mm.group(0)
if '<w:rPr>' in run:
return run.replace('<w:rPr>', f'<w:rPr>{SZ}', 1)
if '<w:rPr />' in run:
return run.replace('<w:rPr />', RPR, 1)
return '<w:r>' + RPR + run[len('<w:r>'):]
tbl = re.sub(r'<w:r>.*?</w:r>', fix_run, tbl, flags=re.S)
return tbl
doc, n_tbl = re.subn(r'<w:tbl>.*?</w:tbl>', fix_table, doc, flags=re.S)
print('表格处理数:', n_tbl)
open(f'{SRC}/word/document.xml', 'w', encoding='utf-8').write(doc)
# ---------- 5. 页脚:公文页码「— n —」 ----------
footer = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
'<w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" '
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
'<w:p><w:pPr><w:jc w:val="center" /><w:rPr>'
'<w:rFonts w:ascii="Times New Roman" w:eastAsia="宋体" />'
'<w:sz w:val="28" /><w:szCs w:val="28" /></w:rPr></w:pPr>'
'<w:r><w:rPr><w:sz w:val="28" /><w:szCs w:val="28" /></w:rPr>'
'<w:t xml:space="preserve">— </w:t></w:r>'
'<w:r><w:fldChar w:fldCharType="begin" /></w:r>'
'<w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r>'
'<w:r><w:fldChar w:fldCharType="separate" /></w:r>'
'<w:r><w:rPr><w:sz w:val="28" /></w:rPr><w:t>1</w:t></w:r>'
'<w:r><w:fldChar w:fldCharType="end" /></w:r>'
'<w:r><w:rPr><w:sz w:val="28" /><w:szCs w:val="28" /></w:rPr>'
'<w:t xml:space="preserve"> —</w:t></w:r>'
'</w:p></w:ftr>')
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('</Relationships>',
'<Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" '
'Id="rIdFooter1" Target="footer1.xml" /></Relationships>')
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('</Types>',
'<Override PartName="/word/footer1.xml" ContentType="application/vnd.openxmlformats-officedocument'
'.wordprocessingml.footer+xml" /></Types>')
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'<dc:creator>.*?</dc:creator>',
'<dc:creator>赤峰市住房和城乡建设局</dc:creator>', core)
core = re.sub(r'<dc:title>.*?</dc:title>',
'<dc:title>赤峰市智慧停车管理平台下级平台数据接入规范 V1.0</dc:title>'
'<dc:subject>下级平台数据接入接口规范</dc:subject>', 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')