@blackbelt-technology/pi-dashboard-document-converter 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.pi/skills/document-converter/SKILL.md +79 -0
  2. package/README.md +106 -0
  3. package/engine/.dockerignore +4 -0
  4. package/engine/Dockerfile +75 -0
  5. package/engine/IMAGE_VERSION +1 -0
  6. package/engine/README.md +65 -0
  7. package/engine/VENDOR.md +40 -0
  8. package/engine/build-image.sh +29 -0
  9. package/engine/document_converter/LICENSE +21 -0
  10. package/engine/document_converter/__init__.py +365 -0
  11. package/engine/document_converter/__main__.py +5 -0
  12. package/engine/document_converter/asciidoc_converter.py +534 -0
  13. package/engine/document_converter/cli.py +751 -0
  14. package/engine/document_converter/code_renderer.py +356 -0
  15. package/engine/document_converter/converter.py +928 -0
  16. package/engine/document_converter/cover_page.py +448 -0
  17. package/engine/document_converter/diagram_resizer.py +311 -0
  18. package/engine/document_converter/diagram_sizing.py +357 -0
  19. package/engine/document_converter/docx_reader.py +627 -0
  20. package/engine/document_converter/field_updater.py +277 -0
  21. package/engine/document_converter/font_manager.py +850 -0
  22. package/engine/document_converter/frontmatter_parser.py +644 -0
  23. package/engine/document_converter/graphviz_renderer.py +354 -0
  24. package/engine/document_converter/image_extractor.py +281 -0
  25. package/engine/document_converter/image_style.py +237 -0
  26. package/engine/document_converter/logo_manager.py +1021 -0
  27. package/engine/document_converter/manifest_manager.py +288 -0
  28. package/engine/document_converter/mermaid_renderer.py +371 -0
  29. package/engine/document_converter/meta_mapper.py +398 -0
  30. package/engine/document_converter/pandoc_styles.py +222 -0
  31. package/engine/document_converter/pdf_converter.py +735 -0
  32. package/engine/document_converter/pdf_server.py +283 -0
  33. package/engine/document_converter/plantuml_renderer.py +460 -0
  34. package/engine/document_converter/plantuml_server.py +273 -0
  35. package/engine/document_converter/pyproject.toml +80 -0
  36. package/engine/document_converter/round_trip.py +312 -0
  37. package/engine/document_converter/spacing_applier.py +332 -0
  38. package/engine/document_converter/spacing_config.py +323 -0
  39. package/engine/document_converter/style_extractor.py +420 -0
  40. package/engine/document_converter/svg_embedder.py +294 -0
  41. package/engine/document_converter/system_variables.py +158 -0
  42. package/engine/document_converter/table_formatter.py +450 -0
  43. package/engine/document_converter/template_extractor.py +1334 -0
  44. package/engine/document_converter/template_manager.py +427 -0
  45. package/engine/document_converter/textbox_extractor.py +551 -0
  46. package/engine/document_converter/toc_generator.py +559 -0
  47. package/engine/document_converter/toc_style.py +290 -0
  48. package/engine/document_converter/tree_renderer.py +328 -0
  49. package/engine/document_converter/utils.py +134 -0
  50. package/engine/document_converter/variable_manager.py +394 -0
  51. package/engine/engine_cli.py +371 -0
  52. package/engine/frontmatter_filler/doc-meta.sample.yaml +106 -0
  53. package/engine/frontmatter_filler/fill.py +517 -0
  54. package/engine/markdown_table_profiler/profile.py +442 -0
  55. package/engine/nano-banana-styles.yaml +59 -0
  56. package/engine/tests/test_styled_diagrams.py +109 -0
  57. package/package.json +32 -0
  58. package/src/__tests__/engine.test.ts +72 -0
  59. package/src/__tests__/facade.test.ts +120 -0
  60. package/src/__tests__/integration.test.ts +101 -0
  61. package/src/__tests__/ocr.test.ts +34 -0
  62. package/src/__tests__/provenance.test.ts +89 -0
  63. package/src/__tests__/routing.test.ts +40 -0
  64. package/src/engine.ts +187 -0
  65. package/src/errors.ts +43 -0
  66. package/src/index.ts +179 -0
  67. package/src/ocr.ts +43 -0
  68. package/src/provenance.ts +79 -0
  69. package/src/routing.ts +49 -0
  70. package/src/schema.json +69 -0
  71. package/src/schema.ts +107 -0
  72. package/src/types.ts +90 -0
@@ -0,0 +1,850 @@
1
+ """Font management for DOCX documents.
2
+
3
+ This module provides functionality for:
4
+ - Extracting font information from DOCX files
5
+ - Finding font files in directories (individual and ZIP-archived)
6
+ - Embedding fonts into DOCX files with ODTTF obfuscation
7
+ - Reading font metadata from TTF/OTF files
8
+ """
9
+ import os
10
+ import re
11
+ import shutil
12
+ import uuid
13
+ import zipfile
14
+ from pathlib import Path
15
+ from typing import Dict, List, Optional, Set, Tuple
16
+ from xml.etree import ElementTree as ET
17
+
18
+ # OOXML namespaces
19
+ WORD_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
20
+ REL_NS = 'http://schemas.openxmlformats.org/package/2006/relationships'
21
+ FONT_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/font'
22
+
23
+ # Register namespaces for proper XML output
24
+ ET.register_namespace('w', WORD_NS)
25
+ ET.register_namespace('r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships')
26
+
27
+
28
+ def get_font_name_from_file(font_path: Path) -> Optional[str]:
29
+ """Read the font family name from a TTF/OTF file.
30
+
31
+ Uses fontTools to read the name table from the font file.
32
+
33
+ Args:
34
+ font_path: Path to the font file.
35
+
36
+ Returns:
37
+ Font family name, or None if it cannot be read.
38
+ """
39
+ try:
40
+ from fontTools.ttLib import TTFont
41
+ font = TTFont(font_path)
42
+ # Try to get font family name (nameID 1)
43
+ name = font['name'].getDebugName(1)
44
+ font.close()
45
+ return name
46
+ except ImportError:
47
+ # fontTools not installed, fall back to filename parsing
48
+ return _parse_font_name_from_filename(font_path.stem)
49
+ except Exception:
50
+ return _parse_font_name_from_filename(font_path.stem)
51
+
52
+
53
+ def _parse_font_name_from_filename(filename: str) -> str:
54
+ """Parse font family name from filename.
55
+
56
+ Handles common naming patterns like:
57
+ - SourceSansPro-Regular -> Source Sans Pro
58
+ - source-sans-pro -> Source Sans Pro
59
+ - Arial-Bold -> Arial
60
+
61
+ Args:
62
+ filename: Font filename without extension.
63
+
64
+ Returns:
65
+ Parsed font family name.
66
+ """
67
+ # Remove common suffixes
68
+ suffixes = ['-Regular', '-Bold', '-Italic', '-BoldItalic', '-Light',
69
+ '-Medium', '-Semibold', '-ExtraLight', '-Black',
70
+ '-LightItalic', '-SemiboldItalic', '-BoldIt', '-It']
71
+ name = filename
72
+ for suffix in suffixes:
73
+ if name.lower().endswith(suffix.lower()):
74
+ name = name[:-len(suffix)]
75
+ break
76
+
77
+ # Convert CamelCase to spaces: SourceSansPro -> Source Sans Pro
78
+ name = re.sub(r'([a-z])([A-Z])', r'\1 \2', name)
79
+
80
+ # Convert kebab-case to spaces: source-sans-pro -> source sans pro
81
+ name = name.replace('-', ' ').replace('_', ' ')
82
+
83
+ # Title case and clean up
84
+ name = ' '.join(word.capitalize() for word in name.split())
85
+
86
+ return name
87
+
88
+
89
+ def normalize_font_name(name: str) -> str:
90
+ """Normalize a font name for comparison.
91
+
92
+ Removes spaces, hyphens, underscores and converts to lowercase.
93
+
94
+ Args:
95
+ name: Font name to normalize.
96
+
97
+ Returns:
98
+ Normalized font name.
99
+ """
100
+ return re.sub(r'[\s\-_]', '', name).lower()
101
+
102
+
103
+ def extract_fonts_from_zip(fonts_dir: Path) -> List[Path]:
104
+ """Extract fonts from ZIP files in the fonts directory.
105
+
106
+ Args:
107
+ fonts_dir: Path to fonts directory containing ZIP files.
108
+
109
+ Returns:
110
+ List of paths to extracted font files.
111
+ """
112
+ extracted_fonts = []
113
+ temp_extract_dir = fonts_dir / "_extracted"
114
+
115
+ # Create temporary extraction directory
116
+ temp_extract_dir.mkdir(exist_ok=True)
117
+
118
+ # Find all ZIP files in fonts directory
119
+ zip_files = list(fonts_dir.glob("*.zip"))
120
+
121
+ for zip_file in zip_files:
122
+ try:
123
+ with zipfile.ZipFile(zip_file, 'r') as zip_ref:
124
+ # Extract all font files
125
+ for file_info in zip_ref.filelist:
126
+ # Only extract font files (TTF, OTF)
127
+ if file_info.filename.lower().endswith(('.ttf', '.otf')):
128
+ # Extract to temp directory
129
+ extracted_path = temp_extract_dir / Path(file_info.filename).name
130
+ with zip_ref.open(file_info) as source:
131
+ with open(extracted_path, 'wb') as target:
132
+ target.write(source.read())
133
+ extracted_fonts.append(extracted_path)
134
+ except Exception as e:
135
+ print(f"Warning: Could not extract fonts from {zip_file}: {e}")
136
+
137
+ return extracted_fonts
138
+
139
+
140
+ def get_available_fonts(fonts_dir: Path) -> List[Path]:
141
+ """Get all available font files from fonts directory.
142
+
143
+ Searches both individual font files and ZIP archives.
144
+
145
+ Args:
146
+ fonts_dir: Path to fonts directory.
147
+
148
+ Returns:
149
+ List of paths to font files.
150
+ """
151
+ if not fonts_dir.exists():
152
+ return []
153
+
154
+ fonts = []
155
+
156
+ # Get directly placed font files
157
+ for ext in ['*.ttf', '*.otf', '*.TTF', '*.OTF']:
158
+ fonts.extend(fonts_dir.glob(ext))
159
+
160
+ # Extract and get fonts from ZIP files
161
+ extracted = extract_fonts_from_zip(fonts_dir)
162
+ fonts.extend(extracted)
163
+
164
+ return fonts
165
+
166
+
167
+ def cleanup_extracted_fonts(fonts_dir: Path) -> None:
168
+ """Clean up temporarily extracted fonts.
169
+
170
+ Args:
171
+ fonts_dir: Path to fonts directory.
172
+ """
173
+ temp_extract_dir = fonts_dir / "_extracted"
174
+ if temp_extract_dir.exists():
175
+ shutil.rmtree(temp_extract_dir, ignore_errors=True)
176
+
177
+
178
+ def extract_fonts_from_docx(docx_path: Path) -> Dict[str, dict]:
179
+ """Extract font information from a DOCX file's fontTable.xml.
180
+
181
+ Reads the font table to identify all fonts used in the document
182
+ and whether they have embedded font data.
183
+
184
+ Args:
185
+ docx_path: Path to the DOCX file.
186
+
187
+ Returns:
188
+ Dictionary mapping font names to their info:
189
+ {
190
+ 'Source Sans Pro': {
191
+ 'name': 'Source Sans Pro',
192
+ 'embedded': False,
193
+ 'embed_regular': None, # relationship ID if embedded
194
+ 'embed_bold': None,
195
+ 'embed_italic': None,
196
+ 'embed_bold_italic': None,
197
+ }
198
+ }
199
+ """
200
+ fonts = {}
201
+
202
+ try:
203
+ with zipfile.ZipFile(docx_path, 'r') as docx:
204
+ # Read fontTable.xml
205
+ if 'word/fontTable.xml' not in docx.namelist():
206
+ return fonts
207
+
208
+ font_table_xml = docx.read('word/fontTable.xml')
209
+ root = ET.fromstring(font_table_xml)
210
+
211
+ # Find all font elements
212
+ for font_elem in root.findall(f'.//{{{WORD_NS}}}font'):
213
+ font_name = font_elem.get(f'{{{WORD_NS}}}name')
214
+ if not font_name:
215
+ continue
216
+
217
+ font_info = {
218
+ 'name': font_name,
219
+ 'embedded': False,
220
+ 'embed_regular': None,
221
+ 'embed_bold': None,
222
+ 'embed_italic': None,
223
+ 'embed_bold_italic': None,
224
+ }
225
+
226
+ # Check for embedded font references
227
+ embed_regular = font_elem.find(f'{{{WORD_NS}}}embedRegular')
228
+ embed_bold = font_elem.find(f'{{{WORD_NS}}}embedBold')
229
+ embed_italic = font_elem.find(f'{{{WORD_NS}}}embedItalic')
230
+ embed_bold_italic = font_elem.find(f'{{{WORD_NS}}}embedBoldItalic')
231
+
232
+ r_ns = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
233
+
234
+ if embed_regular is not None:
235
+ font_info['embed_regular'] = embed_regular.get(f'{{{r_ns}}}id')
236
+ font_info['embedded'] = True
237
+ if embed_bold is not None:
238
+ font_info['embed_bold'] = embed_bold.get(f'{{{r_ns}}}id')
239
+ font_info['embedded'] = True
240
+ if embed_italic is not None:
241
+ font_info['embed_italic'] = embed_italic.get(f'{{{r_ns}}}id')
242
+ font_info['embedded'] = True
243
+ if embed_bold_italic is not None:
244
+ font_info['embed_bold_italic'] = embed_bold_italic.get(f'{{{r_ns}}}id')
245
+ font_info['embedded'] = True
246
+
247
+ fonts[font_name] = font_info
248
+
249
+ except Exception as e:
250
+ print(f"Warning: Could not read fonts from {docx_path}: {e}")
251
+
252
+ return fonts
253
+
254
+
255
+ def extract_embedded_fonts(docx_path: Path, output_dir: Path) -> List[Path]:
256
+ """Extract and deobfuscate embedded fonts from a DOCX file.
257
+
258
+ DOCX files store embedded fonts as ODTTF files with XOR obfuscation.
259
+ This function extracts and deobfuscates them to standard TTF/OTF.
260
+
261
+ Args:
262
+ docx_path: Path to the DOCX file.
263
+ output_dir: Directory to save extracted fonts.
264
+
265
+ Returns:
266
+ List of paths to extracted font files.
267
+ """
268
+ extracted = []
269
+ output_dir.mkdir(parents=True, exist_ok=True)
270
+
271
+ try:
272
+ with zipfile.ZipFile(docx_path, 'r') as docx:
273
+ # Find all font files in word/fonts/
274
+ font_files = [f for f in docx.namelist()
275
+ if f.startswith('word/fonts/') and f.endswith('.odttf')]
276
+
277
+ # Read relationships to get font GUIDs for deobfuscation
278
+ rels = {}
279
+ if 'word/_rels/fontTable.xml.rels' in docx.namelist():
280
+ rels_xml = docx.read('word/_rels/fontTable.xml.rels')
281
+ rels_root = ET.fromstring(rels_xml)
282
+ for rel in rels_root.findall(f'.//{{{REL_NS}}}Relationship'):
283
+ rel_id = rel.get('Id')
284
+ target = rel.get('Target')
285
+ if target:
286
+ # Extract GUID from target path like fonts/{GUID}.odttf
287
+ match = re.search(r'\{([A-Fa-f0-9\-]+)\}', target)
288
+ if match:
289
+ rels[target] = match.group(1)
290
+
291
+ for font_file in font_files:
292
+ # Read obfuscated font data
293
+ obfuscated_data = docx.read(font_file)
294
+
295
+ # Get GUID for deobfuscation
296
+ font_filename = Path(font_file).name
297
+ guid = None
298
+ for target, g in rels.items():
299
+ if font_filename in target:
300
+ guid = g
301
+ break
302
+
303
+ if guid:
304
+ # Deobfuscate
305
+ deobfuscated_data = _deobfuscate_font(obfuscated_data, guid)
306
+ else:
307
+ # Try to extract GUID from filename
308
+ match = re.search(r'\{([A-Fa-f0-9\-]+)\}', font_filename)
309
+ if match:
310
+ guid = match.group(1)
311
+ deobfuscated_data = _deobfuscate_font(obfuscated_data, guid)
312
+ else:
313
+ deobfuscated_data = obfuscated_data
314
+
315
+ # Determine output filename from font metadata
316
+ temp_path = output_dir / font_filename.replace('.odttf', '.ttf')
317
+ temp_path.write_bytes(deobfuscated_data)
318
+
319
+ # Try to read actual font name
320
+ font_name = get_font_name_from_file(temp_path)
321
+ if font_name:
322
+ # Rename with proper name
323
+ proper_name = font_name.replace(' ', '') + '.ttf'
324
+ proper_path = output_dir / proper_name
325
+ if temp_path != proper_path:
326
+ temp_path.rename(proper_path)
327
+ temp_path = proper_path
328
+
329
+ extracted.append(temp_path)
330
+
331
+ except Exception as e:
332
+ print(f"Warning: Could not extract embedded fonts from {docx_path}: {e}")
333
+
334
+ return extracted
335
+
336
+
337
+ def _deobfuscate_font(data: bytes, guid: str) -> bytes:
338
+ """Deobfuscate ODTTF font data using XOR with GUID-derived key.
339
+
340
+ The OOXML specification uses XOR obfuscation with a 32-byte key
341
+ derived from the font's GUID. Only the first 32 bytes are obfuscated.
342
+
343
+ Args:
344
+ data: Obfuscated font data.
345
+ guid: GUID string (with or without braces/hyphens).
346
+
347
+ Returns:
348
+ Deobfuscated font data.
349
+ """
350
+ # Clean GUID and convert to bytes
351
+ guid_clean = guid.replace('{', '').replace('}', '').replace('-', '')
352
+
353
+ # Convert hex string to bytes (reverse byte order for each pair)
354
+ try:
355
+ guid_bytes = bytes.fromhex(guid_clean)
356
+ except ValueError:
357
+ return data # Return as-is if GUID is invalid
358
+
359
+ # Create 32-byte key by repeating the 16-byte GUID twice (reversed)
360
+ key = guid_bytes[::-1] + guid_bytes[::-1]
361
+
362
+ # XOR first 32 bytes
363
+ result = bytearray(data)
364
+ for i in range(min(32, len(result))):
365
+ result[i] ^= key[i]
366
+
367
+ return bytes(result)
368
+
369
+
370
+ def _obfuscate_font(data: bytes, guid: str) -> bytes:
371
+ """Obfuscate font data for embedding in DOCX.
372
+
373
+ Uses the same XOR algorithm as deobfuscation (XOR is its own inverse).
374
+
375
+ Args:
376
+ data: Font data to obfuscate.
377
+ guid: GUID string to use as key.
378
+
379
+ Returns:
380
+ Obfuscated font data (ODTTF format).
381
+ """
382
+ return _deobfuscate_font(data, guid) # XOR is symmetric
383
+
384
+
385
+ def find_font_file(
386
+ font_name: str,
387
+ search_dirs: List[Path],
388
+ include_system: bool = True
389
+ ) -> Dict[str, Path]:
390
+ """Find font files matching a font name.
391
+
392
+ Searches in the provided directories for font files that match
393
+ the given font name. Supports individual files and ZIP archives.
394
+
395
+ Args:
396
+ font_name: Font family name to search for.
397
+ search_dirs: List of directories to search.
398
+ include_system: Whether to search system font directories.
399
+
400
+ Returns:
401
+ Dictionary mapping variant names to file paths:
402
+ {
403
+ 'regular': Path('/path/to/Font-Regular.ttf'),
404
+ 'bold': Path('/path/to/Font-Bold.ttf'),
405
+ 'italic': Path('/path/to/Font-Italic.ttf'),
406
+ 'bolditalic': Path('/path/to/Font-BoldItalic.ttf'),
407
+ }
408
+ """
409
+ found = {}
410
+ normalized_name = normalize_font_name(font_name)
411
+
412
+ # Collect all font files from search directories
413
+ all_fonts = []
414
+ for search_dir in search_dirs:
415
+ if search_dir and search_dir.exists():
416
+ all_fonts.extend(get_available_fonts(search_dir))
417
+
418
+ # Search system fonts if requested
419
+ if include_system:
420
+ system_fonts = _get_system_font_dirs()
421
+ for sys_dir in system_fonts:
422
+ if sys_dir.exists():
423
+ for ext in ['*.ttf', '*.otf', '*.TTF', '*.OTF']:
424
+ all_fonts.extend(sys_dir.glob(ext))
425
+
426
+ # Match fonts by name
427
+ for font_path in all_fonts:
428
+ # Get font name from file
429
+ file_font_name = get_font_name_from_file(font_path)
430
+ if file_font_name and normalize_font_name(file_font_name) == normalized_name:
431
+ variant = _detect_font_variant(font_path)
432
+ if variant not in found:
433
+ found[variant] = font_path
434
+
435
+ return found
436
+
437
+
438
+ def _get_system_font_dirs() -> List[Path]:
439
+ """Get system font directories for the current platform.
440
+
441
+ Returns:
442
+ List of system font directory paths.
443
+ """
444
+ import platform
445
+ system = platform.system()
446
+
447
+ dirs = []
448
+ if system == 'Darwin': # macOS
449
+ dirs = [
450
+ Path('/Library/Fonts'),
451
+ Path('/System/Library/Fonts'),
452
+ Path.home() / 'Library/Fonts',
453
+ ]
454
+ elif system == 'Windows':
455
+ windir = os.environ.get('WINDIR', 'C:\\Windows')
456
+ dirs = [
457
+ Path(windir) / 'Fonts',
458
+ Path.home() / 'AppData/Local/Microsoft/Windows/Fonts',
459
+ ]
460
+ else: # Linux
461
+ dirs = [
462
+ Path('/usr/share/fonts'),
463
+ Path('/usr/local/share/fonts'),
464
+ Path.home() / '.fonts',
465
+ Path.home() / '.local/share/fonts',
466
+ ]
467
+
468
+ return [d for d in dirs if d.exists()]
469
+
470
+
471
+ def _detect_font_variant(font_path: Path) -> str:
472
+ """Detect the font variant (regular, bold, italic, etc.) from a font file.
473
+
474
+ Args:
475
+ font_path: Path to the font file.
476
+
477
+ Returns:
478
+ Variant name: 'regular', 'bold', 'italic', or 'bolditalic'.
479
+ """
480
+ filename = font_path.stem.lower()
481
+
482
+ if 'bolditalic' in filename or 'boldit' in filename or ('bold' in filename and 'italic' in filename):
483
+ return 'bolditalic'
484
+ elif 'bold' in filename:
485
+ return 'bold'
486
+ elif 'italic' in filename or filename.endswith('it'):
487
+ return 'italic'
488
+ else:
489
+ return 'regular'
490
+
491
+
492
+ def resolve_template_fonts(
493
+ docx_path: Path,
494
+ template_fonts_dir: Optional[Path] = None,
495
+ default_fonts_dir: Optional[Path] = None,
496
+ include_system: bool = True
497
+ ) -> Dict[str, Dict[str, Path]]:
498
+ """Resolve all fonts used in a DOCX to their font files.
499
+
500
+ Args:
501
+ docx_path: Path to the DOCX file.
502
+ template_fonts_dir: Template's fonts directory (searched first).
503
+ default_fonts_dir: Default template's fonts directory (fallback).
504
+ include_system: Whether to search system fonts as last resort.
505
+
506
+ Returns:
507
+ Dictionary mapping font names to variant paths:
508
+ {
509
+ 'Source Sans Pro': {
510
+ 'regular': Path('/path/to/SourceSansPro-Regular.ttf'),
511
+ 'bold': Path('/path/to/SourceSansPro-Bold.ttf'),
512
+ },
513
+ 'Arial': {
514
+ 'regular': Path('/path/to/Arial.ttf'),
515
+ }
516
+ }
517
+ """
518
+ result = {}
519
+
520
+ # Get fonts used in the document
521
+ doc_fonts = extract_fonts_from_docx(docx_path)
522
+
523
+ # Build search directories (order matters: template first, then default)
524
+ search_dirs = []
525
+ if template_fonts_dir and template_fonts_dir.exists():
526
+ search_dirs.append(template_fonts_dir)
527
+ if default_fonts_dir and default_fonts_dir.exists():
528
+ search_dirs.append(default_fonts_dir)
529
+
530
+ # Resolve each font
531
+ for font_name, font_info in doc_fonts.items():
532
+ # Skip if already embedded
533
+ if font_info['embedded']:
534
+ continue
535
+
536
+ # Find font files
537
+ found = find_font_file(font_name, search_dirs, include_system)
538
+ if found:
539
+ result[font_name] = found
540
+
541
+ return result
542
+
543
+
544
+ def _add_odttf_content_type(docx_path: Path) -> None:
545
+ """Add odttf content type to [Content_Types].xml if not present.
546
+
547
+ DOCX files need to declare the content type for .odttf (obfuscated font) files.
548
+ Without this, Word will report "unreadable content" errors.
549
+
550
+ Args:
551
+ docx_path: Path to the DOCX file.
552
+ """
553
+ try:
554
+ with zipfile.ZipFile(docx_path, 'r') as docx_in:
555
+ content_types_xml = docx_in.read('[Content_Types].xml').decode('utf-8')
556
+
557
+ # Check if odttf extension is already declared
558
+ if 'Extension="odttf"' in content_types_xml:
559
+ return # Already present
560
+
561
+ # Use string manipulation to add the odttf extension
562
+ # This preserves the original XML format without namespace prefix issues
563
+ odttf_default = '<Default Extension="odttf" ContentType="application/vnd.openxmlformats-officedocument.obfuscatedFont"/>'
564
+
565
+ # Insert after <Types ...> opening tag
566
+ import re
567
+ pattern = r'(<Types[^>]*>)'
568
+ replacement = r'\1' + odttf_default
569
+ modified_xml = re.sub(pattern, replacement, content_types_xml)
570
+
571
+ # Write back
572
+ temp_path = docx_path.with_suffix('.docx.tmp')
573
+ with zipfile.ZipFile(docx_path, 'r') as docx_in:
574
+ with zipfile.ZipFile(temp_path, 'w', zipfile.ZIP_DEFLATED) as docx_out:
575
+ for item in docx_in.namelist():
576
+ if item == '[Content_Types].xml':
577
+ docx_out.writestr(item, modified_xml.encode('utf-8'))
578
+ else:
579
+ docx_out.writestr(item, docx_in.read(item))
580
+
581
+ # Replace original
582
+ docx_path.unlink()
583
+ temp_path.rename(docx_path)
584
+
585
+ except Exception as e:
586
+ print(f"Warning: Could not add odttf content type: {e}")
587
+
588
+
589
+ def embed_font_in_docx(
590
+ docx_path: Path,
591
+ font_name: str,
592
+ font_files: Dict[str, Path],
593
+ output_path: Optional[Path] = None
594
+ ) -> bool:
595
+ """Embed font files into a DOCX document.
596
+
597
+ Uses string manipulation to preserve original XML structure and namespaces,
598
+ avoiding ElementTree's namespace prefix issues that cause Word corruption.
599
+
600
+ Args:
601
+ docx_path: Path to the DOCX file.
602
+ font_name: Font family name as it appears in the document.
603
+ font_files: Dictionary mapping variants to font file paths.
604
+ output_path: Output path (defaults to overwriting input).
605
+
606
+ Returns:
607
+ True if fonts were embedded successfully.
608
+ """
609
+ if not font_files:
610
+ return False
611
+
612
+ if output_path is None:
613
+ output_path = docx_path
614
+
615
+ temp_path = output_path.with_suffix('.docx.tmp')
616
+
617
+ try:
618
+ # Read the DOCX as a zip
619
+ with zipfile.ZipFile(docx_path, 'r') as docx_in:
620
+ # Read fontTable.xml as string to preserve formatting
621
+ font_table_xml = docx_in.read('word/fontTable.xml').decode('utf-8')
622
+
623
+ # Check if font exists in table
624
+ # Look for w:font w:name="Font Name" pattern
625
+ font_pattern = rf'<w:font\s+w:name="{re.escape(font_name)}"[^>]*>'
626
+ if not re.search(font_pattern, font_table_xml):
627
+ return False
628
+
629
+ # Read existing relationships or prepare new content
630
+ rels_xml = ''
631
+ existing_rels = []
632
+ if 'word/_rels/fontTable.xml.rels' in docx_in.namelist():
633
+ rels_xml = docx_in.read('word/_rels/fontTable.xml.rels').decode('utf-8')
634
+ # Extract existing relationship IDs
635
+ existing_rels = re.findall(r'Id="(rId\d+)"', rels_xml)
636
+
637
+ # Prepare embed elements and relationships
638
+ rel_id_counter = len(existing_rels) + 1
639
+ new_rels = []
640
+ embed_elements = []
641
+
642
+ variant_to_element = {
643
+ 'regular': 'embedRegular',
644
+ 'bold': 'embedBold',
645
+ 'italic': 'embedItalic',
646
+ 'bolditalic': 'embedBoldItalic',
647
+ }
648
+
649
+ font_files_to_write = {}
650
+
651
+ for variant, font_file in font_files.items():
652
+ if variant not in variant_to_element:
653
+ continue
654
+
655
+ elem_name = variant_to_element[variant]
656
+
657
+ # Generate GUID for obfuscation
658
+ font_guid = str(uuid.uuid4()).upper()
659
+
660
+ # Generate relationship ID
661
+ while f'rId{rel_id_counter}' in existing_rels:
662
+ rel_id_counter += 1
663
+ rel_id = f'rId{rel_id_counter}'
664
+ existing_rels.append(rel_id)
665
+ rel_id_counter += 1
666
+
667
+ # Prepare font file for writing
668
+ font_filename = f'{{{font_guid}}}.odttf'
669
+ font_data = font_file.read_bytes()
670
+ obfuscated_data = _obfuscate_font(font_data, font_guid)
671
+ font_files_to_write[f'word/fonts/{font_filename}'] = obfuscated_data
672
+
673
+ # Prepare relationship entry
674
+ new_rels.append(
675
+ f'<Relationship Id="{rel_id}" '
676
+ f'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/font" '
677
+ f'Target="fonts/{font_filename}"/>'
678
+ )
679
+
680
+ # Prepare embed element
681
+ embed_elements.append((elem_name, rel_id))
682
+
683
+ # Build embed elements string
684
+ embeds_str = ''
685
+ for elem_name, rel_id in embed_elements:
686
+ embeds_str += f'<w:{elem_name} r:id="{rel_id}"/>'
687
+
688
+ # Find the closing </w:font> tag for the specific font and insert embeds before it
689
+ # Strategy: find the font opening tag, then find its matching </w:font>
690
+
691
+ # First, find where our font element starts
692
+ font_start_pattern = rf'<w:font\s+w:name="{re.escape(font_name)}"'
693
+ font_start_match = re.search(font_start_pattern, font_table_xml)
694
+
695
+ if font_start_match:
696
+ start_pos = font_start_match.start()
697
+ # Find the next </w:font> after this position
698
+ rest_of_xml = font_table_xml[start_pos:]
699
+ close_tag_match = re.search(r'</w:font>', rest_of_xml)
700
+
701
+ if close_tag_match:
702
+ # Calculate absolute position of closing tag
703
+ close_tag_pos = start_pos + close_tag_match.start()
704
+ # Insert embeds just before </w:font>
705
+ modified_font_table = (
706
+ font_table_xml[:close_tag_pos] +
707
+ embeds_str +
708
+ font_table_xml[close_tag_pos:]
709
+ )
710
+ else:
711
+ # No closing tag found - shouldn't happen in valid XML
712
+ modified_font_table = font_table_xml
713
+ else:
714
+ modified_font_table = font_table_xml
715
+
716
+ # Modify or create relationships file
717
+ if rels_xml:
718
+ # Insert new relationships before </Relationships>
719
+ new_rels_str = ''.join(new_rels)
720
+ modified_rels = rels_xml.replace('</Relationships>', new_rels_str + '</Relationships>')
721
+ else:
722
+ # Create new relationships file
723
+ modified_rels = (
724
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
725
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
726
+ + ''.join(new_rels) +
727
+ '</Relationships>'
728
+ )
729
+
730
+ # Write output zip
731
+ with zipfile.ZipFile(temp_path, 'w', zipfile.ZIP_DEFLATED) as docx_out:
732
+ # Copy existing files except fontTable, its rels, and fonts we're replacing
733
+ for item in docx_in.namelist():
734
+ if item == 'word/fontTable.xml':
735
+ continue
736
+ if item == 'word/_rels/fontTable.xml.rels':
737
+ continue
738
+ # Preserve existing font files that aren't being replaced
739
+ if item.startswith('word/fonts/'):
740
+ if item not in font_files_to_write:
741
+ docx_out.writestr(item, docx_in.read(item))
742
+ continue
743
+ docx_out.writestr(item, docx_in.read(item))
744
+
745
+ # Write modified fontTable.xml
746
+ docx_out.writestr('word/fontTable.xml', modified_font_table.encode('utf-8'))
747
+
748
+ # Write relationships
749
+ docx_out.writestr('word/_rels/fontTable.xml.rels', modified_rels.encode('utf-8'))
750
+
751
+ # Write new font files
752
+ for font_path, font_data in font_files_to_write.items():
753
+ docx_out.writestr(font_path, font_data)
754
+
755
+ # Replace original with temp
756
+ if output_path == docx_path:
757
+ docx_path.unlink()
758
+ temp_path.rename(output_path)
759
+
760
+ return True
761
+
762
+ except Exception as e:
763
+ print(f"Warning: Could not embed fonts in {docx_path}: {e}")
764
+ if temp_path.exists():
765
+ temp_path.unlink()
766
+ return False
767
+
768
+
769
+ def embed_template_fonts(
770
+ docx_path: Path,
771
+ template_fonts_dir: Optional[Path] = None,
772
+ default_fonts_dir: Optional[Path] = None,
773
+ include_system: bool = True,
774
+ output_path: Optional[Path] = None
775
+ ) -> Dict[str, bool]:
776
+ """Embed all template fonts into a DOCX document.
777
+
778
+ This is the main orchestration function that:
779
+ 1. Detects fonts used in the document
780
+ 2. Resolves font files from template/default/system directories
781
+ 3. Embeds each font into the document
782
+
783
+ Args:
784
+ docx_path: Path to the DOCX file.
785
+ template_fonts_dir: Template's fonts directory.
786
+ default_fonts_dir: Default template's fonts directory.
787
+ include_system: Whether to search system fonts.
788
+ output_path: Output path (defaults to overwriting input).
789
+
790
+ Returns:
791
+ Dictionary mapping font names to embedding success status.
792
+ """
793
+ results = {}
794
+
795
+ # Resolve fonts
796
+ resolved = resolve_template_fonts(
797
+ docx_path,
798
+ template_fonts_dir,
799
+ default_fonts_dir,
800
+ include_system
801
+ )
802
+
803
+ if not resolved:
804
+ return results
805
+
806
+ # Use output path or input path
807
+ current_path = docx_path
808
+ if output_path and output_path != docx_path:
809
+ shutil.copy2(docx_path, output_path)
810
+ current_path = output_path
811
+
812
+ # Embed each font
813
+ fonts_embedded = False
814
+ for font_name, font_files in resolved.items():
815
+ success = embed_font_in_docx(current_path, font_name, font_files)
816
+ results[font_name] = success
817
+ if success:
818
+ fonts_embedded = True
819
+ print(f"Embedded font: {font_name} ({len(font_files)} variant(s))")
820
+ else:
821
+ print(f"Warning: Could not embed font: {font_name}")
822
+
823
+ # Add odttf content type to [Content_Types].xml if fonts were embedded
824
+ if fonts_embedded:
825
+ _add_odttf_content_type(current_path)
826
+
827
+ # Cleanup extracted fonts
828
+ if template_fonts_dir:
829
+ cleanup_extracted_fonts(template_fonts_dir)
830
+ if default_fonts_dir:
831
+ cleanup_extracted_fonts(default_fonts_dir)
832
+
833
+ return results
834
+
835
+
836
+ # Legacy function for backwards compatibility
837
+ def embed_fonts_in_docx(docx_path: Path, fonts_dir: Path) -> None:
838
+ """Embed fonts from fonts directory into DOCX file.
839
+
840
+ This is a simplified wrapper around embed_template_fonts().
841
+
842
+ Args:
843
+ docx_path: Path to DOCX file.
844
+ fonts_dir: Path to fonts directory containing font files.
845
+ """
846
+ embed_template_fonts(
847
+ docx_path,
848
+ template_fonts_dir=fonts_dir,
849
+ include_system=False
850
+ )