# -*- coding: utf-8 -*- """ 脱敏 Markdown → 带高亮的 Word(.docx)→ Word COM 导出 PDF 替换掉浏览器打印路线(沙箱下 Chrome/Edge headless 不产出文件) """ import io, os, re, sys, subprocess sys.stdout.reconfigure(encoding='utf-8') from docx import Document from docx.shared import Pt, RGBColor, Cm from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_COLOR_INDEX from docx.enum.table import WD_TABLE_ALIGNMENT from docx.enum.section import WD_ORIENT from docx.oxml.ns import qn from docx.oxml import OxmlElement BASE = r'E:/cfc/docs/参考资料' OUT = os.path.join(BASE, '脱敏交付') os.makedirs(OUT, exist_ok=True) PURPLE = RGBColor(0x5B, 0x3E, 0x96) DARK = RGBColor(0x25, 0x23, 0x2B) GREY = RGBColor(0x5A, 0x54, 0x66) FONT_CN = '微软雅黑' FONT_EN = 'Segoe UI' MASK = [ ('张学红', 'L 女士'), ('560822024', 'A-2401'), # 清理带编号/姓名的原始文件名,避免二次可识别 ('`A-2401-L 女士.json`', '报告解析 JSON'), ('`A-2401-L 女士.pdf`', '原始检测报告 PDF'), ('`A-2401-L 女士`', '报告解析文件'), ] KEY_PHRASES = [ '她不是吃得少,是吃得很讲究——但讲究的方向恰好全在压制铁吸收', '抓三件事——拆开早餐的铁吸收抑制', '她的肠道生态底子是好的,问题高度集中,可干预性很强', '这不是"菌群崩坏",是"关键岗位缺人"', '铁被早餐堵死了、双歧缺粮塌方了、早绝经让骨与雌激素两个窗口提前了', '不需要补乳杆菌', '不必补乳杆菌', '长双歧杆菌为第一靶点', '外源益生菌的**定植率很低**', '益生菌**点火**,瓜尔豆纤维**添柴**', '不能把"运动少"归因为懒、缺动力或自律不足', '必须临床区分,不可自行归因', '不得表述为"她正在抑郁"', '42 岁绝经 = 早绝经', '二选一时取瓜尔豆纤维', '她不吃肉,所以红肉不是她的问题', '菊粉或瓜尔豆纤维(二选一)→ 推荐瓜尔豆纤维', '与铁剂错开 2 小时', ] # ---------------- 基础排版工具 ---------------- def set_run_font(run, size=10.5, bold=False, color=DARK, italic=False): run.font.size = Pt(size) run.font.bold = bold run.font.italic = italic run.font.color.rgb = color run.font.name = FONT_EN rPr = run._element.get_or_add_rPr() rFonts = rPr.find(qn('w:rFonts')) if rFonts is None: rFonts = OxmlElement('w:rFonts'); rPr.append(rFonts) rFonts.set(qn('w:eastAsia'), FONT_CN) rFonts.set(qn('w:ascii'), FONT_EN) rFonts.set(qn('w:hAnsi'), FONT_EN) def shade_cell(cell, hexcolor): tcPr = cell._tc.get_or_add_tcPr() shd = OxmlElement('w:shd') shd.set(qn('w:val'), 'clear'); shd.set(qn('w:color'), 'auto') shd.set(qn('w:fill'), hexcolor) tcPr.append(shd) def add_bottom_border(par, color='5B3E96', sz=12): pPr = par._p.get_or_add_pPr() pbdr = OxmlElement('w:pBdr') bottom = OxmlElement('w:bottom') bottom.set(qn('w:val'), 'single'); bottom.set(qn('w:sz'), str(sz)) bottom.set(qn('w:space'), '4'); bottom.set(qn('w:color'), color) pbdr.append(bottom); pPr.append(pbdr) def add_left_bar(par, color='7B5CB8'): pPr = par._p.get_or_add_pPr() pbdr = OxmlElement('w:pBdr') left = OxmlElement('w:left') left.set(qn('w:val'), 'single'); left.set(qn('w:sz'), '18') left.set(qn('w:space'), '8'); left.set(qn('w:color'), color) pbdr.append(left); pPr.append(pbdr) def shade_paragraph(par, hexcolor): pPr = par._p.get_or_add_pPr() shd = OxmlElement('w:shd') shd.set(qn('w:val'), 'clear'); shd.set(qn('w:color'), 'auto') shd.set(qn('w:fill'), hexcolor) pPr.append(shd) # ---------------- 行内标记解析:**粗体** ==高亮== ---------------- TOKEN = re.compile(r'(\*\*.+?\*\*|==.+?==)') def add_inline(par, text, size=10.5, base_bold=False, color=DARK): """解析 **bold** 与 ==highlight==,支持「**粗体里嵌 ==高亮==」的嵌套""" for seg in TOKEN.split(text): if not seg: continue bold = base_bold if seg.startswith('**') and seg.endswith('**') and len(seg) > 4: seg = seg[2:-2] bold = True for sub in re.split(r'(==.+?==)', seg): if not sub: continue if sub.startswith('==') and sub.endswith('==') and len(sub) > 4: r = par.add_run(sub[2:-2]) set_run_font(r, size=size, bold=True, color=RGBColor(0x1A, 0x16, 0x20)) r.font.highlight_color = WD_COLOR_INDEX.YELLOW else: r = par.add_run(sub) set_run_font(r, size=size, bold=bold, color=color) # ---------------- Markdown 解析 ---------------- def parse_table(lines): """返回 rows(含表头)""" rows = [] for ln in lines: cells = [c.strip() for c in ln.strip().strip('|').split('|')] if all(re.fullmatch(r':?-{2,}:?', c) for c in cells if c): continue rows.append(cells) return rows def build_docx(md_path, out_docx, doc_title): raw = io.open(md_path, encoding='utf-8').read() for a, b in MASK: raw = raw.replace(a, b) # 去掉残留的反引号(docx 里会显示为字面 ` ) raw = re.sub(r'`([^`\n]{1,80})`', r'\1', raw) # 抬头关键信息高亮(原文已被 ** 包裹,需单独处理) raw = raw.replace('**42 岁绝经(绝经 10 年,属早绝经)**', '==42 岁绝经(绝经 10 年,属早绝经)==') for p in KEY_PHRASES: if p in raw and ('==' + p + '==') not in raw: raw = raw.replace(p, '==' + p + '==', 1) # 脱敏声明插入到首个 --- 之前 raw = raw.replace('\n---\n', '\n> **本文件已脱敏**:受检者姓名与报告编号均已做替换处理,仅保留归因所需的年龄、性别、生理阶段信息。\n\n---\n', 1) lines = raw.split('\n') doc = Document() sec = doc.sections[0] sec.page_width = Cm(21.0); sec.page_height = Cm(29.7) sec.left_margin = Cm(1.9); sec.right_margin = Cm(1.9) sec.top_margin = Cm(1.5); sec.bottom_margin = Cm(1.5) st = doc.styles['Normal'] st.font.name = FONT_EN; st.font.size = Pt(10.5) st.element.rPr.rFonts.set(qn('w:eastAsia'), FONT_CN) i = 0 n = len(lines) while i < n: ln = lines[i] s = ln.strip() # 空行 if not s: i += 1; continue # 表格 if s.startswith('|') and i + 1 < n and lines[i+1].strip().startswith('|'): block = [] while i < n and lines[i].strip().startswith('|'): block.append(lines[i]); i += 1 rows = [r for r in parse_table(block) if any(c for c in r)] if not rows: continue ncol = max(len(r) for r in rows) # --- 自适应列宽:按"该列最长内容"分配,幂压缩避免长文本列吃掉全部宽度 --- def wlen(s): return sum(2 if ord(ch) > 127 else 1 for ch in s) mxs = [] for ci in range(ncol): mx = 1 for row in rows: cell_txt = row[ci] if ci < len(row) else '' mx = max(mx, wlen(cell_txt)) mxs.append(mx) weights = [m ** 0.7 for m in mxs] tot = sum(weights) ratios = [max(0.085, min(0.42, x / tot)) for x in weights] ssum = sum(ratios) ratios = [r / ssum for r in ratios] CONTENT_W = 17.2 # cm,页面宽 21 - 左右边距各 1.9 col_w = [Cm(CONTENT_W * r) for r in ratios] tbl = doc.add_table(rows=0, cols=ncol) tbl.style = 'Table Grid' tbl.alignment = WD_TABLE_ALIGNMENT.CENTER tbl.autofit = False for ri, row in enumerate(rows): cells = tbl.add_row().cells for ci in range(ncol): txt = row[ci] if ci < len(row) else '' cell = cells[ci] cell.width = col_w[ci] cell.text = '' p = cell.paragraphs[0] p.paragraph_format.space_before = Pt(1.2) p.paragraph_format.space_after = Pt(1.2) p.paragraph_format.line_spacing = 1.18 if ri == 0: shade_cell(cell, '5B3E96') add_inline(p, txt, size=8.8, base_bold=True, color=RGBColor(0xFF, 0xFF, 0xFF)) else: if ri % 2 == 0: shade_cell(cell, 'FBF9FE') add_inline(p, txt, size=8.8) # 表头行跨页重复 + 行不跨页断裂 try: trPr = tbl.rows[0]._tr.get_or_add_trPr() th = OxmlElement('w:tblHeader'); th.set(qn('w:val'), 'true') trPr.append(th) for r_ in tbl.rows: trPr_ = r_._tr.get_or_add_trPr() cs = OxmlElement('w:cantSplit'); cs.set(qn('w:val'), 'true') trPr_.append(cs) except Exception: pass sp = doc.add_paragraph() sp.paragraph_format.space_after = Pt(2) continue # 标题 if s.startswith('#### '): p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(8) p.paragraph_format.space_after = Pt(3) p.paragraph_format.keep_with_next = True add_inline(p, s[5:], size=11, base_bold=True, color=RGBColor(0x4A,0x3F,0x63)) i += 1; continue if s.startswith('### '): p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(11) p.paragraph_format.space_after = Pt(4) p.paragraph_format.keep_with_next = True add_inline(p, s[4:], size=11.8, base_bold=True, color=RGBColor(0x3F,0x35,0x55)) add_bottom_border(p, color='CFC2E8', sz=6) i += 1; continue if s.startswith('## '): p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(15) p.paragraph_format.space_after = Pt(6) p.paragraph_format.left_indent = Cm(0.18) p.paragraph_format.keep_with_next = True add_inline(p, s[3:], size=13.4, base_bold=True, color=PURPLE) add_left_bar(p); shade_paragraph(p, 'F7F4FC') i += 1; continue if s.startswith('# '): p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(2) p.paragraph_format.space_after = Pt(8) add_inline(p, s[2:], size=18, base_bold=True, color=PURPLE) add_bottom_border(p, sz=16) i += 1; continue # 分隔线 if re.fullmatch(r'-{3,}', s): p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(2) p.paragraph_format.space_after = Pt(2) add_bottom_border(p, color='E2DCEE', sz=6) i += 1; continue # 引用块 if s.startswith('>'): block = [] while i < n and lines[i].strip().startswith('>'): block.append(lines[i].strip()[1:].strip()); i += 1 for b in block: if not b: continue p = doc.add_paragraph() p.paragraph_format.left_indent = Cm(0.35) p.paragraph_format.space_before = Pt(3) p.paragraph_format.space_after = Pt(3) p.paragraph_format.line_spacing = 1.6 txt = re.sub(r'^[-*]\s+', '· ', b) add_inline(p, txt, size=9.9, color=RGBColor(0x3C,0x34,0x50)) add_left_bar(p, color='A98FE0'); shade_paragraph(p, 'FAF7FE') continue # 列表 m = re.match(r'^(\s*)([-*]|\d+\.)\s+(.*)$', ln) if m: indent = len(m.group(1)) // 2 marker = m.group(2) body = m.group(3) p = doc.add_paragraph() p.paragraph_format.left_indent = Cm(0.55 + indent * 0.45) p.paragraph_format.first_line_indent = Cm(-0.42) p.paragraph_format.space_before = Pt(2) p.paragraph_format.space_after = Pt(2) prefix = '· ' if marker in ('-', '*') else marker + ' ' add_inline(p, prefix + body, size=10.4) i += 1; continue # 普通段落 p = doc.add_paragraph() p.paragraph_format.space_before = Pt(3) p.paragraph_format.space_after = Pt(3) p.paragraph_format.line_spacing = 1.72 p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY add_inline(p, s, size=10.5) i += 1 doc.save(out_docx) return out_docx # ---------------- Word COM → PDF ---------------- PS = r''' param([string]$DocxPath, [string]$PdfPath) $ErrorActionPreference = 'Stop' $word = New-Object -ComObject Word.Application $word.Visible = $false $word.DisplayAlerts = 0 try { $doc = $word.Documents.Open($DocxPath, $false, $true) $doc.SaveAs([ref]$PdfPath, [ref]17) $doc.Close([ref]0) Write-Output "PDF_OK" } finally { $word.Quit() [System.Runtime.InteropServices.Marshal]::ReleaseComObject($word) | Out-Null } ''' if __name__ == '__main__': ps_path = os.path.join(OUT, '_topdf.ps1') io.open(ps_path, 'w', encoding='utf-8-sig').write(PS) jobs = [ ('560822024-张学红-归因分析-简版.md', 'L女士-归因分析-简版', 'L 女士 · 肠道菌群归因分析(简版)'), ('560822024-张学红-归因分析-完整版.md', 'L女士-归因分析-完整版', 'L 女士 · 肠道菌群归因分析(完整版)'), ] for src, stem, title in jobs: docx_path = os.path.join(OUT, stem + '.docx') build_docx(os.path.join(BASE, src), docx_path, title) print('docx:', os.path.basename(docx_path), f'{os.path.getsize(docx_path)/1024:.0f} KB')