fix_footer_fields.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #!/usr/bin/env python3
  2. """
  3. Fix footer PAGE field instructions in a DOCX file for WPS/Word compatibility.
  4. docx-js generates bare `PAGE` instrText in footers, but WPS ignores `pgNumType fmt`
  5. from section properties, causing page numbers to display as raw field codes like
  6. "PAGE \* arabic \* MERGEFORMAT" instead of actual numbers.
  7. This script:
  8. 1. Reads document.xml to determine each section's page number format
  9. (Roman vs Arabic) based on <w:pgNumType> and footer relationships
  10. 2. Patches each footer XML: replaces bare ` PAGE ` with the correct
  11. format-switch variant (` PAGE \\* arabic \\* MERGEFORMAT` or
  12. ` PAGE \\* ROMAN \\* MERGEFORMAT`)
  13. 3. Removes empty <w:pgNumType/> from cover sections (docx-js emits
  14. these even when no pageNumbers is set, confusing WPS)
  15. 4. Replaces the original file in-place
  16. Usage:
  17. "$(command -v zcode-python || command -v python3)" fix_footer_fields.py <docx_file>
  18. "$(command -v zcode-python || command -v python3)" fix_footer_fields.py <docx_file> --dry-run # preview changes only
  19. Example:
  20. "$(command -v zcode-python || command -v python3)" fix_footer_fields.py output.docx
  21. """
  22. import argparse
  23. import re
  24. import shutil
  25. import sys
  26. import tempfile
  27. import zipfile
  28. from pathlib import Path
  29. # ── Namespace helpers ──────────────────────────────────────────────
  30. W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
  31. R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
  32. # Patterns
  33. # Match bare PAGE (not already followed by \*)
  34. BARE_PAGE_RE = re.compile(
  35. r'(<w:instrText[^>]*>)\s*PAGE\s*(</w:instrText>)'
  36. )
  37. # Match PAGE that already has a format switch (to detect and possibly fix)
  38. EXISTING_FORMAT_RE = re.compile(
  39. r'(<w:instrText[^>]*>)\s*PAGE\s+\\\*\s+\w+.*?(</w:instrText>)'
  40. )
  41. # Match PAGE with wrong \* decimal format (common bug)
  42. DECIMAL_BUG_RE = re.compile(
  43. r'(<w:instrText[^>]*>)\s*PAGE\s+\\\*\s+decimal\b[^<]*(</w:instrText>)'
  44. )
  45. # Empty pgNumType
  46. EMPTY_PGNUMTYPE_RE = re.compile(r'<w:pgNumType/>')
  47. # pgNumType with fmt attribute
  48. PGNUMTYPE_FMT_RE = re.compile(r'<w:pgNumType[^/]*?\bw:fmt="([^"]*)"')
  49. # Footer reference in sectPr
  50. FOOTER_REF_RE = re.compile(
  51. r'<w:footerReference[^>]*r:id="([^"]*)"[^>]*/?>|'
  52. r'<w:footerReference[^>]*r:id="([^"]*)"[^>]*>.*?</w:footerReference>'
  53. )
  54. # Section properties
  55. SECT_PR_RE = re.compile(r'<w:sectPr\b[^>]*>.*?</w:sectPr>', re.DOTALL)
  56. def _determine_section_formats(document_xml: str, rels_content: str) -> dict:
  57. """Parse document.xml to map footer rId → format ('arabic' or 'ROMAN').
  58. Strategy:
  59. - Find each <w:sectPr> block
  60. - Extract <w:pgNumType w:fmt="..."> if present
  61. - Extract <w:footerReference r:id="...">
  62. - Map rId to the inferred format
  63. If pgNumType has fmt="upperRoman" or "lowerRoman" → ROMAN
  64. Otherwise (including "decimal", absent, etc.) → arabic
  65. Returns:
  66. dict mapping rId (e.g. "rId8") to format string ("arabic" or "ROMAN")
  67. """
  68. fmt_map = {} # rId → "arabic" | "ROMAN"
  69. for sect_match in SECT_PR_RE.finditer(document_xml):
  70. sect_xml = sect_match.group(0)
  71. # Determine format from pgNumType
  72. fmt_match = PGNUMTYPE_FMT_RE.search(sect_xml)
  73. if fmt_match:
  74. fmt_val = fmt_match.group(1).lower()
  75. if "roman" in fmt_val:
  76. page_format = "ROMAN"
  77. else:
  78. page_format = "arabic"
  79. else:
  80. # No pgNumType or no fmt → default to arabic
  81. page_format = "arabic"
  82. # Find footer references in this section
  83. for fref_match in FOOTER_REF_RE.finditer(sect_xml):
  84. rid = fref_match.group(1) or fref_match.group(2)
  85. if rid:
  86. fmt_map[rid] = page_format
  87. return fmt_map
  88. def _resolve_footer_files(rels_content: str) -> dict:
  89. """Parse document.xml.rels to map rId → footer filename.
  90. Returns:
  91. dict mapping rId (e.g. "rId8") to filename (e.g. "footer1.xml")
  92. """
  93. rid_to_file = {}
  94. # Match Relationship elements for footer targets
  95. rel_re = re.compile(
  96. r'<Relationship[^>]*\bId="([^"]*)"[^>]*\bTarget="([^"]*footer[^"]*)"',
  97. re.IGNORECASE
  98. )
  99. for m in rel_re.finditer(rels_content):
  100. rid = m.group(1)
  101. target = m.group(2)
  102. # Target is like "footer1.xml" or "word/footer1.xml"
  103. filename = target.split("/")[-1]
  104. rid_to_file[rid] = filename
  105. return rid_to_file
  106. def _patch_footer_xml(footer_xml: str, page_format: str) -> tuple:
  107. """Patch a single footer XML string.
  108. Args:
  109. footer_xml: Raw XML content of footer file
  110. page_format: "arabic" or "ROMAN"
  111. Returns:
  112. (patched_xml, changes_list)
  113. """
  114. changes = []
  115. result = footer_xml
  116. # Fix 1: Replace \* decimal with \* arabic (common bug)
  117. if DECIMAL_BUG_RE.search(result):
  118. replacement = rf'\g<1> PAGE \\* {page_format} \\* MERGEFORMAT \g<2>'
  119. result = DECIMAL_BUG_RE.sub(replacement, result)
  120. changes.append(f"Fixed \\* decimal → \\* {page_format}")
  121. # Fix 2: Patch bare PAGE (no format switch at all)
  122. if BARE_PAGE_RE.search(result):
  123. replacement = rf'\g<1> PAGE \\* {page_format} \\* MERGEFORMAT \g<2>'
  124. result = BARE_PAGE_RE.sub(replacement, result)
  125. changes.append(f"Added \\* {page_format} \\* MERGEFORMAT to bare PAGE")
  126. return result, changes
  127. def fix_footer_fields(docx_path: str, dry_run: bool = False) -> list:
  128. """Fix footer PAGE field instructions in a DOCX file.
  129. Args:
  130. docx_path: Path to DOCX file (modified in-place unless dry_run)
  131. dry_run: If True, only report changes without modifying
  132. Returns:
  133. List of change descriptions
  134. """
  135. docx_path = Path(docx_path)
  136. if not docx_path.exists():
  137. raise FileNotFoundError(f"File not found: {docx_path}")
  138. all_changes = []
  139. with tempfile.TemporaryDirectory() as temp_dir:
  140. temp_path = Path(temp_dir)
  141. extracted_dir = temp_path / "extracted"
  142. temp_output = temp_path / "output.docx"
  143. # Extract DOCX
  144. with zipfile.ZipFile(docx_path, 'r') as zip_ref:
  145. zip_ref.extractall(extracted_dir)
  146. word_dir = extracted_dir / "word"
  147. document_xml_path = word_dir / "document.xml"
  148. rels_path = word_dir / "_rels" / "document.xml.rels"
  149. if not document_xml_path.exists():
  150. raise ValueError("document.xml not found in DOCX")
  151. document_xml = document_xml_path.read_text(encoding='utf-8')
  152. # ── Step 1: Remove empty <w:pgNumType/> from cover section ──
  153. empty_count = len(EMPTY_PGNUMTYPE_RE.findall(document_xml))
  154. if empty_count > 0:
  155. document_xml = EMPTY_PGNUMTYPE_RE.sub('', document_xml)
  156. all_changes.append(
  157. f"Removed {empty_count} empty <w:pgNumType/> from document.xml"
  158. )
  159. if not dry_run:
  160. document_xml_path.write_text(document_xml, encoding='utf-8')
  161. # ── Step 2: Determine section → format mapping ──
  162. rels_content = ""
  163. if rels_path.exists():
  164. rels_content = rels_path.read_text(encoding='utf-8')
  165. rid_to_format = _determine_section_formats(document_xml, rels_content)
  166. rid_to_file = _resolve_footer_files(rels_content)
  167. # Build filename → format mapping
  168. file_to_format = {}
  169. for rid, fmt in rid_to_format.items():
  170. fname = rid_to_file.get(rid)
  171. if fname:
  172. file_to_format[fname] = fmt
  173. # ── Step 3: Patch each footer XML ──
  174. footer_files = sorted(word_dir.glob("footer*.xml"))
  175. if not footer_files:
  176. all_changes.append("No footer files found — nothing to patch")
  177. return all_changes
  178. for footer_path in footer_files:
  179. fname = footer_path.name
  180. # Determine format: use mapping if available, default to arabic
  181. page_format = file_to_format.get(fname, "arabic")
  182. footer_xml = footer_path.read_text(encoding='utf-8')
  183. patched_xml, changes = _patch_footer_xml(footer_xml, page_format)
  184. if changes:
  185. for c in changes:
  186. all_changes.append(f"{fname}: {c}")
  187. if not dry_run:
  188. footer_path.write_text(patched_xml, encoding='utf-8')
  189. else:
  190. all_changes.append(f"{fname}: already correct (format={page_format})")
  191. if not dry_run:
  192. # Repack DOCX
  193. with zipfile.ZipFile(temp_output, 'w', zipfile.ZIP_DEFLATED) as zipf:
  194. for file_path in extracted_dir.rglob('*'):
  195. if file_path.is_file():
  196. arcname = file_path.relative_to(extracted_dir)
  197. zipf.write(file_path, arcname)
  198. # Replace original
  199. shutil.move(str(temp_output), str(docx_path))
  200. return all_changes
  201. def main():
  202. parser = argparse.ArgumentParser(
  203. description=(
  204. 'Fix footer PAGE field instructions in a DOCX file. '
  205. 'Patches bare PAGE → PAGE \\* arabic \\* MERGEFORMAT (or ROMAN), '
  206. 'fixes \\* decimal bug, and removes empty <w:pgNumType/>.'
  207. )
  208. )
  209. parser.add_argument('docx_file', help='DOCX file to fix (modified in-place)')
  210. parser.add_argument(
  211. '--dry-run', action='store_true',
  212. help='Preview changes without modifying the file'
  213. )
  214. args = parser.parse_args()
  215. try:
  216. changes = fix_footer_fields(args.docx_file, dry_run=args.dry_run)
  217. prefix = "[DRY RUN] " if args.dry_run else ""
  218. for c in changes:
  219. print(f" {prefix}{c}")
  220. if args.dry_run:
  221. print("\nDry run complete — no files modified.")
  222. else:
  223. print(f"\nSuccessfully fixed footer fields in {args.docx_file}")
  224. except Exception as e:
  225. print(f"ERROR: {e}", file=sys.stderr)
  226. sys.exit(1)
  227. if __name__ == '__main__':
  228. main()