add_toc_placeholders.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. #!/usr/bin/env python3
  2. """
  3. Add placeholder entries to Table of Contents in a DOCX file.
  4. This script adds placeholder TOC entries between the 'separate' and 'end'
  5. field characters, so users see some content on first open instead of an empty TOC.
  6. The original file is replaced with the modified version.
  7. Usage:
  8. python add_toc_placeholders.py <docx_file> # auto-extract headings (default)
  9. python add_toc_placeholders.py <docx_file> --auto # explicit auto mode
  10. python add_toc_placeholders.py <docx_file> --entries <entries_json>
  11. entries_json format: JSON string with array of objects:
  12. [
  13. {"level": 1, "text": "Chapter 1 Overview", "page": "1"},
  14. {"level": 2, "text": "Section 1.1 Details", "page": "1"}
  15. ]
  16. Default behavior (no flags): auto-extracts Heading 1-3 from the document.
  17. Filters out table/figure captions (e.g. "表 1:xxx", "图 2:xxx").
  18. Example:
  19. python add_toc_placeholders.py document.docx
  20. python add_toc_placeholders.py document.docx --auto
  21. python add_toc_placeholders.py document.docx --entries '[{"level":1,"text":"Introduction","page":"1"}]'
  22. """
  23. import argparse
  24. import json
  25. import re
  26. import shutil
  27. import sys
  28. import tempfile
  29. import zipfile
  30. from pathlib import Path
  31. def _extract_headings_from_docx(docx_path: str, max_level: int = 3) -> list:
  32. """Extract headings from a DOCX file for auto-mode TOC generation.
  33. Args:
  34. docx_path: Path to DOCX file
  35. max_level: Maximum heading level to include (default 3)
  36. Returns:
  37. List of dicts with 'level', 'text', 'page' keys
  38. """
  39. from docx import Document
  40. doc = Document(docx_path)
  41. entries = []
  42. page_estimate = 1
  43. # Pattern to filter out table/figure captions styled as headings
  44. caption_pattern = re.compile(r'^[表图]\s*\d')
  45. for i, para in enumerate(doc.paragraphs):
  46. style_name = para.style.name if para.style else ''
  47. if not style_name.startswith('Heading'):
  48. continue
  49. m = re.search(r'(\d+)', style_name)
  50. if not m:
  51. continue
  52. level = int(m.group(1))
  53. if level > max_level:
  54. continue
  55. text = para.text.strip()
  56. if not text:
  57. continue
  58. # Filter table/figure captions
  59. if caption_pattern.match(text):
  60. continue
  61. # Rough page estimate: increment every ~8 headings
  62. page_estimate = max(1, 1 + i // 8)
  63. entries.append({"level": level, "text": text, "page": str(page_estimate)})
  64. return entries
  65. def add_toc_placeholders(docx_path: str, entries: list = None) -> None:
  66. """Add placeholder TOC entries to a DOCX file (in-place replacement).
  67. Args:
  68. docx_path: Path to DOCX file (will be modified in-place)
  69. entries: Optional list of placeholder entries. Each entry should be a dict
  70. with 'level' (1-3), 'text', and 'page' keys.
  71. """
  72. docx_path = Path(docx_path)
  73. # Create temp directory for extraction
  74. with tempfile.TemporaryDirectory() as temp_dir:
  75. temp_path = Path(temp_dir)
  76. extracted_dir = temp_path / "extracted"
  77. temp_output = temp_path / "output.docx"
  78. # Extract DOCX
  79. with zipfile.ZipFile(docx_path, 'r') as zip_ref:
  80. zip_ref.extractall(extracted_dir)
  81. # Ensure TOC styles exist in styles.xml
  82. styles_xml_path = extracted_dir / "word" / "styles.xml"
  83. toc_style_mapping = _ensure_toc_styles(styles_xml_path)
  84. print(f"TOC style mapping: {toc_style_mapping}")
  85. # Fix settings.xml: ensure updateFields has val="true"
  86. settings_xml_path = extracted_dir / "word" / "settings.xml"
  87. _fix_update_fields(settings_xml_path)
  88. # Fix Heading styles: ensure outlineLvl is set (required for TOC field update)
  89. _fix_heading_outline_levels(styles_xml_path)
  90. # Process document.xml
  91. document_xml = extracted_dir / "word" / "document.xml"
  92. if not document_xml.exists():
  93. raise ValueError("document.xml not found in the DOCX file")
  94. # Read and process XML
  95. content = document_xml.read_text(encoding='utf-8')
  96. # Fix fldChar structure: split merged begin+instrText+separate into separate <w:r> elements
  97. content = _fix_fld_char_structure(content)
  98. # Find TOC structure and add placeholders (uses lxml for robust XML parsing)
  99. modified_content = _insert_toc_placeholders(content, entries, toc_style_mapping)
  100. # Write back
  101. document_xml.write_text(modified_content, encoding='utf-8')
  102. # Repack DOCX to temp file
  103. with zipfile.ZipFile(temp_output, 'w', zipfile.ZIP_DEFLATED) as zipf:
  104. for file_path in extracted_dir.rglob('*'):
  105. if file_path.is_file():
  106. arcname = file_path.relative_to(extracted_dir)
  107. zipf.write(file_path, arcname)
  108. # Replace original file with modified version (use shutil.move for cross-device support)
  109. docx_path.unlink()
  110. shutil.move(str(temp_output), str(docx_path))
  111. def _fix_update_fields(settings_xml_path: Path) -> None:
  112. """Fix settings.xml to ensure <w:updateFields w:val="true"/> is present.
  113. The docx npm library generates <w:updateFields/> without val="true",
  114. which Word/WPS interprets as false, preventing TOC auto-update on open.
  115. """
  116. if not settings_xml_path.exists():
  117. return
  118. content = settings_xml_path.read_text(encoding='utf-8')
  119. original = content
  120. # Case 1: <w:updateFields/> (self-closing, no val) → add val="true"
  121. if '<w:updateFields/>' in content:
  122. content = content.replace('<w:updateFields/>', '<w:updateFields w:val="true"/>')
  123. print('Fixed: <w:updateFields/> → <w:updateFields w:val="true"/>')
  124. # Case 2: <w:updateFields w:val="false"/> → change to true (match precisely)
  125. elif re.search(r'<w:updateFields\s+w:val="false"\s*/>', content):
  126. content = re.sub(
  127. r'<w:updateFields\s+w:val="false"\s*/>',
  128. '<w:updateFields w:val="true"/>',
  129. content
  130. )
  131. print('Fixed: <w:updateFields w:val="false"/> → <w:updateFields w:val="true"/>')
  132. # Case 3: Not present at all → inject before </w:settings>
  133. elif '<w:updateFields' not in content:
  134. content = content.replace('</w:settings>', '<w:updateFields w:val="true"/></w:settings>')
  135. print('Fixed: added <w:updateFields w:val="true"/> to settings.xml')
  136. if content != original:
  137. settings_xml_path.write_text(content, encoding='utf-8')
  138. def _fix_heading_outline_levels(styles_xml_path: Path) -> None:
  139. """Fix Heading styles to include outlineLvl in pPr.
  140. The docx npm library creates Heading styles but sometimes doesn't set outlineLvl
  141. in the style definition. Without outlineLvl, Word's TOC field update won't find
  142. headings even though they display correctly.
  143. This ensures Heading1 has outlineLvl=0, Heading2 has outlineLvl=1, etc.
  144. """
  145. if not styles_xml_path.exists():
  146. return
  147. content = styles_xml_path.read_text(encoding='utf-8')
  148. original = content
  149. W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
  150. for level in range(1, 7):
  151. style_id = f'Heading{level}'
  152. outline_val = str(level - 1)
  153. # Pattern: find <w:style> with w:styleId="HeadingN"
  154. style_pattern = (
  155. rf'(<w:style[^>]*w:styleId="{style_id}"[^>]*>)'
  156. rf'(.*?)'
  157. rf'(</w:style>)'
  158. )
  159. match = re.search(style_pattern, content, flags=re.DOTALL)
  160. if not match:
  161. continue
  162. style_content = match.group(2)
  163. # Check if outlineLvl already exists in this style
  164. if '<w:outlineLvl' in style_content:
  165. continue
  166. # Find or create <w:pPr> within this style
  167. ppr_match = re.search(r'(<w:pPr[^>]*>)(.*?)(</w:pPr>)', style_content, flags=re.DOTALL)
  168. if ppr_match:
  169. # Add outlineLvl inside existing pPr
  170. new_ppr_content = ppr_match.group(2) + f'<w:outlineLvl w:val="{outline_val}"/>'
  171. new_style_content = (
  172. style_content[:ppr_match.start()] +
  173. ppr_match.group(1) + new_ppr_content + ppr_match.group(3) +
  174. style_content[ppr_match.end():]
  175. )
  176. else:
  177. # No pPr exists, create one
  178. new_ppr = f'<w:pPr><w:outlineLvl w:val="{outline_val}"/></w:pPr>'
  179. # Insert pPr right after style opening (after name/basedOn if present)
  180. new_style_content = new_ppr + style_content
  181. new_style = match.group(1) + new_style_content + match.group(3)
  182. content = content[:match.start()] + new_style + content[match.end():]
  183. print(f'Fixed: added outlineLvl={outline_val} to {style_id} style')
  184. if content != original:
  185. styles_xml_path.write_text(content, encoding='utf-8')
  186. def _fix_fld_char_structure(xml_content: str) -> str:
  187. """Fix malformed fldChar structure where begin+instrText+separate are in one <w:r>.
  188. The docx npm library generates:
  189. <w:r><w:fldChar begin/><w:instrText>TOC...</w:instrText><w:fldChar separate/></w:r>
  190. Word/WPS requires the standard structure:
  191. <w:r><w:fldChar begin/></w:r>
  192. <w:r><w:instrText>TOC...</w:instrText></w:r>
  193. <w:r><w:fldChar separate/></w:r>
  194. """
  195. # Match a <w:r> that contains both begin fldChar AND instrText AND separate fldChar
  196. pattern = (
  197. r'<w:r(?:\s[^>]*)?>('
  198. r'<w:fldChar[^>]*w:fldCharType="begin"[^>]*/>' # begin
  199. r')('
  200. r'<w:instrText[^>]*>.*?</w:instrText>' # instrText
  201. r')('
  202. r'<w:fldChar[^>]*w:fldCharType="separate"[^>]*/>' # separate
  203. r')</w:r>'
  204. )
  205. def split_run(match):
  206. begin = match.group(1)
  207. instr = match.group(2)
  208. separate = match.group(3)
  209. return f'<w:r>{begin}</w:r><w:r>{instr}</w:r><w:r>{separate}</w:r>'
  210. modified = re.sub(pattern, split_run, xml_content, flags=re.DOTALL)
  211. if modified != xml_content:
  212. print("Fixed: split merged fldChar begin+instrText+separate into separate <w:r> elements")
  213. # Fix TOC instrText: remove \t switch with wrong style names
  214. # docx npm lib generates \t "Heading1,1,Heading2,2,..." but Word expects "Heading 1,1,..."
  215. # Since we already have \o "1-3" which uses outlineLvl (now fixed), \t is redundant and harmful
  216. toc_t_pattern = r'(TOC\s+[^<]*?)\\t\s+&quot;[^&]*&quot;'
  217. modified2 = re.sub(toc_t_pattern, r'\1', modified)
  218. if modified2 != modified:
  219. print("Fixed: removed \\t switch from TOC instrText (\\o with outlineLvl is sufficient)")
  220. modified = modified2
  221. return modified
  222. def _detect_toc_styles(styles_xml_path: Path) -> dict:
  223. """Detect TOC style IDs from styles.xml.
  224. Args:
  225. styles_xml_path: Path to styles.xml
  226. Returns:
  227. Dictionary mapping level (1-3) to style ID string
  228. """
  229. if not styles_xml_path.exists():
  230. return {}
  231. content = styles_xml_path.read_text(encoding='utf-8')
  232. result = {}
  233. for level in range(1, 4):
  234. # Standard TOC style names: "TOC 1", "TOC 2", "TOC 3" (with space)
  235. # or "TOC1", "TOC2", "TOC3" (no space) — docx-js uses numeric IDs like "9", "11", "12"
  236. patterns = [
  237. rf'w:styleId="(TOC{level})"',
  238. rf'w:styleId="(TOC {level})"',
  239. rf'<w:name\s+w:val="toc\s*{level}"[^/]*/>\s*</w:name>|<w:name\s+w:val="toc\s*{level}"[^/]*/>',
  240. ]
  241. for pattern in patterns[:2]:
  242. m = re.search(pattern, content)
  243. if m:
  244. result[level] = m.group(1)
  245. break
  246. else:
  247. # Try matching by w:name (case insensitive toc N)
  248. # Find <w:style> blocks with name containing "toc N"
  249. name_pattern = rf'<w:style[^>]*w:styleId="([^"]*)"[^>]*>.*?<w:name\s+w:val="[Tt][Oo][Cc]\s*{level}"'
  250. m = re.search(name_pattern, content, flags=re.DOTALL)
  251. if m:
  252. result[level] = m.group(1)
  253. return result
  254. def _ensure_toc_styles(styles_xml_path: Path) -> dict:
  255. """Ensure TOC styles exist in styles.xml, adding them if necessary.
  256. Returns:
  257. Dictionary mapping level (1-3) to style ID string
  258. """
  259. if not styles_xml_path.exists():
  260. return {1: "9", 2: "11", 3: "12"}
  261. content = styles_xml_path.read_text(encoding='utf-8')
  262. detected = _detect_toc_styles(styles_xml_path)
  263. result = dict(detected)
  264. W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
  265. # Define TOC styles to add if missing
  266. toc_style_defs = {
  267. 1: {
  268. 'id': '9',
  269. 'name': 'toc 1',
  270. 'xml': f'''<w:style w:type="paragraph" w:styleId="9" xmlns:w="{W_NS}">
  271. <w:name w:val="toc 1"/>
  272. <w:basedOn w:val="Normal"/>
  273. <w:uiPriority w:val="39"/>
  274. <w:pPr>
  275. <w:tabs><w:tab w:val="right" w:leader="dot" w:pos="9026"/></w:tabs>
  276. <w:spacing w:before="120" w:after="60"/>
  277. </w:pPr>
  278. <w:rPr><w:b/><w:bCs/></w:rPr>
  279. </w:style>'''
  280. },
  281. 2: {
  282. 'id': '11',
  283. 'name': 'toc 2',
  284. 'xml': f'''<w:style w:type="paragraph" w:styleId="11" xmlns:w="{W_NS}">
  285. <w:name w:val="toc 2"/>
  286. <w:basedOn w:val="Normal"/>
  287. <w:uiPriority w:val="39"/>
  288. <w:pPr>
  289. <w:tabs><w:tab w:val="right" w:leader="dot" w:pos="9026"/></w:tabs>
  290. <w:ind w:left="360"/>
  291. <w:spacing w:before="60" w:after="40"/>
  292. </w:pPr>
  293. </w:style>'''
  294. },
  295. 3: {
  296. 'id': '12',
  297. 'name': 'toc 3',
  298. 'xml': f'''<w:style w:type="paragraph" w:styleId="12" xmlns:w="{W_NS}">
  299. <w:name w:val="toc 3"/>
  300. <w:basedOn w:val="Normal"/>
  301. <w:uiPriority w:val="39"/>
  302. <w:pPr>
  303. <w:tabs><w:tab w:val="right" w:leader="dot" w:pos="9026"/></w:tabs>
  304. <w:ind w:left="720"/>
  305. <w:spacing w:before="40" w:after="20"/>
  306. </w:pPr>
  307. </w:style>'''
  308. },
  309. }
  310. modified = False
  311. for level in range(1, 4):
  312. if level not in result:
  313. style_def = toc_style_defs[level]
  314. result[level] = style_def['id']
  315. # Add style before </w:styles>
  316. insert_point = content.rfind('</w:styles>')
  317. if insert_point == -1:
  318. print(f"WARNING: Could not find </w:styles> to insert TOC {level} style", file=sys.stderr)
  319. continue
  320. content = content[:insert_point] + style_def['xml'] + '\n' + content[insert_point:]
  321. print(f"Added TOC {level} style (ID: {style_def['id']})")
  322. modified = True
  323. if modified:
  324. styles_xml_path.write_text(content, encoding='utf-8')
  325. # Ensure Hyperlink style exists
  326. _ensure_hyperlink_style(styles_xml_path)
  327. return result
  328. def _ensure_hyperlink_style(styles_xml_path: Path) -> None:
  329. """Ensure Hyperlink character style exists in styles.xml."""
  330. if not styles_xml_path.exists():
  331. return
  332. content = styles_xml_path.read_text(encoding='utf-8')
  333. if 'w:styleId="Hyperlink"' in content:
  334. return
  335. W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
  336. hyperlink_style = f'''<w:style w:type="character" w:styleId="Hyperlink" xmlns:w="{W_NS}">
  337. <w:name w:val="Hyperlink"/>
  338. <w:uiPriority w:val="99"/>
  339. <w:rPr>
  340. <w:color w:val="0563C1"/>
  341. <w:u w:val="single"/>
  342. </w:rPr>
  343. </w:style>'''
  344. insert_point = content.rfind('</w:styles>')
  345. if insert_point != -1:
  346. content = content[:insert_point] + hyperlink_style + '\n' + content[insert_point:]
  347. styles_xml_path.write_text(content, encoding='utf-8')
  348. print("Added Hyperlink character style")
  349. def _insert_toc_placeholders(xml_content: str, entries: list = None, toc_style_mapping: dict = None) -> str:
  350. """Insert placeholder TOC entries and heading bookmarks into XML content.
  351. Uses lxml ElementTree for robust XML manipulation instead of fragile regex.
  352. This function does TWO things:
  353. 1. Adds bookmark anchors to each Heading paragraph (so Word can link TOC → heading)
  354. 2. Replaces TOC placeholder area with proper entries containing HYPERLINK + PAGEREF
  355. Args:
  356. xml_content: The XML content of document.xml
  357. entries: List of placeholder entries with 'level', 'text', 'page' keys
  358. toc_style_mapping: Dictionary mapping level to style ID
  359. Returns:
  360. Modified XML content with bookmarks and TOC placeholders
  361. Raises:
  362. RuntimeError: If TOC structure cannot be found or is malformed
  363. """
  364. from lxml import etree
  365. if entries is None:
  366. entries = [{"level": 1, "text": "Contents", "page": "1"}]
  367. if toc_style_mapping is None:
  368. toc_style_mapping = {1: "9", 2: "11", 3: "12"}
  369. W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
  370. R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
  371. # Parse XML
  372. root = etree.fromstring(xml_content.encode('utf-8'))
  373. nsmap = {'w': W, 'r': R_NS}
  374. # ── Step 1: Add bookmarks to Heading paragraphs ──
  375. bookmark_id_counter = 100000
  376. heading_bookmark_map = {} # text → first bookmark_name (backward compat)
  377. heading_bookmark_map_all = {} # text → [list of bookmark_names] for duplicate headings
  378. for para in root.iter(f'{{{W}}}p'):
  379. # Find pStyle
  380. ppr = para.find(f'{{{W}}}pPr')
  381. if ppr is None:
  382. continue
  383. pstyle = ppr.find(f'{{{W}}}pStyle')
  384. if pstyle is None:
  385. continue
  386. style_val = pstyle.get(f'{{{W}}}val', '')
  387. if not re.match(r'Heading\d$', style_val):
  388. continue
  389. # Extract heading text
  390. texts = []
  391. for t_elem in para.iter(f'{{{W}}}t'):
  392. if t_elem.text:
  393. texts.append(t_elem.text)
  394. heading_text = ''.join(texts).strip()
  395. if not heading_text:
  396. continue
  397. # Skip if already has bookmark
  398. if para.find(f'{{{W}}}bookmarkStart') is not None:
  399. continue
  400. # Generate bookmark
  401. bm_name = f"_Toc{bookmark_id_counter}"
  402. bm_id_str = str(bookmark_id_counter)
  403. bookmark_id_counter += 1
  404. # Store mapping (support duplicate headings)
  405. if heading_text not in heading_bookmark_map_all:
  406. heading_bookmark_map_all[heading_text] = []
  407. heading_bookmark_map_all[heading_text].append(bm_name)
  408. if heading_text not in heading_bookmark_map:
  409. heading_bookmark_map[heading_text] = bm_name
  410. # Insert bookmarkStart after pPr
  411. bm_start = etree.Element(f'{{{W}}}bookmarkStart')
  412. bm_start.set(f'{{{W}}}id', bm_id_str)
  413. bm_start.set(f'{{{W}}}name', bm_name)
  414. bm_end = etree.Element(f'{{{W}}}bookmarkEnd')
  415. bm_end.set(f'{{{W}}}id', bm_id_str)
  416. ppr_index = list(para).index(ppr)
  417. para.insert(ppr_index + 1, bm_start)
  418. # bookmarkEnd at end of paragraph
  419. para.append(bm_end)
  420. bookmarks_added = len(heading_bookmark_map)
  421. if bookmarks_added > 0:
  422. print(f"Added {bookmarks_added} bookmarks to Heading paragraphs")
  423. # ── Step 2: Find TOC field structure (begin → instrText → separate → end) ──
  424. toc_separate_para = None
  425. toc_end_para = None
  426. # Track field nesting to handle nested fields correctly
  427. field_stack = []
  428. toc_field_depth = None
  429. for fld_char in root.iter(f'{{{W}}}fldChar'):
  430. fld_type = fld_char.get(f'{{{W}}}fldCharType')
  431. run = fld_char.getparent()
  432. if fld_type == 'begin':
  433. para = run.getparent()
  434. instr_text = ''
  435. found_run = False
  436. for sibling in para:
  437. if sibling is run:
  438. found_run = True
  439. it = sibling.find(f'{{{W}}}instrText')
  440. if it is not None and it.text:
  441. instr_text += it.text
  442. continue
  443. if found_run and sibling.tag == f'{{{W}}}r':
  444. it = sibling.find(f'{{{W}}}instrText')
  445. if it is not None and it.text:
  446. instr_text += it.text
  447. if sibling.find(f'{{{W}}}fldChar') is not None:
  448. break
  449. field_stack.append(instr_text.strip())
  450. if 'TOC' in instr_text and toc_field_depth is None:
  451. toc_field_depth = len(field_stack)
  452. elif fld_type == 'separate':
  453. if toc_field_depth is not None and len(field_stack) == toc_field_depth:
  454. toc_separate_para = run.getparent()
  455. elif fld_type == 'end':
  456. if toc_field_depth is not None and len(field_stack) == toc_field_depth:
  457. toc_end_para = run.getparent()
  458. break
  459. if field_stack:
  460. field_stack.pop()
  461. if toc_separate_para is None or toc_end_para is None:
  462. has_begin = root.find(f'.//{{{W}}}fldChar[@{{{W}}}fldCharType="begin"]') is not None
  463. has_separate = root.find(f'.//{{{W}}}fldChar[@{{{W}}}fldCharType="separate"]') is not None
  464. if not has_begin:
  465. raise RuntimeError(
  466. "TOC FAILED: No field structure found in document. "
  467. "Ensure the code includes a TableOfContents element."
  468. )
  469. elif not has_separate:
  470. raise RuntimeError(
  471. "TOC FAILED: TOC field has 'begin' but no 'separate' fldChar. "
  472. "Run _fix_fld_char_structure() first or check the docx-js version."
  473. )
  474. else:
  475. raise RuntimeError(
  476. "TOC FAILED: Field structure found but no TOC instrText detected. "
  477. "Ensure TableOfContents element generates a TOC \\o field code."
  478. )
  479. # ── Step 3: Remove everything between separate-para and end-para ──
  480. # The TOC paragraphs may be direct children of <w:body> or wrapped in <w:sdt><w:sdtContent>
  481. toc_container = toc_separate_para.getparent() # could be body or sdtContent
  482. container_children = list(toc_container)
  483. sep_idx = container_children.index(toc_separate_para)
  484. end_idx = container_children.index(toc_end_para)
  485. for elem in container_children[sep_idx + 1:end_idx]:
  486. toc_container.remove(elem)
  487. # ── Step 4: Build and insert placeholder paragraphs ──
  488. indent_mapping = {1: 0, 2: 360, 3: 720, 4: 1080, 5: 1440, 6: 1800}
  489. heading_occurrence_counter = {}
  490. insert_pos = list(toc_container).index(toc_end_para)
  491. for entry in entries:
  492. level = entry.get('level', 1)
  493. text_raw = entry.get('text', '')
  494. page = entry.get('page', '1')
  495. toc_style = toc_style_mapping.get(level, toc_style_mapping.get(1, "9"))
  496. indent = indent_mapping.get(level, 0)
  497. # Resolve bookmark (handle duplicate headings correctly)
  498. bm_name = ''
  499. if text_raw in heading_bookmark_map_all:
  500. occ = heading_occurrence_counter.get(text_raw, 0)
  501. bm_list = heading_bookmark_map_all[text_raw]
  502. if occ < len(bm_list):
  503. bm_name = bm_list[occ]
  504. heading_occurrence_counter[text_raw] = occ + 1
  505. # Build paragraph element
  506. p = etree.Element(f'{{{W}}}p')
  507. toc_container.insert(insert_pos, p)
  508. insert_pos += 1
  509. # pPr
  510. ppr = etree.SubElement(p, f'{{{W}}}pPr')
  511. pstyle = etree.SubElement(ppr, f'{{{W}}}pStyle')
  512. pstyle.set(f'{{{W}}}val', str(toc_style))
  513. if indent > 0:
  514. ind = etree.SubElement(ppr, f'{{{W}}}ind')
  515. ind.set(f'{{{W}}}left', str(indent))
  516. tabs = etree.SubElement(ppr, f'{{{W}}}tabs')
  517. tab = etree.SubElement(tabs, f'{{{W}}}tab')
  518. tab.set(f'{{{W}}}val', 'right')
  519. tab.set(f'{{{W}}}leader', 'dot')
  520. tab.set(f'{{{W}}}pos', '9026')
  521. spacing = etree.SubElement(ppr, f'{{{W}}}spacing')
  522. spacing.set(f'{{{W}}}before', '120')
  523. spacing.set(f'{{{W}}}after', '60')
  524. if bm_name:
  525. hyperlink = etree.SubElement(p, f'{{{W}}}hyperlink')
  526. hyperlink.set(f'{{{W}}}anchor', bm_name)
  527. hyperlink.set(f'{{{W}}}history', '1')
  528. r_text = etree.SubElement(hyperlink, f'{{{W}}}r')
  529. rpr = etree.SubElement(r_text, f'{{{W}}}rPr')
  530. rstyle = etree.SubElement(rpr, f'{{{W}}}rStyle')
  531. rstyle.set(f'{{{W}}}val', 'Hyperlink')
  532. t = etree.SubElement(r_text, f'{{{W}}}t')
  533. t.text = text_raw
  534. r_tab = etree.SubElement(hyperlink, f'{{{W}}}r')
  535. etree.SubElement(r_tab, f'{{{W}}}tab')
  536. r_begin = etree.SubElement(hyperlink, f'{{{W}}}r')
  537. fc_begin = etree.SubElement(r_begin, f'{{{W}}}fldChar')
  538. fc_begin.set(f'{{{W}}}fldCharType', 'begin')
  539. r_instr = etree.SubElement(hyperlink, f'{{{W}}}r')
  540. instr = etree.SubElement(r_instr, f'{{{W}}}instrText')
  541. instr.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve')
  542. instr.text = f' PAGEREF {bm_name} \\h '
  543. r_sep = etree.SubElement(hyperlink, f'{{{W}}}r')
  544. fc_sep = etree.SubElement(r_sep, f'{{{W}}}fldChar')
  545. fc_sep.set(f'{{{W}}}fldCharType', 'separate')
  546. r_page = etree.SubElement(hyperlink, f'{{{W}}}r')
  547. t_page = etree.SubElement(r_page, f'{{{W}}}t')
  548. t_page.text = str(page)
  549. r_end = etree.SubElement(hyperlink, f'{{{W}}}r')
  550. fc_end = etree.SubElement(r_end, f'{{{W}}}fldChar')
  551. fc_end.set(f'{{{W}}}fldCharType', 'end')
  552. else:
  553. r_text = etree.SubElement(p, f'{{{W}}}r')
  554. t = etree.SubElement(r_text, f'{{{W}}}t')
  555. t.text = text_raw
  556. r_tab = etree.SubElement(p, f'{{{W}}}r')
  557. etree.SubElement(r_tab, f'{{{W}}}tab')
  558. r_page = etree.SubElement(p, f'{{{W}}}r')
  559. t_page = etree.SubElement(r_page, f'{{{W}}}t')
  560. t_page.text = str(page)
  561. placeholders_inserted = len(entries)
  562. print(f"Inserted {placeholders_inserted} TOC placeholder entries")
  563. # Serialize back to string
  564. result = etree.tostring(root, xml_declaration=True, encoding='UTF-8', standalone=True)
  565. return result.decode('utf-8')
  566. def main():
  567. parser = argparse.ArgumentParser(
  568. description='Add placeholder entries to Table of Contents in a DOCX file (in-place)'
  569. )
  570. parser.add_argument('docx_file', help='DOCX file to modify (will be replaced)')
  571. parser.add_argument(
  572. '--auto', action='store_true',
  573. help='Auto-extract Heading 1-3 from the DOCX as TOC entries (recommended)'
  574. )
  575. parser.add_argument(
  576. '--entries',
  577. help='JSON string with placeholder entries: [{"level":1,"text":"Chapter 1","page":"1"}]'
  578. )
  579. args = parser.parse_args()
  580. # Determine entries
  581. entries = None
  582. if args.entries:
  583. try:
  584. entries = json.loads(args.entries)
  585. except json.JSONDecodeError as e:
  586. print(f"Error parsing entries JSON: {e}", file=sys.stderr)
  587. sys.exit(1)
  588. elif args.auto or True:
  589. # Default to auto mode — always extract from document headings
  590. entries = _extract_headings_from_docx(args.docx_file)
  591. if entries:
  592. print(f"Auto-extracted {len(entries)} headings from document", file=sys.stderr)
  593. else:
  594. print("No headings found in document, using minimal placeholder", file=sys.stderr)
  595. entries = [{"level": 1, "text": "Contents", "page": "1"}]
  596. # Add placeholders
  597. try:
  598. add_toc_placeholders(args.docx_file, entries)
  599. print(f"Successfully added TOC placeholders to {args.docx_file}")
  600. except RuntimeError as e:
  601. # TOC structure errors — hard fail with exit code 1
  602. print(f"ERROR: {e}", file=sys.stderr)
  603. sys.exit(1)
  604. except Exception as e:
  605. print(f"Error: {e}", file=sys.stderr)
  606. sys.exit(1)
  607. if __name__ == '__main__':
  608. main()