export_service.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. """export_service.py — 将 Blocks 转换为 .doc 文件并返回永久下载链接"""
  2. import base64
  3. import io
  4. import json
  5. import time
  6. import unicodedata
  7. from pathlib import Path
  8. from typing import Optional
  9. from docx import Document
  10. from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
  11. from docx.enum.text import WD_ALIGN_PARAGRAPH
  12. from docx.oxml import OxmlElement
  13. from docx.oxml.ns import qn
  14. from docx.shared import Pt, RGBColor
  15. from lxml import etree
  16. from app.config import settings
  17. from app.core.exceptions import ExportError
  18. # ------------------------------------------------------------------ #
  19. # 样式文件加载
  20. # ------------------------------------------------------------------ #
  21. def load_style_file(style_id: Optional[str] = None) -> dict:
  22. """加载样式 JSON;style_id=None 时使用默认样式文件"""
  23. if style_id is not None:
  24. # 阶段 1 占位
  25. raise ExportError(f"样式 ID 暂不支持: {style_id}(阶段 1 功能)")
  26. path = Path(settings.default_style_file)
  27. if not path.exists():
  28. raise ExportError(f"默认样式文件不存在: {path}")
  29. try:
  30. with open(path, encoding="utf-8") as f:
  31. return json.load(f)
  32. except (OSError, json.JSONDecodeError) as exc:
  33. raise ExportError(f"样式文件解析失败: {exc}") from exc
  34. def build_style_map(style_data: dict) -> dict[str, dict]:
  35. """将样式列表转为双键映射(style_id 和 name 均可命中)"""
  36. mapping: dict[str, dict] = {}
  37. for s in style_data.get("styles", []):
  38. if s.get("style_id"):
  39. mapping[s["style_id"]] = s
  40. if s.get("name"):
  41. mapping[s["name"]] = s
  42. return mapping
  43. # ------------------------------------------------------------------ #
  44. # JSON ↔ lxml 互转
  45. # ------------------------------------------------------------------ #
  46. def dict_to_element(d: dict) -> etree._Element:
  47. """递归将字典转为 lxml Element"""
  48. elem = etree.Element(d["@tag"], attrib=dict(d.get("@attrib", {})))
  49. if d.get("#text"):
  50. elem.text = d["#text"]
  51. if d.get("#tail"):
  52. elem.tail = d["#tail"]
  53. for child_tag, child_val in d.get("@children", {}).items():
  54. items = child_val if isinstance(child_val, list) else [child_val]
  55. for item in items:
  56. if isinstance(item, dict):
  57. elem.append(dict_to_element(item))
  58. return elem
  59. def inject_styles_from_json(doc: Document, style_data: dict) -> None:
  60. """将 JSON 中所有样式的 full_xml_definition upsert 到文档 <w:styles> 节点"""
  61. styles_element = doc.styles.element
  62. for style_entry in style_data.get("styles", []):
  63. xml_def = style_entry.get("full_xml_definition")
  64. if not xml_def:
  65. continue
  66. try:
  67. new_elem = dict_to_element(xml_def)
  68. except Exception:
  69. continue
  70. style_id_key = qn("w:styleId")
  71. new_style_id = new_elem.get(style_id_key)
  72. if new_style_id:
  73. existing = styles_element.find(
  74. f'.//{qn("w:style")}[@{qn("w:styleId")}="{new_style_id}"]'
  75. )
  76. if existing is not None:
  77. styles_element.remove(existing)
  78. styles_element.append(new_elem)
  79. # 注入编号格式定义
  80. inject_numbering_from_json(doc, style_data)
  81. def inject_numbering_from_json(doc: Document, style_data: dict) -> None:
  82. """将 JSON 中的编号格式定义注入到文档
  83. 由于 python-docx 对 numbering part 的支持有限,
  84. 我们需要在保存后通过修改 ZIP 文件来注入编号格式。
  85. 这个函数主要是为了记录编号定义,实际注入在 blocks_to_docx_bytes 中完成。
  86. """
  87. # 暂时不在这里注入,而是在生成文档后通过 ZIP 修改
  88. pass
  89. def _resolve_style_id(style_map: dict, *keys: str) -> Optional[str]:
  90. """解析样式 ID"""
  91. for key in keys:
  92. entry = style_map.get(key)
  93. if entry and entry.get("style_id"):
  94. return entry["style_id"]
  95. return None
  96. def _apply_paragraph_style(para, style: dict):
  97. """应用段落级样式(对齐方式、行距、缩进等)"""
  98. # 对齐方式
  99. align = style.get('align')
  100. if align == 'center':
  101. para.alignment = WD_ALIGN_PARAGRAPH.CENTER
  102. elif align == 'right':
  103. para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
  104. elif align == 'justify':
  105. para.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
  106. elif align == 'left':
  107. para.alignment = WD_ALIGN_PARAGRAPH.LEFT
  108. # 段落格式(行距、缩进等)- 如果需要的话
  109. pf = para.paragraph_format
  110. # 行距
  111. if style.get('line_spacing'):
  112. try:
  113. pf.line_spacing = style['line_spacing']
  114. except Exception:
  115. pass
  116. # 段前间距
  117. if style.get('space_before'):
  118. try:
  119. pf.space_before = Pt(style['space_before'])
  120. except Exception:
  121. pass
  122. # 段后间距
  123. if style.get('space_after'):
  124. try:
  125. pf.space_after = Pt(style['space_after'])
  126. except Exception:
  127. pass
  128. def _apply_run_style(run, style: dict):
  129. """应用 run 级样式(字符级格式)- 增强版"""
  130. # 字体名称(支持中文字体 eastAsia)- 优先处理字体
  131. if style.get('font_name'):
  132. font_name = style['font_name']
  133. run.font.name = font_name
  134. # 对于中文字体,需要设置 eastAsia 属性(关键!)
  135. try:
  136. r = run._element
  137. rPr = r.get_or_add_rPr()
  138. rFonts = rPr.get_or_add_rFonts()
  139. # 设置所有字体属性,确保中文字体正确应用
  140. rFonts.set(qn('w:ascii'), font_name)
  141. rFonts.set(qn('w:hAnsi'), font_name)
  142. rFonts.set(qn('w:eastAsia'), font_name)
  143. rFonts.set(qn('w:cs'), font_name) # 复杂文字
  144. except Exception:
  145. pass
  146. # 字号(优先处理)
  147. if style.get('font_size'):
  148. try:
  149. size_pt = float(style['font_size'])
  150. run.font.size = Pt(size_pt)
  151. # 确保字号正确应用到 XML
  152. r = run._element
  153. rPr = r.get_or_add_rPr()
  154. # 移除旧的字号元素
  155. for sz in rPr.findall(qn('w:sz')):
  156. rPr.remove(sz)
  157. for szCs in rPr.findall(qn('w:szCs')):
  158. rPr.remove(szCs)
  159. # 添加新的字号元素(Word 使用半磅单位)
  160. sz = OxmlElement('w:sz')
  161. sz.set(qn('w:val'), str(int(size_pt * 2)))
  162. rPr.append(sz)
  163. szCs = OxmlElement('w:szCs')
  164. szCs.set(qn('w:val'), str(int(size_pt * 2)))
  165. rPr.append(szCs)
  166. except Exception:
  167. pass
  168. # 粗体
  169. if style.get('bold'):
  170. run.bold = True
  171. # 确保粗体正确应用
  172. try:
  173. r = run._element
  174. rPr = r.get_or_add_rPr()
  175. # 移除旧的粗体元素
  176. for b in rPr.findall(qn('w:b')):
  177. rPr.remove(b)
  178. for bCs in rPr.findall(qn('w:bCs')):
  179. rPr.remove(bCs)
  180. # 添加新的粗体元素
  181. b = OxmlElement('w:b')
  182. rPr.append(b)
  183. bCs = OxmlElement('w:bCs')
  184. rPr.append(bCs)
  185. except Exception:
  186. pass
  187. # 斜体
  188. if style.get('italic'):
  189. run.italic = True
  190. try:
  191. r = run._element
  192. rPr = r.get_or_add_rPr()
  193. for i in rPr.findall(qn('w:i')):
  194. rPr.remove(i)
  195. for iCs in rPr.findall(qn('w:iCs')):
  196. rPr.remove(iCs)
  197. i = OxmlElement('w:i')
  198. rPr.append(i)
  199. iCs = OxmlElement('w:iCs')
  200. rPr.append(iCs)
  201. except Exception:
  202. pass
  203. # 下划线
  204. if style.get('underline'):
  205. run.underline = True
  206. # 删除线
  207. if style.get('strike'):
  208. run.font.strike = True
  209. # 颜色
  210. if style.get('color'):
  211. try:
  212. # 移除可能的 # 前缀
  213. color = style['color'].lstrip('#')
  214. if len(color) == 6:
  215. run.font.color.rgb = RGBColor(
  216. int(color[0:2], 16),
  217. int(color[2:4], 16),
  218. int(color[4:6], 16)
  219. )
  220. except (ValueError, AttributeError):
  221. pass
  222. # ------------------------------------------------------------------ #
  223. # Blocks → Word 转换
  224. # ------------------------------------------------------------------ #
  225. def blocks_to_docx_bytes(blocks: list[dict], style_map: dict, style_data: dict) -> bytes:
  226. """将 Blocks 列表转换为 Word 文档字节流
  227. Args:
  228. blocks: Block 列表
  229. style_map: 样式映射
  230. style_data: 样式数据
  231. Returns:
  232. Word 文档字节流
  233. """
  234. doc = Document()
  235. inject_styles_from_json(doc, style_data)
  236. # 检查 blocks 中是否有常用的字体和字号,用于修改 Normal 样式
  237. # 这样可以确保空行在 Word 中显示正确的字体
  238. _update_normal_style_if_needed(doc, blocks)
  239. for block in blocks:
  240. block_type = block['type']
  241. if block_type == 'heading':
  242. _render_heading_block(doc, block, style_map)
  243. elif block_type == 'paragraph':
  244. _render_paragraph_block(doc, block, style_map)
  245. elif block_type == 'table':
  246. _render_table_block(doc, block, style_map)
  247. elif block_type == 'image':
  248. _render_image_block(doc, block)
  249. # 先保存到临时缓冲区
  250. buf = io.BytesIO()
  251. doc.save(buf)
  252. # 通过 ZIP 操作注入编号格式
  253. docx_bytes = _inject_numbering_via_zip(buf.getvalue(), style_data)
  254. return docx_bytes
  255. def _update_normal_style_if_needed(doc: Document, blocks: list[dict]):
  256. """更新 Normal 样式以匹配 blocks 中最常用的字体
  257. 这样可以确保空行在 Word 中显示正确的字体和字号
  258. """
  259. # 统计段落中最常用的字体和字号
  260. font_counts = {}
  261. size_counts = {}
  262. for block in blocks:
  263. if block['type'] == 'paragraph':
  264. style = block.get('style', {})
  265. font_name = style.get('font_name')
  266. font_size = style.get('font_size')
  267. if font_name:
  268. font_counts[font_name] = font_counts.get(font_name, 0) + 1
  269. if font_size:
  270. size_counts[font_size] = size_counts.get(font_size, 0) + 1
  271. # 找到最常用的字体和字号
  272. most_common_font = max(font_counts.items(), key=lambda x: x[1])[0] if font_counts else None
  273. most_common_size = max(size_counts.items(), key=lambda x: x[1])[0] if size_counts else None
  274. # 如果找到了常用字体或字号,更新 Normal 样式
  275. if most_common_font or most_common_size:
  276. try:
  277. normal_style = doc.styles['Normal']
  278. if most_common_font:
  279. # 修改 Normal 样式的字体
  280. style_element = normal_style.element
  281. rPr = style_element.find(qn('w:rPr'))
  282. if rPr is None:
  283. rPr = OxmlElement('w:rPr')
  284. # 插入到第一个子元素之前
  285. if len(style_element):
  286. style_element.insert(0, rPr)
  287. else:
  288. style_element.append(rPr)
  289. rFonts = rPr.find(qn('w:rFonts'))
  290. if rFonts is None:
  291. rFonts = OxmlElement('w:rFonts')
  292. rPr.append(rFonts)
  293. # 设置所有字体属性
  294. rFonts.set(qn('w:ascii'), most_common_font)
  295. rFonts.set(qn('w:hAnsi'), most_common_font)
  296. rFonts.set(qn('w:eastAsia'), most_common_font)
  297. if most_common_size:
  298. # 修改 Normal 样式的字号
  299. style_element = normal_style.element
  300. rPr = style_element.find(qn('w:rPr'))
  301. if rPr is None:
  302. rPr = OxmlElement('w:rPr')
  303. if len(style_element):
  304. style_element.insert(0, rPr)
  305. else:
  306. style_element.append(rPr)
  307. # 删除旧的字号元素
  308. old_sz = rPr.find(qn('w:sz'))
  309. if old_sz is not None:
  310. rPr.remove(old_sz)
  311. old_szCs = rPr.find(qn('w:szCs'))
  312. if old_szCs is not None:
  313. rPr.remove(old_szCs)
  314. # 添加新的字号元素
  315. sz = OxmlElement('w:sz')
  316. sz.set(qn('w:val'), str(int(most_common_size * 2))) # Word 使用半磅
  317. rPr.append(sz)
  318. szCs = OxmlElement('w:szCs')
  319. szCs.set(qn('w:val'), str(int(most_common_size * 2)))
  320. rPr.append(szCs)
  321. except Exception:
  322. # 如果修改样式失败,继续(不影响文档生成)
  323. pass
  324. def _inject_numbering_via_zip(docx_bytes: bytes, style_data: dict) -> bytes:
  325. """通过 ZIP 操作注入编号格式到 Word 文档
  326. Args:
  327. docx_bytes: 原始 Word 文档字节流
  328. style_data: 样式数据(包含 numbering 定义)
  329. Returns:
  330. 注入编号格式后的 Word 文档字节流
  331. """
  332. numbering_def = style_data.get("numbering")
  333. if not numbering_def:
  334. # 没有编号定义,直接返回原文档
  335. return docx_bytes
  336. try:
  337. from zipfile import ZipFile
  338. from lxml import etree
  339. # 读取原文档
  340. input_buf = io.BytesIO(docx_bytes)
  341. output_buf = io.BytesIO()
  342. with ZipFile(input_buf, 'r') as zip_read:
  343. with ZipFile(output_buf, 'w') as zip_write:
  344. # 复制所有文件
  345. for item in zip_read.infolist():
  346. data = zip_read.read(item.filename)
  347. # 跳过 numbering.xml,我们会重新写入
  348. if item.filename == 'word/numbering.xml':
  349. continue
  350. zip_write.writestr(item, data)
  351. # 将 JSON 格式的编号定义转换为 XML
  352. numbering_element = dict_to_element(numbering_def)
  353. numbering_xml = etree.tostring(
  354. numbering_element,
  355. encoding='UTF-8',
  356. xml_declaration=True,
  357. standalone=True
  358. )
  359. # 写入 numbering.xml
  360. zip_write.writestr('word/numbering.xml', numbering_xml)
  361. # 确保 _rels/document.xml.rels 中有 numbering 的关系
  362. # 读取 document.xml.rels
  363. try:
  364. rels_data = zip_read.read('word/_rels/document.xml.rels')
  365. rels_root = etree.fromstring(rels_data)
  366. # 检查是否已有 numbering 关系
  367. ns = {'r': 'http://schemas.openxmlformats.org/package/2006/relationships'}
  368. numbering_rels = rels_root.xpath(
  369. '//r:Relationship[@Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"]',
  370. namespaces=ns
  371. )
  372. if not numbering_rels:
  373. # 添加 numbering 关系
  374. from docx.oxml.ns import qn
  375. rel_elem = etree.SubElement(rels_root, qn('r:Relationship'))
  376. # 找到最大的 rId
  377. existing_ids = [int(r.get('Id')[3:]) for r in rels_root.findall(qn('r:Relationship')) if r.get('Id', '').startswith('rId')]
  378. next_id = max(existing_ids) + 1 if existing_ids else 1
  379. rel_elem.set('Id', f'rId{next_id}')
  380. rel_elem.set('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering')
  381. rel_elem.set('Target', 'numbering.xml')
  382. # 写回 rels 文件
  383. rels_xml = etree.tostring(rels_root, encoding='UTF-8', xml_declaration=True)
  384. zip_write.writestr('word/_rels/document.xml.rels', rels_xml)
  385. except KeyError:
  386. # 如果没有 rels 文件,忽略
  387. pass
  388. return output_buf.getvalue()
  389. except Exception as e:
  390. # 如果注入失败,返回原文档
  391. print(f"警告: 通过 ZIP 注入编号格式失败: {e}")
  392. return docx_bytes
  393. def _render_heading_block(doc: Document, block: dict, style_map: dict):
  394. """渲染标题块(支持编号格式和自定义样式)- 增强版"""
  395. level = block['level']
  396. content = block['content']
  397. style_name = block.get('word_style', f'Heading {level}')
  398. block_style = block.get('style', {})
  399. # 创建段落
  400. para = doc.add_paragraph()
  401. # 应用 Word 样式
  402. style_id = _resolve_style_id(style_map, style_name, f'Heading {level}')
  403. if style_id:
  404. try:
  405. para.style = doc.styles[style_id]
  406. except KeyError:
  407. para.style = f'Heading {level}'
  408. else:
  409. para.style = f'Heading {level}'
  410. # 应用 Block 级自定义样式(段落级)
  411. _apply_paragraph_style(para, block_style)
  412. # 渲染内容
  413. if isinstance(content, list):
  414. # 富文本:应用 run 级样式
  415. _render_rich_text(para, content, block_style)
  416. else:
  417. # 纯文本:应用 block 级样式到 run
  418. run = para.add_run(str(content))
  419. # 标题也需要应用自定义样式(如果有的话)
  420. if block_style:
  421. _apply_run_style(run, block_style)
  422. # 尝试应用编号格式(如果样式中包含编号定义)
  423. try:
  424. # 检查样式是否有编号定义
  425. style_element = para.style.element
  426. if style_element is not None:
  427. from docx.oxml.ns import qn
  428. # 查找样式中的编号属性
  429. pPr = style_element.find(qn('w:pPr'))
  430. if pPr is not None:
  431. numPr = pPr.find(qn('w:numPr'))
  432. if numPr is not None:
  433. # 样式中有编号定义,复制到段落
  434. para_pPr = para._element.get_or_add_pPr()
  435. # 移除可能存在的旧编号属性
  436. old_numPr = para_pPr.find(qn('w:numPr'))
  437. if old_numPr is not None:
  438. para_pPr.remove(old_numPr)
  439. # 复制编号属性
  440. import copy
  441. para_pPr.append(copy.deepcopy(numPr))
  442. except Exception as e:
  443. # 如果应用编号失败,继续(标题仍然会显示,只是没有编号)
  444. pass
  445. def _render_paragraph_block(doc: Document, block: dict, style_map: dict):
  446. """渲染段落块(支持富文本和自定义样式)- 增强版"""
  447. content = block['content']
  448. style_name = block.get('word_style', 'Normal')
  449. block_style = block.get('style', {})
  450. para = doc.add_paragraph()
  451. # 应用 Word 样式
  452. style_id = _resolve_style_id(style_map, style_name, 'Normal')
  453. if style_id:
  454. try:
  455. para.style = doc.styles[style_id]
  456. except KeyError:
  457. para.style = 'Normal'
  458. else:
  459. para.style = 'Normal'
  460. # 应用 Block 级自定义样式(段落级)
  461. _apply_paragraph_style(para, block_style)
  462. # 渲染内容
  463. if isinstance(content, list):
  464. # 富文本:应用 run 级样式
  465. _render_rich_text(para, content, block_style)
  466. elif content:
  467. # 有内容的纯文本
  468. run = para.add_run(str(content))
  469. _apply_run_style(run, block_style)
  470. else:
  471. # 空内容 - 关键修复:确保空段落也能保留样式
  472. # 创建空 run 并应用样式,这样用户在 Word 中输入文本时会自动应用这些样式
  473. run = para.add_run('')
  474. _apply_run_style(run, block_style)
  475. # 对于空段落,还需要确保段落格式正确
  476. # 特别是字体和字号,即使 run 是空的也要设置
  477. if block_style.get('font_name') or block_style.get('font_size'):
  478. # 再添加一个空格符 run 来"激活"样式(Word 的特殊处理)
  479. # 然后立即删除,但样式会保留
  480. try:
  481. # 方法:在段落属性中设置默认 run 属性
  482. pPr = para._element.get_or_add_pPr()
  483. rPr = pPr.find(qn('w:rPr'))
  484. if rPr is None:
  485. rPr = OxmlElement('w:rPr')
  486. pPr.insert(0, rPr)
  487. # 设置字体
  488. if block_style.get('font_name'):
  489. font_name = block_style['font_name']
  490. rFonts = rPr.find(qn('w:rFonts'))
  491. if rFonts is None:
  492. rFonts = OxmlElement('w:rFonts')
  493. rPr.append(rFonts)
  494. rFonts.set(qn('w:ascii'), font_name)
  495. rFonts.set(qn('w:hAnsi'), font_name)
  496. rFonts.set(qn('w:eastAsia'), font_name)
  497. rFonts.set(qn('w:cs'), font_name)
  498. # 设置字号
  499. if block_style.get('font_size'):
  500. size_pt = float(block_style['font_size'])
  501. # 移除旧的字号
  502. for sz in rPr.findall(qn('w:sz')):
  503. rPr.remove(sz)
  504. for szCs in rPr.findall(qn('w:szCs')):
  505. rPr.remove(szCs)
  506. # 添加新的字号
  507. sz = OxmlElement('w:sz')
  508. sz.set(qn('w:val'), str(int(size_pt * 2)))
  509. rPr.append(sz)
  510. szCs = OxmlElement('w:szCs')
  511. szCs.set(qn('w:val'), str(int(size_pt * 2)))
  512. rPr.append(szCs)
  513. except Exception:
  514. pass
  515. def _render_rich_text(para, segments: list, block_style: dict = None):
  516. """渲染富文本格式 - 增强版"""
  517. for seg in segments:
  518. text = seg.get('text', '')
  519. seg_style = seg.get('style', {})
  520. run = para.add_run(text)
  521. # 合并样式:block_style 作为默认,seg_style 覆盖
  522. merged_style = {}
  523. if block_style:
  524. merged_style.update(block_style)
  525. merged_style.update(seg_style)
  526. # 应用合并后的样式
  527. if merged_style:
  528. _apply_run_style(run, merged_style)
  529. # 处理 word_style(如果片段有独立的 word_style)
  530. word_style = seg.get('word_style')
  531. if word_style:
  532. # 注意:run 不能直接应用样式,只能应用字符样式
  533. # 这里我们只应用格式属性
  534. pass
  535. def _render_table_block(doc: Document, block: dict, style_map: dict):
  536. """渲染表格块(支持合并单元格、列宽、行高等)"""
  537. table_data = block['content']
  538. if isinstance(table_data, str):
  539. try:
  540. table_data = json.loads(table_data)
  541. except json.JSONDecodeError:
  542. return
  543. rows = table_data.get('rows', [])
  544. if not rows:
  545. return
  546. # 使用 col_widths 确定真实列数(而不是第一行的单元格数)
  547. col_widths = table_data.get('col_widths', [])
  548. if col_widths:
  549. num_cols = len(col_widths)
  550. else:
  551. # 回退:扫描所有行,找到最大的列索引
  552. num_cols = 0
  553. for row_data in rows:
  554. col_index = 0
  555. for cell_data in row_data.get('cells', []):
  556. colspan = cell_data.get('colspan', 1)
  557. col_index += colspan
  558. num_cols = max(num_cols, col_index)
  559. if num_cols == 0:
  560. return
  561. num_rows = len(rows)
  562. # 创建表格
  563. table = doc.add_table(rows=num_rows, cols=num_cols)
  564. # 应用表格样式
  565. table_style = block.get('word_style', 'Table Grid')
  566. try:
  567. table.style = table_style
  568. except KeyError:
  569. table.style = 'Table Grid'
  570. # 设置表格对齐方式(默认居中)
  571. block_style = block.get('style', {})
  572. table_align = block_style.get('table_align', 'center') # 默认居中
  573. if table_align == 'center':
  574. table.alignment = WD_TABLE_ALIGNMENT.CENTER
  575. elif table_align == 'left':
  576. table.alignment = WD_TABLE_ALIGNMENT.LEFT
  577. elif table_align == 'right':
  578. table.alignment = WD_TABLE_ALIGNMENT.RIGHT
  579. # 设置列宽
  580. if col_widths:
  581. for col_idx, width in enumerate(col_widths):
  582. if col_idx < len(table.columns):
  583. table.columns[col_idx].width = Pt(width)
  584. # 填充内容并处理合并单元格
  585. merge_map = {} # {(row, col): (end_row, end_col)} 记录合并区域
  586. occupied = {} # {(row, col): True} 记录哪些位置已被占用(被合并的单元格)
  587. for r_idx, row_data in enumerate(rows):
  588. # 设置行高
  589. row_height = row_data.get('height')
  590. if row_height:
  591. table.rows[r_idx].height = Pt(row_height)
  592. cells_data = row_data.get('cells', [])
  593. # 构建一个映射:col_index -> cell_data
  594. cells_by_col = {}
  595. for cell_data in cells_data:
  596. col_idx = cell_data.get('col_index', None)
  597. if col_idx is not None:
  598. cells_by_col[col_idx] = cell_data
  599. # 遍历所有列
  600. for col_idx in range(num_cols):
  601. # 检查这个位置是否被占用(被上方的合并单元格占用)
  602. if occupied.get((r_idx, col_idx), False):
  603. continue # 跳过被占用的位置
  604. # 检查是否有数据要填充到这个位置
  605. if col_idx not in cells_by_col:
  606. continue # 这个位置没有数据
  607. cell_data = cells_by_col[col_idx]
  608. # 跳过被合并的单元格(rowspan=0 表示这个单元格被上面的单元格合并了)
  609. rowspan = cell_data.get('rowspan', 1)
  610. if rowspan == 0:
  611. continue
  612. colspan = cell_data.get('colspan', 1)
  613. # 确保不越界
  614. if col_idx >= num_cols:
  615. continue
  616. # 获取起始单元格
  617. start_cell = table.rows[r_idx].cells[col_idx]
  618. # 处理合并单元格
  619. if colspan > 1 or rowspan > 1:
  620. # 计算结束位置
  621. end_col = min(col_idx + colspan - 1, num_cols - 1)
  622. end_row = min(r_idx + rowspan - 1, num_rows - 1)
  623. # 合并单元格
  624. if end_col > col_idx or end_row > r_idx:
  625. try:
  626. end_cell = table.rows[end_row].cells[end_col]
  627. start_cell.merge(end_cell)
  628. merge_map[(r_idx, col_idx)] = (end_row, end_col)
  629. # 标记被合并的单元格位置为已占用
  630. for merge_r in range(r_idx, end_row + 1):
  631. for merge_c in range(col_idx, end_col + 1):
  632. if merge_r != r_idx or merge_c != col_idx: # 不标记起始单元格
  633. occupied[(merge_r, merge_c)] = True
  634. except Exception:
  635. pass # 合并失败,继续
  636. # 设置单元格宽度(如果有)
  637. cell_width = cell_data.get('width')
  638. if cell_width:
  639. try:
  640. start_cell.width = Pt(cell_width)
  641. except Exception:
  642. pass
  643. # 填充单元格内容
  644. cell_text = cell_data.get('text', '')
  645. cell_style = cell_data.get('style', {})
  646. cell_word_style = cell_data.get('word_style') # 获取单元格的 word_style
  647. # 设置单元格垂直对齐(默认居中)
  648. valign = cell_style.get('valign', 'center') # 默认垂直居中
  649. if valign == 'center' or valign == 'middle':
  650. start_cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
  651. elif valign == 'top':
  652. start_cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.TOP
  653. elif valign == 'bottom':
  654. start_cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.BOTTOM
  655. # 清空默认段落
  656. start_cell.text = ''
  657. para = start_cell.paragraphs[0]
  658. # 应用单元格的 Word 样式(如果有)
  659. if cell_word_style:
  660. # 尝试从 style_map 解析样式ID
  661. style_id = _resolve_style_id(style_map, cell_word_style)
  662. if style_id:
  663. # 通过 style_id 应用样式
  664. try:
  665. para.style = doc.styles[style_id]
  666. except KeyError:
  667. # 如果 style_id 不存在,尝试直接使用名称
  668. try:
  669. para.style = cell_word_style
  670. except KeyError:
  671. # 都失败了,使用 Normal
  672. para.style = 'Normal'
  673. else:
  674. # 没有找到 style_id,尝试直接使用名称
  675. try:
  676. para.style = cell_word_style
  677. except KeyError:
  678. # 失败了,使用 Normal
  679. para.style = 'Normal'
  680. # 应用单元格段落级样式(对齐)
  681. _apply_paragraph_style(para, cell_style)
  682. # 渲染单元格内容(支持富文本)
  683. if isinstance(cell_text, list):
  684. # 富文本格式
  685. _render_rich_text(para, cell_text, cell_style)
  686. else:
  687. # 纯文本格式
  688. run = para.add_run(str(cell_text))
  689. # 应用单元格 run 级样式
  690. _apply_run_style(run, cell_style)
  691. def _render_image_block(doc: Document, block: dict):
  692. """渲染图片块(支持 Base64 Data URL)"""
  693. content = block['content']
  694. style = block.get('style', {})
  695. # 只处理 Data URL
  696. if not isinstance(content, str) or not content.startswith('data:'):
  697. return
  698. try:
  699. # 解析 data:image/png;base64,xxxxx
  700. if ',' not in content:
  701. return
  702. header, b64_data = content.split(',', 1)
  703. image_bytes = base64.b64decode(b64_data)
  704. # 创建段落并设置对齐
  705. paragraph = doc.add_paragraph()
  706. align = style.get('align', 'left')
  707. if align == 'center':
  708. paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
  709. elif align == 'right':
  710. paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
  711. # 插入图片
  712. run = paragraph.add_run()
  713. width = style.get('width', 10.0)
  714. height = style.get('height', 7.0)
  715. unit = style.get('unit', 'cm')
  716. # 转换为磅(Word内部单位:1厘米 = 28.35磅,1英寸 = 72磅)
  717. if unit == 'cm':
  718. width_pt = width * 28.35
  719. height_pt = height * 28.35
  720. else: # inches
  721. width_pt = width * 72
  722. height_pt = height * 72
  723. run.add_picture(
  724. io.BytesIO(image_bytes),
  725. width=Pt(width_pt),
  726. height=Pt(height_pt)
  727. )
  728. except Exception as e:
  729. # 失败时添加占位文本
  730. p = doc.add_paragraph(f"[图片加载失败]")
  731. p.runs[0].font.color.rgb = RGBColor(255, 0, 0)
  732. # ------------------------------------------------------------------ #
  733. # 公共工具
  734. # ------------------------------------------------------------------ #
  735. def _safe_filename(name: str) -> str:
  736. """生成安全的文件名"""
  737. name = unicodedata.normalize("NFKC", name)
  738. for ch in r'\/:*?"<>|':
  739. name = name.replace(ch, "_")
  740. return name.strip() or "document"
  741. def _make_filename(blocks: list[dict]) -> str:
  742. """从 blocks 中提取第一个标题或段落作为文件名 + 时间戳
  743. Args:
  744. blocks: Block 列表
  745. Returns:
  746. 文件名(不含扩展名)
  747. """
  748. # 查找第一个标题或段落
  749. first_text = ""
  750. for block in blocks:
  751. if block['type'] in ('heading', 'paragraph'):
  752. content = block['content']
  753. if isinstance(content, list):
  754. # 富文本:拼接所有片段
  755. first_text = "".join(seg.get("text", "") for seg in content)
  756. else:
  757. first_text = str(content)
  758. if first_text.strip():
  759. break
  760. # 提取第一行
  761. first_line = first_text.split('\n')[0].strip()
  762. safe = _safe_filename(first_line) if first_line else "document"
  763. # 限制长度
  764. if len(safe) > 50:
  765. safe = safe[:50]
  766. ts = int(time.time() * 1000)
  767. return f"{safe}_{ts}"