export_service.py 44 KB

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