export_service.py 56 KB

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