@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,158 @@
1
+ """System variables module for resolving runtime variables in documents.
2
+
3
+ This module provides functionality to resolve system variables like {{$date}},
4
+ {{$fileName}}, {{$year}}, {{$month}}, {{$day}}, and {{$toc}} in document content
5
+ and template variable values.
6
+ """
7
+ import re
8
+ from dataclasses import dataclass, field
9
+ from datetime import date
10
+ from typing import Callable, Dict, Optional
11
+
12
+ # Month names for different languages
13
+ MONTH_NAMES: Dict[str, list] = {
14
+ 'en': ['January', 'February', 'March', 'April', 'May', 'June',
15
+ 'July', 'August', 'September', 'October', 'November', 'December'],
16
+ 'hu': ['januar', 'februar', 'marcius', 'aprilis', 'majus', 'junius',
17
+ 'julius', 'augusztus', 'szeptember', 'oktober', 'november', 'december'],
18
+ 'de': ['Januar', 'Februar', 'Marz', 'April', 'Mai', 'Juni',
19
+ 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
20
+ 'fr': ['janvier', 'fevrier', 'mars', 'avril', 'mai', 'juin',
21
+ 'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'decembre'],
22
+ }
23
+
24
+
25
+ def _format_date_en(d: date) -> str:
26
+ """Format date in English style: January 22, 2026."""
27
+ month_name = MONTH_NAMES['en'][d.month - 1]
28
+ return f"{month_name} {d.day}, {d.year}"
29
+
30
+
31
+ def _format_date_hu(d: date) -> str:
32
+ """Format date in Hungarian style: 2026. januar 22."""
33
+ month_name = MONTH_NAMES['hu'][d.month - 1]
34
+ return f"{d.year}. {month_name} {d.day}."
35
+
36
+
37
+ def _format_date_de(d: date) -> str:
38
+ """Format date in German style: 22. Januar 2026."""
39
+ month_name = MONTH_NAMES['de'][d.month - 1]
40
+ return f"{d.day}. {month_name} {d.year}"
41
+
42
+
43
+ def _format_date_fr(d: date) -> str:
44
+ """Format date in French style: 22 janvier 2026."""
45
+ month_name = MONTH_NAMES['fr'][d.month - 1]
46
+ return f"{d.day} {month_name} {d.year}"
47
+
48
+
49
+ # Date format functions per language
50
+ DATE_FORMATS: Dict[str, Callable[[date], str]] = {
51
+ 'en': _format_date_en,
52
+ 'hu': _format_date_hu,
53
+ 'de': _format_date_de,
54
+ 'fr': _format_date_fr,
55
+ }
56
+
57
+
58
+ @dataclass
59
+ class SystemContext:
60
+ """Context for resolving system variables.
61
+
62
+ Attributes:
63
+ file_name: The output file name (e.g., 'document.docx').
64
+ Note: This should be the output filename, not the input filename,
65
+ so that {{$fileName}} resolves to the final document name.
66
+ language: The language code for date formatting (e.g., 'en', 'hu').
67
+ has_toc_placeholder: Whether the document contains a {{$toc}} placeholder.
68
+ """
69
+ file_name: str
70
+ language: str = 'en'
71
+ has_toc_placeholder: bool = False
72
+
73
+
74
+ def get_formatted_date(language: str) -> str:
75
+ """Get today's date formatted for the specified language.
76
+
77
+ Args:
78
+ language: ISO 639-1 language code (e.g., 'en', 'hu', 'de', 'fr').
79
+
80
+ Returns:
81
+ Formatted date string according to the language conventions.
82
+ Falls back to English format for unknown languages.
83
+ """
84
+ formatter = DATE_FORMATS.get(language, DATE_FORMATS['en'])
85
+ return formatter(date.today())
86
+
87
+
88
+ def detect_toc_placeholder(content: str) -> Optional[int]:
89
+ """Detect the position of {{$toc}} placeholder in content.
90
+
91
+ Args:
92
+ content: The document content to search.
93
+
94
+ Returns:
95
+ The character position of the first {{$toc}} placeholder,
96
+ or None if not found.
97
+ """
98
+ match = re.search(r'\{\{\$toc\}\}', content)
99
+ if match:
100
+ return match.start()
101
+ return None
102
+
103
+
104
+ def get_system_variables(context: SystemContext) -> dict:
105
+ """Get system variables as a dictionary.
106
+
107
+ Returns a dictionary mapping system variable names (without $) to their values.
108
+ This is useful for adding system variables to template replacements.
109
+
110
+ Args:
111
+ context: SystemContext with file name and language.
112
+
113
+ Returns:
114
+ Dictionary mapping variable names to values.
115
+ """
116
+ today = date.today()
117
+
118
+ return {
119
+ '$date': get_formatted_date(context.language),
120
+ '$fileName': context.file_name,
121
+ '$year': str(today.year),
122
+ '$month': f"{today.month:02d}",
123
+ '$day': f"{today.day:02d}",
124
+ }
125
+
126
+
127
+ def resolve_system_variables(text: str, context: SystemContext) -> str:
128
+ """Resolve system variables in text.
129
+
130
+ Replaces system variables with their runtime values:
131
+ - {{$date}}: Current date formatted for the document language
132
+ - {{$fileName}}: Source file name
133
+ - {{$year}}: Current year (4 digits)
134
+ - {{$month}}: Current month (2 digits, zero-padded)
135
+ - {{$day}}: Current day (2 digits, zero-padded)
136
+ - {{$toc}}: Preserved for later processing
137
+
138
+ Args:
139
+ text: The text containing system variables.
140
+ context: SystemContext with file name and language.
141
+
142
+ Returns:
143
+ Text with system variables replaced by their values.
144
+ """
145
+ # Get system variables
146
+ sys_vars = get_system_variables(context)
147
+
148
+ # Build replacements with {{$var}} syntax
149
+ replacements = {f'{{{{{k}}}}}': v for k, v in sys_vars.items()}
150
+
151
+ result = text
152
+ for variable, value in replacements.items():
153
+ result = result.replace(variable, value)
154
+
155
+ # Note: {{$toc}} is intentionally NOT replaced here
156
+ # It's preserved for later processing by the TOC generator
157
+
158
+ return result
@@ -0,0 +1,450 @@
1
+ """Table formatting utilities for DOCX documents."""
2
+ import json
3
+ import re
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+
8
+ from docx import Document
9
+ from docx.shared import Pt, RGBColor, Twips
10
+ from docx.oxml.ns import nsdecls, qn
11
+ from docx.oxml import parse_xml
12
+ from docx.table import Table
13
+
14
+
15
+ @dataclass
16
+ class TableStyleConfig:
17
+ """Configuration for table styling.
18
+
19
+ Attributes:
20
+ header_bg_color: Background color for header row (hex without #).
21
+ header_text_color: Text color for header row (hex without #).
22
+ odd_row_color: Background color for odd data rows (hex without #).
23
+ even_row_color: Background color for even data rows (hex without #).
24
+ border_color: Border color (hex without #).
25
+ border_size: Border size in eighths of a point.
26
+ striped: Whether to use alternating row colors.
27
+ column_widths: Optional dict mapping column names to width multipliers.
28
+ """
29
+ header_bg_color: str = "4472C4"
30
+ header_text_color: str = "FFFFFF"
31
+ odd_row_color: str = "FFFFFF"
32
+ even_row_color: str = "D6DCE5"
33
+ border_color: str = "8EAADB"
34
+ border_size: int = 4
35
+ striped: bool = True
36
+ column_widths: Optional[Dict[str, float]] = None
37
+
38
+ @classmethod
39
+ def from_dict(cls, style_dict: Dict[str, Any]) -> 'TableStyleConfig':
40
+ """Create TableStyleConfig from a dictionary.
41
+
42
+ Args:
43
+ style_dict: Dictionary with style properties.
44
+
45
+ Returns:
46
+ TableStyleConfig with values from dict, defaults for missing keys.
47
+ """
48
+ return cls(
49
+ header_bg_color=style_dict.get('header_bg_color', "4472C4"),
50
+ header_text_color=style_dict.get('header_text_color', "FFFFFF"),
51
+ odd_row_color=style_dict.get('odd_row_color', "FFFFFF"),
52
+ even_row_color=style_dict.get('even_row_color', "D6DCE5"),
53
+ border_color=style_dict.get('border_color', "8EAADB"),
54
+ border_size=style_dict.get('border_size', 4),
55
+ striped=style_dict.get('striped', True),
56
+ column_widths=style_dict.get('column_widths'),
57
+ )
58
+
59
+ def merge(self, override: 'TableStyleConfig') -> 'TableStyleConfig':
60
+ """Merge this config with an override config.
61
+
62
+ Override values take precedence where they differ from defaults.
63
+
64
+ Args:
65
+ override: TableStyleConfig with override values.
66
+
67
+ Returns:
68
+ New TableStyleConfig with merged values.
69
+ """
70
+ default = TableStyleConfig()
71
+ return TableStyleConfig(
72
+ header_bg_color=override.header_bg_color if override.header_bg_color != default.header_bg_color else self.header_bg_color,
73
+ header_text_color=override.header_text_color if override.header_text_color != default.header_text_color else self.header_text_color,
74
+ odd_row_color=override.odd_row_color if override.odd_row_color != default.odd_row_color else self.odd_row_color,
75
+ even_row_color=override.even_row_color if override.even_row_color != default.even_row_color else self.even_row_color,
76
+ border_color=override.border_color if override.border_color != default.border_color else self.border_color,
77
+ border_size=override.border_size if override.border_size != default.border_size else self.border_size,
78
+ striped=override.striped if override.striped != default.striped else self.striped,
79
+ column_widths=override.column_widths if override.column_widths is not None else self.column_widths,
80
+ )
81
+
82
+
83
+ # Default table style configuration
84
+ DEFAULT_TABLE_STYLE = TableStyleConfig()
85
+
86
+
87
+ def parse_table_style_block(content: str) -> List[Tuple[TableStyleConfig, int]]:
88
+ """Parse table style blocks from content.
89
+
90
+ Finds HTML comments in format: <!-- table-style: key=value, key=value -->
91
+
92
+ Args:
93
+ content: The document content to parse.
94
+
95
+ Returns:
96
+ List of tuples (TableStyleConfig, position) for each style block found.
97
+ """
98
+ blocks = []
99
+
100
+ # Pattern to match table-style comments
101
+ pattern = r'<!--\s*table-style:\s*(.+?)\s*-->'
102
+
103
+ for match in re.finditer(pattern, content):
104
+ style_str = match.group(1)
105
+ position = match.start()
106
+
107
+ # Parse key=value pairs
108
+ style_dict: Dict[str, Any] = {}
109
+
110
+ # Handle column_widths JSON specially
111
+ col_widths_match = re.search(r'column_widths=(\{[^}]+\})', style_str)
112
+ if col_widths_match:
113
+ try:
114
+ style_dict['column_widths'] = json.loads(col_widths_match.group(1))
115
+ except json.JSONDecodeError:
116
+ pass
117
+ # Remove from style_str for further parsing
118
+ style_str = style_str.replace(col_widths_match.group(0), '')
119
+
120
+ # Parse remaining key=value pairs
121
+ # Keys that should remain as strings (hex colors)
122
+ color_keys = {'header_bg_color', 'header_text_color', 'odd_row_color',
123
+ 'even_row_color', 'border_color'}
124
+
125
+ for pair in re.findall(r'(\w+)=([^,\s]+)', style_str):
126
+ key, value = pair
127
+ # Convert types
128
+ if value.lower() == 'true':
129
+ style_dict[key] = True
130
+ elif value.lower() == 'false':
131
+ style_dict[key] = False
132
+ elif key in color_keys:
133
+ # Keep color values as strings
134
+ style_dict[key] = value
135
+ elif value.isdigit():
136
+ style_dict[key] = int(value)
137
+ else:
138
+ style_dict[key] = value
139
+
140
+ config = TableStyleConfig.from_dict(style_dict)
141
+ blocks.append((config, position))
142
+
143
+ return blocks
144
+
145
+
146
+ def apply_column_widths(table: Table, widths: Dict[str, float]) -> None:
147
+ """Apply column width multipliers to a table.
148
+
149
+ Args:
150
+ table: The docx Table to modify.
151
+ widths: Dict mapping column header text to width multipliers.
152
+ """
153
+ if not table.rows:
154
+ return
155
+
156
+ # Get header row to map column names to indices
157
+ header_row = table.rows[0]
158
+ col_indices: Dict[str, int] = {}
159
+
160
+ for idx, cell in enumerate(header_row.cells):
161
+ cell_text = cell.text.strip()
162
+ if cell_text in widths:
163
+ col_indices[cell_text] = idx
164
+
165
+ if not col_indices:
166
+ return
167
+
168
+ # Calculate total width multiplier for normalization
169
+ total_mult = sum(widths.get(cell.text.strip(), 1.0) for cell in header_row.cells)
170
+
171
+ # Get current table width or use default
172
+ tbl = table._tbl
173
+ tbl_pr = tbl.find(qn('w:tblPr'))
174
+ table_width = 9360 # Default ~6.5 inches in twips
175
+
176
+ if tbl_pr is not None:
177
+ tbl_w = tbl_pr.find(qn('w:tblW'))
178
+ if tbl_w is not None:
179
+ width_val = tbl_w.get(qn('w:w'))
180
+ if width_val and width_val.isdigit():
181
+ table_width = int(width_val)
182
+
183
+ # Apply widths to each column
184
+ for cell in header_row.cells:
185
+ cell_text = cell.text.strip()
186
+ mult = widths.get(cell_text, 1.0)
187
+ col_width = int(table_width * mult / total_mult)
188
+
189
+ # Set cell width
190
+ tc = cell._tc
191
+ tcPr = tc.get_or_add_tcPr()
192
+ tcW = tcPr.find(qn('w:tcW'))
193
+ if tcW is None:
194
+ tcW = parse_xml(f'<w:tcW {nsdecls("w")} w:w="{col_width}" w:type="dxa"/>')
195
+ tcPr.append(tcW)
196
+ else:
197
+ tcW.set(qn('w:w'), str(col_width))
198
+ tcW.set(qn('w:type'), 'dxa')
199
+
200
+
201
+ def get_table_headers(table: Table) -> List[str]:
202
+ """Get the header row column names from a table.
203
+
204
+ Args:
205
+ table: The docx Table to inspect.
206
+
207
+ Returns:
208
+ List of column header texts, or empty list if no rows.
209
+ """
210
+ if not table.rows:
211
+ return []
212
+ return [cell.text.strip() for cell in table.rows[0].cells]
213
+
214
+
215
+ def find_matching_profile(
216
+ table: Table,
217
+ profiles: Dict[str, Dict[str, float]]
218
+ ) -> Optional[Dict[str, float]]:
219
+ """Find a matching column width profile for a table.
220
+
221
+ Matches profiles by checking if the table's headers match the profile's
222
+ column names exactly (same columns in any order).
223
+
224
+ Args:
225
+ table: The docx Table to match.
226
+ profiles: Dict mapping profile names to column width dicts.
227
+
228
+ Returns:
229
+ The matching profile's column widths dict, or None if no match.
230
+ """
231
+ if not profiles:
232
+ return None
233
+
234
+ headers = get_table_headers(table)
235
+ if not headers:
236
+ return None
237
+
238
+ header_set = set(headers)
239
+
240
+ for profile_name, profile_widths in profiles.items():
241
+ profile_columns = set(profile_widths.keys())
242
+ if header_set == profile_columns:
243
+ return profile_widths
244
+
245
+ return None
246
+
247
+
248
+ def apply_table_profiles(
249
+ docx_path: Path,
250
+ profiles: Dict[str, Dict[str, float]]
251
+ ) -> int:
252
+ """Apply column width profiles to all matching tables in a document.
253
+
254
+ For each table, checks if its headers match any profile and applies
255
+ the corresponding column widths.
256
+
257
+ Args:
258
+ docx_path: Path to the DOCX file.
259
+ profiles: Dict mapping profile names to column width dicts.
260
+
261
+ Returns:
262
+ Number of tables that had profiles applied.
263
+ """
264
+ if not profiles:
265
+ return 0
266
+
267
+ doc = Document(docx_path)
268
+ applied_count = 0
269
+
270
+ for table in doc.tables:
271
+ matching_widths = find_matching_profile(table, profiles)
272
+ if matching_widths:
273
+ apply_column_widths(table, matching_widths)
274
+ applied_count += 1
275
+
276
+ if applied_count > 0:
277
+ doc.save(docx_path)
278
+
279
+ return applied_count
280
+
281
+
282
+ def set_cell_shading(cell, color: str) -> None:
283
+ """Set background shading color for a cell.
284
+
285
+ Args:
286
+ cell: The table cell to shade.
287
+ color: Hex color code without # (e.g., "4472C4" for blue).
288
+ """
289
+ shading_elm = parse_xml(
290
+ f'<w:shd {nsdecls("w")} w:fill="{color}" w:val="clear"/>'
291
+ )
292
+ cell._tc.get_or_add_tcPr().append(shading_elm)
293
+
294
+
295
+ def set_cell_borders(cell, color: str = "000000", size: int = 4) -> None:
296
+ """Set borders for a cell.
297
+
298
+ Args:
299
+ cell: The table cell.
300
+ color: Border color in hex without # (default: black).
301
+ size: Border size in eighths of a point (default: 4 = 0.5pt).
302
+ """
303
+ tc = cell._tc
304
+ tcPr = tc.get_or_add_tcPr()
305
+
306
+ tcBorders = parse_xml(
307
+ f'''<w:tcBorders {nsdecls("w")}>
308
+ <w:top w:val="single" w:sz="{size}" w:color="{color}"/>
309
+ <w:left w:val="single" w:sz="{size}" w:color="{color}"/>
310
+ <w:bottom w:val="single" w:sz="{size}" w:color="{color}"/>
311
+ <w:right w:val="single" w:sz="{size}" w:color="{color}"/>
312
+ </w:tcBorders>'''
313
+ )
314
+ tcPr.append(tcBorders)
315
+
316
+
317
+ def format_table(
318
+ table: Table,
319
+ header_bg_color: str = "4472C4",
320
+ header_text_color: str = "FFFFFF",
321
+ odd_row_color: str = "FFFFFF",
322
+ even_row_color: str = "D6DCE5",
323
+ border_color: str = "8EAADB",
324
+ border_size: int = 4
325
+ ) -> None:
326
+ """Format a single table with borders, header styling, and striped rows.
327
+
328
+ Args:
329
+ table: The docx Table object to format.
330
+ header_bg_color: Background color for header row (hex without #).
331
+ header_text_color: Text color for header row (hex without #).
332
+ odd_row_color: Background color for odd rows (hex without #).
333
+ even_row_color: Background color for even rows (hex without #).
334
+ border_color: Border color (hex without #).
335
+ border_size: Border size in eighths of a point.
336
+ """
337
+ for row_idx, row in enumerate(table.rows):
338
+ for cell in row.cells:
339
+ # Set borders on all cells
340
+ set_cell_borders(cell, color=border_color, size=border_size)
341
+
342
+ if row_idx == 0:
343
+ # Header row: dark background, white text
344
+ set_cell_shading(cell, header_bg_color)
345
+ for paragraph in cell.paragraphs:
346
+ for run in paragraph.runs:
347
+ run.font.color.rgb = RGBColor(
348
+ int(header_text_color[0:2], 16),
349
+ int(header_text_color[2:4], 16),
350
+ int(header_text_color[4:6], 16)
351
+ )
352
+ run.font.bold = True
353
+ else:
354
+ # Data rows: alternating colors
355
+ if row_idx % 2 == 1:
356
+ set_cell_shading(cell, odd_row_color)
357
+ else:
358
+ set_cell_shading(cell, even_row_color)
359
+
360
+
361
+ def format_tables(
362
+ docx_path: Path,
363
+ header_bg_color: str = "4472C4",
364
+ header_text_color: str = "FFFFFF",
365
+ odd_row_color: str = "FFFFFF",
366
+ even_row_color: str = "D6DCE5",
367
+ border_color: str = "8EAADB",
368
+ border_size: int = 4
369
+ ) -> None:
370
+ """Format all tables in a DOCX document.
371
+
372
+ Args:
373
+ docx_path: Path to the DOCX file to format.
374
+ header_bg_color: Background color for header rows (hex without #).
375
+ header_text_color: Text color for header rows (hex without #).
376
+ odd_row_color: Background color for odd data rows (hex without #).
377
+ even_row_color: Background color for even data rows (hex without #).
378
+ border_color: Border color (hex without #).
379
+ border_size: Border size in eighths of a point.
380
+ """
381
+ doc = Document(docx_path)
382
+
383
+ for table in doc.tables:
384
+ format_table(
385
+ table,
386
+ header_bg_color=header_bg_color,
387
+ header_text_color=header_text_color,
388
+ odd_row_color=odd_row_color,
389
+ even_row_color=even_row_color,
390
+ border_color=border_color,
391
+ border_size=border_size
392
+ )
393
+
394
+ doc.save(docx_path)
395
+
396
+
397
+ def fix_table_styles_for_pdf(docx_path: Path) -> dict:
398
+ """Fix table styles that cause PDF rendering issues in LibreOffice.
399
+
400
+ Pandoc generates tables with invalid style references ('Table', 'Compact')
401
+ that don't exist in the document's style definitions. LibreOffice fails to
402
+ render these tables correctly, showing only the last cell content.
403
+
404
+ This function removes invalid style references while preserving the actual
405
+ formatting (borders, shading, etc.) that was applied directly to elements.
406
+
407
+ Args:
408
+ docx_path: Path to the DOCX file to fix.
409
+
410
+ Returns:
411
+ Dictionary with counts of fixes applied.
412
+ """
413
+ doc = Document(docx_path)
414
+ fixes = {'tblStyle': 0, 'pStyle_Compact': 0}
415
+
416
+ for table in doc.tables:
417
+ tbl_elem = table._tbl
418
+ tbl_pr = tbl_elem.find(qn('w:tblPr'))
419
+
420
+ if tbl_pr is not None:
421
+ # Remove invalid 'Table' style reference
422
+ # The actual formatting (borders, shading) is applied directly to cells
423
+ tbl_style = tbl_pr.find(qn('w:tblStyle'))
424
+ if tbl_style is not None:
425
+ style_val = tbl_style.get(qn('w:val'))
426
+ if style_val == 'Table':
427
+ tbl_pr.remove(tbl_style)
428
+ fixes['tblStyle'] += 1
429
+
430
+ # Remove invalid 'Compact' paragraph style from table cells
431
+ # Add proper spacing to maintain compact appearance
432
+ for p in tbl_elem.findall('.//' + qn('w:p')):
433
+ pPr = p.find(qn('w:pPr'))
434
+ if pPr is not None:
435
+ pStyle = pPr.find(qn('w:pStyle'))
436
+ if pStyle is not None and pStyle.get(qn('w:val')) == 'Compact':
437
+ pPr.remove(pStyle)
438
+ fixes['pStyle_Compact'] += 1
439
+
440
+ # Add spacing to maintain compact look
441
+ spacing = pPr.find(qn('w:spacing'))
442
+ if spacing is None:
443
+ spacing = parse_xml(
444
+ '<w:spacing xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" '
445
+ 'w:before="40" w:after="40" w:line="240" w:lineRule="auto"/>'
446
+ )
447
+ pPr.append(spacing)
448
+
449
+ doc.save(docx_path)
450
+ return fixes