@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.
- package/.pi/skills/document-converter/SKILL.md +79 -0
- package/README.md +106 -0
- package/engine/.dockerignore +4 -0
- package/engine/Dockerfile +75 -0
- package/engine/IMAGE_VERSION +1 -0
- package/engine/README.md +65 -0
- package/engine/VENDOR.md +40 -0
- package/engine/build-image.sh +29 -0
- package/engine/document_converter/LICENSE +21 -0
- package/engine/document_converter/__init__.py +365 -0
- package/engine/document_converter/__main__.py +5 -0
- package/engine/document_converter/asciidoc_converter.py +534 -0
- package/engine/document_converter/cli.py +751 -0
- package/engine/document_converter/code_renderer.py +356 -0
- package/engine/document_converter/converter.py +928 -0
- package/engine/document_converter/cover_page.py +448 -0
- package/engine/document_converter/diagram_resizer.py +311 -0
- package/engine/document_converter/diagram_sizing.py +357 -0
- package/engine/document_converter/docx_reader.py +627 -0
- package/engine/document_converter/field_updater.py +277 -0
- package/engine/document_converter/font_manager.py +850 -0
- package/engine/document_converter/frontmatter_parser.py +644 -0
- package/engine/document_converter/graphviz_renderer.py +354 -0
- package/engine/document_converter/image_extractor.py +281 -0
- package/engine/document_converter/image_style.py +237 -0
- package/engine/document_converter/logo_manager.py +1021 -0
- package/engine/document_converter/manifest_manager.py +288 -0
- package/engine/document_converter/mermaid_renderer.py +371 -0
- package/engine/document_converter/meta_mapper.py +398 -0
- package/engine/document_converter/pandoc_styles.py +222 -0
- package/engine/document_converter/pdf_converter.py +735 -0
- package/engine/document_converter/pdf_server.py +283 -0
- package/engine/document_converter/plantuml_renderer.py +460 -0
- package/engine/document_converter/plantuml_server.py +273 -0
- package/engine/document_converter/pyproject.toml +80 -0
- package/engine/document_converter/round_trip.py +312 -0
- package/engine/document_converter/spacing_applier.py +332 -0
- package/engine/document_converter/spacing_config.py +323 -0
- package/engine/document_converter/style_extractor.py +420 -0
- package/engine/document_converter/svg_embedder.py +294 -0
- package/engine/document_converter/system_variables.py +158 -0
- package/engine/document_converter/table_formatter.py +450 -0
- package/engine/document_converter/template_extractor.py +1334 -0
- package/engine/document_converter/template_manager.py +427 -0
- package/engine/document_converter/textbox_extractor.py +551 -0
- package/engine/document_converter/toc_generator.py +559 -0
- package/engine/document_converter/toc_style.py +290 -0
- package/engine/document_converter/tree_renderer.py +328 -0
- package/engine/document_converter/utils.py +134 -0
- package/engine/document_converter/variable_manager.py +394 -0
- package/engine/engine_cli.py +371 -0
- package/engine/frontmatter_filler/doc-meta.sample.yaml +106 -0
- package/engine/frontmatter_filler/fill.py +517 -0
- package/engine/markdown_table_profiler/profile.py +442 -0
- package/engine/nano-banana-styles.yaml +59 -0
- package/engine/tests/test_styled_diagrams.py +109 -0
- package/package.json +32 -0
- package/src/__tests__/engine.test.ts +72 -0
- package/src/__tests__/facade.test.ts +120 -0
- package/src/__tests__/integration.test.ts +101 -0
- package/src/__tests__/ocr.test.ts +34 -0
- package/src/__tests__/provenance.test.ts +89 -0
- package/src/__tests__/routing.test.ts +40 -0
- package/src/engine.ts +187 -0
- package/src/errors.ts +43 -0
- package/src/index.ts +179 -0
- package/src/ocr.ts +43 -0
- package/src/provenance.ts +79 -0
- package/src/routing.ts +49 -0
- package/src/schema.json +69 -0
- package/src/schema.ts +107 -0
- package/src/types.ts +90 -0
|
@@ -0,0 +1,928 @@
|
|
|
1
|
+
"""Main document conversion logic."""
|
|
2
|
+
import logging
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
|
|
9
|
+
from .mermaid_renderer import (
|
|
10
|
+
render_all_diagrams,
|
|
11
|
+
DiagramFormat,
|
|
12
|
+
resolve_diagram_format,
|
|
13
|
+
generate_mermaid_config
|
|
14
|
+
)
|
|
15
|
+
from .svg_embedder import is_svg_embedding_available
|
|
16
|
+
from .plantuml_renderer import (
|
|
17
|
+
has_plantuml_blocks,
|
|
18
|
+
render_all_plantuml_diagrams,
|
|
19
|
+
PlantUMLRenderError
|
|
20
|
+
)
|
|
21
|
+
from .graphviz_renderer import (
|
|
22
|
+
has_graphviz_blocks,
|
|
23
|
+
render_all_graphviz_diagrams,
|
|
24
|
+
replace_graphviz_with_images
|
|
25
|
+
)
|
|
26
|
+
from .code_renderer import (
|
|
27
|
+
CodeStyleConfig,
|
|
28
|
+
extract_code_blocks,
|
|
29
|
+
render_all_code_blocks
|
|
30
|
+
)
|
|
31
|
+
from .tree_renderer import (
|
|
32
|
+
TreeStyleConfig,
|
|
33
|
+
extract_tree_blocks,
|
|
34
|
+
render_all_tree_blocks
|
|
35
|
+
)
|
|
36
|
+
from .diagram_sizing import (
|
|
37
|
+
SizingConfig,
|
|
38
|
+
SizingMode,
|
|
39
|
+
RotationMode,
|
|
40
|
+
calculate_diagram_dimensions,
|
|
41
|
+
parse_sizing_config
|
|
42
|
+
)
|
|
43
|
+
from .diagram_resizer import build_diagram_size_map, apply_diagram_sizes
|
|
44
|
+
from .utils import validate_file, check_dependencies, create_temp_dir, cleanup_temp_files
|
|
45
|
+
from .template_manager import apply_template, load_template
|
|
46
|
+
from .font_manager import get_available_fonts, cleanup_extracted_fonts, embed_template_fonts
|
|
47
|
+
from .table_formatter import (
|
|
48
|
+
format_tables, fix_table_styles_for_pdf, TableStyleConfig,
|
|
49
|
+
parse_table_style_block, DEFAULT_TABLE_STYLE, apply_table_profiles
|
|
50
|
+
)
|
|
51
|
+
from .cover_page import extract_title_and_description, add_cover_page, demote_headings, copy_template_cover_page, normalize_heading_levels
|
|
52
|
+
from .toc_generator import add_toc, add_static_toc
|
|
53
|
+
from .toc_style import TocConfig, TocMode, TocStyleConfig, extract_toc_config
|
|
54
|
+
from .textbox_extractor import replace_text_in_textbox
|
|
55
|
+
from .frontmatter_parser import (
|
|
56
|
+
parse_frontmatter,
|
|
57
|
+
extract_template_config,
|
|
58
|
+
extract_variables,
|
|
59
|
+
extract_conversion_options,
|
|
60
|
+
extract_table_style,
|
|
61
|
+
extract_table_profiles,
|
|
62
|
+
extract_diagram_config,
|
|
63
|
+
extract_code_style,
|
|
64
|
+
extract_tree_style,
|
|
65
|
+
warn_unknown_keys,
|
|
66
|
+
merge_with_defaults,
|
|
67
|
+
)
|
|
68
|
+
from .system_variables import (
|
|
69
|
+
resolve_system_variables,
|
|
70
|
+
get_system_variables,
|
|
71
|
+
detect_toc_placeholder,
|
|
72
|
+
SystemContext,
|
|
73
|
+
)
|
|
74
|
+
from .pandoc_styles import fix_style_references
|
|
75
|
+
from .logo_manager import (
|
|
76
|
+
parse_logos_frontmatter,
|
|
77
|
+
extract_logos_from_markdown,
|
|
78
|
+
merge_logo_configs,
|
|
79
|
+
replace_logo_placeholders_in_docx,
|
|
80
|
+
)
|
|
81
|
+
from .field_updater import update_fields_if_available, FieldUpdateError
|
|
82
|
+
from .spacing_config import SpacingConfig, extract_spacing_config, load_template_spacing
|
|
83
|
+
from .spacing_applier import apply_spacing_to_document
|
|
84
|
+
|
|
85
|
+
logger = logging.getLogger(__name__)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def normalize_markdown(md_content: str) -> str:
|
|
89
|
+
"""Normalize markdown for better pandoc/DOCX conversion.
|
|
90
|
+
|
|
91
|
+
Handles:
|
|
92
|
+
- Bullet point normalization (* to -)
|
|
93
|
+
- Proper spacing around lists
|
|
94
|
+
- Proper spacing around headers
|
|
95
|
+
- Nested list formatting
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
md_content: Original markdown content.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
Normalized markdown content with proper spacing.
|
|
102
|
+
"""
|
|
103
|
+
lines = md_content.split('\n')
|
|
104
|
+
result = []
|
|
105
|
+
|
|
106
|
+
# Regex patterns for list items
|
|
107
|
+
bullet_pattern = r'^[-*]\s+'
|
|
108
|
+
numbered_pattern = r'^\d+\.\s+'
|
|
109
|
+
indented_bullet_pattern = r'^(\s+)[-*]\s+'
|
|
110
|
+
indented_numbered_pattern = r'^(\s+)\d+\.\s+'
|
|
111
|
+
any_list_pattern = r'^[-*]\s+|^\d+\.\s+|^\s+[-*]\s+|^\s+\d+\.\s+'
|
|
112
|
+
|
|
113
|
+
for i, line in enumerate(lines):
|
|
114
|
+
# Normalize bullet points: convert "* " or "* " to "- "
|
|
115
|
+
if re.match(r'^\*\s+', line):
|
|
116
|
+
line = re.sub(r'^\*\s+', '- ', line)
|
|
117
|
+
|
|
118
|
+
# Normalize nested bullets with multiple spaces
|
|
119
|
+
if re.match(r'^(\s+)\*\s+', line):
|
|
120
|
+
line = re.sub(r'^(\s+)\*\s+', r'\1- ', line)
|
|
121
|
+
|
|
122
|
+
# Check if current line is any type of list item
|
|
123
|
+
is_list_item = bool(re.match(any_list_pattern, line))
|
|
124
|
+
|
|
125
|
+
# Check if current line is a top-level list item (bullet or numbered)
|
|
126
|
+
is_top_level_list = bool(re.match(bullet_pattern, line) or re.match(numbered_pattern, line))
|
|
127
|
+
|
|
128
|
+
# Add blank line before top-level list if previous line is not blank and not a list item
|
|
129
|
+
if is_top_level_list and i > 0:
|
|
130
|
+
prev_line = lines[i-1].strip()
|
|
131
|
+
is_prev_list_item = bool(re.match(any_list_pattern, lines[i-1]))
|
|
132
|
+
if prev_line and not is_prev_list_item:
|
|
133
|
+
# Check if we already have a blank line in result
|
|
134
|
+
if result and result[-1].strip():
|
|
135
|
+
result.append('')
|
|
136
|
+
|
|
137
|
+
# Add blank line after list ends (when non-list, non-blank line follows list item)
|
|
138
|
+
if result and not is_list_item and line.strip():
|
|
139
|
+
last_line = result[-1] if result else ''
|
|
140
|
+
if re.match(any_list_pattern, last_line):
|
|
141
|
+
result.append('')
|
|
142
|
+
|
|
143
|
+
# Add blank line before headers if previous line is not blank
|
|
144
|
+
if re.match(r'^#{1,6}\s', line) and i > 0:
|
|
145
|
+
if result and result[-1].strip():
|
|
146
|
+
result.append('')
|
|
147
|
+
|
|
148
|
+
result.append(line)
|
|
149
|
+
|
|
150
|
+
return '\n'.join(result)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def copy_static_images(markdown_content: str, source_dir: Path, temp_dir: Path) -> None:
|
|
154
|
+
"""Copy static images referenced in markdown from source directory to temp directory.
|
|
155
|
+
|
|
156
|
+
This handles relative image paths like `` by copying
|
|
157
|
+
the referenced images to the temp directory so pandoc can find them.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
markdown_content: Markdown content to scan for image references.
|
|
161
|
+
source_dir: Source directory where the markdown file is located.
|
|
162
|
+
temp_dir: Temporary directory where images should be copied.
|
|
163
|
+
"""
|
|
164
|
+
# Find all image references in markdown
|
|
165
|
+
for img_match in re.finditer(r'!\[.*?\]\(([^)]+)\)', markdown_content):
|
|
166
|
+
img_path = img_match.group(1)
|
|
167
|
+
|
|
168
|
+
# Skip URLs
|
|
169
|
+
if img_path.startswith(('http://', 'https://', 'data:')):
|
|
170
|
+
continue
|
|
171
|
+
|
|
172
|
+
# Skip already processed mermaid diagrams (diagram_X.png or just filename.png in temp)
|
|
173
|
+
if img_path.startswith('diagram_') or not '/' in img_path:
|
|
174
|
+
continue
|
|
175
|
+
|
|
176
|
+
# Resolve the image path relative to source directory
|
|
177
|
+
src_img = source_dir / img_path
|
|
178
|
+
if src_img.exists():
|
|
179
|
+
# Create subdirectory in temp if needed
|
|
180
|
+
dest_img = temp_dir / img_path
|
|
181
|
+
dest_img.parent.mkdir(parents=True, exist_ok=True)
|
|
182
|
+
shutil.copy2(src_img, dest_img)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def save_debug_markdown(markdown_content: str, output_path: Path) -> Path:
|
|
186
|
+
"""Save processed markdown for debugging purposes.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
markdown_content: Processed markdown content.
|
|
190
|
+
output_path: Path to the output DOCX file.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
Path to the saved debug file.
|
|
194
|
+
"""
|
|
195
|
+
debug_path = output_path.parent / f"{output_path.stem}_debug.md"
|
|
196
|
+
debug_path.write_text(markdown_content, encoding='utf-8')
|
|
197
|
+
return debug_path
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def replace_mermaid_with_images(markdown_content: str, diagram_map: Dict[str, Any], relative_to: Optional[Path] = None) -> str:
|
|
201
|
+
"""Replace Mermaid code blocks with image references.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
markdown_content: Original markdown content.
|
|
205
|
+
diagram_map: Mapping of Mermaid code to DiagramInfo objects (or legacy Path objects).
|
|
206
|
+
relative_to: Optional path to make image references relative to. If None, uses absolute paths.
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
Modified markdown with image references instead of Mermaid blocks.
|
|
210
|
+
If diagram has a title in metadata, adds it as a figure caption below the image.
|
|
211
|
+
"""
|
|
212
|
+
import re
|
|
213
|
+
from .mermaid_renderer import DiagramInfo
|
|
214
|
+
|
|
215
|
+
# Build list of image references in order
|
|
216
|
+
image_refs = []
|
|
217
|
+
for mermaid_code, diagram_info in diagram_map.items():
|
|
218
|
+
# Handle both DiagramInfo objects and legacy Path objects
|
|
219
|
+
if isinstance(diagram_info, DiagramInfo):
|
|
220
|
+
image_path = diagram_info.path
|
|
221
|
+
title = diagram_info.title
|
|
222
|
+
else:
|
|
223
|
+
# Legacy Path object
|
|
224
|
+
image_path = diagram_info
|
|
225
|
+
title = None
|
|
226
|
+
|
|
227
|
+
# Use title as alt text if available, otherwise use generic "Diagram"
|
|
228
|
+
alt_text = title if title else "Diagram"
|
|
229
|
+
|
|
230
|
+
if relative_to:
|
|
231
|
+
try:
|
|
232
|
+
rel_path = image_path.relative_to(relative_to)
|
|
233
|
+
image_ref = f""
|
|
234
|
+
except ValueError:
|
|
235
|
+
image_ref = f""
|
|
236
|
+
else:
|
|
237
|
+
image_ref = f""
|
|
238
|
+
|
|
239
|
+
# Note: We no longer add a separate caption since the title is now in the alt text
|
|
240
|
+
# This prevents duplicate figure labels in the output
|
|
241
|
+
|
|
242
|
+
image_refs.append(image_ref)
|
|
243
|
+
|
|
244
|
+
# Replace all mermaid blocks in order
|
|
245
|
+
idx = 0
|
|
246
|
+
def replacer(match):
|
|
247
|
+
nonlocal idx
|
|
248
|
+
if idx < len(image_refs):
|
|
249
|
+
result = image_refs[idx]
|
|
250
|
+
idx += 1
|
|
251
|
+
return result
|
|
252
|
+
return match.group(0)
|
|
253
|
+
|
|
254
|
+
# Pattern to match any mermaid block
|
|
255
|
+
pattern = r'```mermaid\s*\n.*?```'
|
|
256
|
+
modified = re.sub(pattern, replacer, markdown_content, flags=re.DOTALL)
|
|
257
|
+
|
|
258
|
+
return modified
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def convert_md_to_docx(
|
|
262
|
+
input_path: str | Path,
|
|
263
|
+
output_path: str | Path,
|
|
264
|
+
config: Optional[Dict] = None,
|
|
265
|
+
template_path: Optional[str | Path] = None,
|
|
266
|
+
template_name: Optional[str] = None,
|
|
267
|
+
templates_dir: Optional[str | Path] = None,
|
|
268
|
+
document_name: Optional[str] = None,
|
|
269
|
+
document_title: Optional[str] = None,
|
|
270
|
+
font_name: str = "Source Sans Pro",
|
|
271
|
+
fonts_dir: Optional[str | Path] = None,
|
|
272
|
+
diagram_width: int = 1200,
|
|
273
|
+
diagram_scale: int = 2,
|
|
274
|
+
diagram_format: str | DiagramFormat = "png",
|
|
275
|
+
embed_svg_in_word: bool = False,
|
|
276
|
+
enable_cover_page: bool = True,
|
|
277
|
+
enable_toc: bool = True,
|
|
278
|
+
toc_heading: str = "Tartalomjegyzék",
|
|
279
|
+
debug: bool = False,
|
|
280
|
+
variables: Optional[Dict[str, str]] = None,
|
|
281
|
+
embed_fonts: bool = True,
|
|
282
|
+
update_fields: Optional[bool] = None,
|
|
283
|
+
enable_code_render: bool = True,
|
|
284
|
+
enable_tree_render: bool = True,
|
|
285
|
+
code_theme: Optional[str] = None,
|
|
286
|
+
code_line_numbers: bool = False
|
|
287
|
+
) -> None:
|
|
288
|
+
"""Convert markdown file with Mermaid diagrams to DOCX.
|
|
289
|
+
|
|
290
|
+
Args:
|
|
291
|
+
input_path: Path to input markdown file.
|
|
292
|
+
output_path: Path to output DOCX file.
|
|
293
|
+
config: Optional configuration dictionary (reserved for future use).
|
|
294
|
+
template_path: Path to DOCX template file. If None, uses default template.
|
|
295
|
+
template_name: Name of a template to use from templates directory.
|
|
296
|
+
templates_dir: Directory containing templates (default: ./templates).
|
|
297
|
+
document_name: Text to replace <document name> placeholder in template.
|
|
298
|
+
document_title: Text to replace <document title> placeholder in template.
|
|
299
|
+
font_name: Default font name for the document (default: "Source Sans Pro").
|
|
300
|
+
fonts_dir: Path to directory containing font files. If None, uses default fonts directory.
|
|
301
|
+
diagram_width: Maximum width for diagrams in pixels (default: 1200 for page fitting).
|
|
302
|
+
diagram_scale: Scale factor for diagram resolution (default: 2 for high quality).
|
|
303
|
+
diagram_format: Output format for diagrams - 'png', 'svg', or 'auto' (default: 'png').
|
|
304
|
+
'auto' uses SVG for HTML/Markdown, PNG for DOCX.
|
|
305
|
+
embed_svg_in_word: Whether to embed SVG directly in Word (experimental, default: False).
|
|
306
|
+
Only applies when diagram_format is 'svg' and output is DOCX.
|
|
307
|
+
Requires Word 2016+ for proper rendering.
|
|
308
|
+
enable_cover_page: Whether to create a cover page from H1 title (default: True).
|
|
309
|
+
enable_toc: Whether to add a Table of Contents (default: True).
|
|
310
|
+
toc_heading: Heading text for the TOC (default: "Tartalomjegyzék").
|
|
311
|
+
debug: Whether to save processed markdown for debugging (default: False).
|
|
312
|
+
variables: Dictionary of variable names to values for template substitution.
|
|
313
|
+
embed_fonts: Whether to embed fonts into the DOCX file (default: True).
|
|
314
|
+
Searches template fonts directory, default fonts, and system fonts.
|
|
315
|
+
update_fields: Whether to update field codes (TOC, page numbers, etc.) after
|
|
316
|
+
generation. If None (default), automatically enabled when TOC is enabled.
|
|
317
|
+
Requires LibreOffice to be installed. If LibreOffice is not available,
|
|
318
|
+
the document is created with unpopulated fields that can be updated
|
|
319
|
+
manually in Word (Ctrl+A, F9).
|
|
320
|
+
enable_code_render: Whether to render code blocks as syntax-highlighted images
|
|
321
|
+
(default: True). Uses Pygments for highlighting.
|
|
322
|
+
enable_tree_render: Whether to render ASCII trees as images (default: True).
|
|
323
|
+
Auto-detects trees with 5+ lines of box-drawing characters.
|
|
324
|
+
code_theme: Pygments theme for code highlighting (default: "default").
|
|
325
|
+
CLI override for frontmatter code_style.theme.
|
|
326
|
+
code_line_numbers: Whether to show line numbers in code blocks (default: False).
|
|
327
|
+
CLI override for frontmatter code_style.line_numbers.
|
|
328
|
+
|
|
329
|
+
Raises:
|
|
330
|
+
FileNotFoundError: If input file does not exist.
|
|
331
|
+
RuntimeError: If dependencies are missing or conversion fails.
|
|
332
|
+
"""
|
|
333
|
+
input_path = Path(input_path)
|
|
334
|
+
output_path = Path(output_path)
|
|
335
|
+
|
|
336
|
+
# Validate input file
|
|
337
|
+
if not validate_file(input_path):
|
|
338
|
+
raise FileNotFoundError(f"Input file does not exist or is not readable: {input_path}")
|
|
339
|
+
|
|
340
|
+
# Check dependencies
|
|
341
|
+
if not check_dependencies():
|
|
342
|
+
raise RuntimeError(
|
|
343
|
+
"Mermaid CLI (mmdc) is not installed. "
|
|
344
|
+
"Please install it with: npm install -g @mermaid-js/mermaid-cli"
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
# Set up paths
|
|
348
|
+
from .template_manager import load_template, resolve_templates_dir
|
|
349
|
+
|
|
350
|
+
# Default templates directory (relative to cwd or absolute)
|
|
351
|
+
resolved_templates_dir = resolve_templates_dir(templates_dir)
|
|
352
|
+
|
|
353
|
+
# Handle named template from templates directory
|
|
354
|
+
template_info = None
|
|
355
|
+
if template_name:
|
|
356
|
+
try:
|
|
357
|
+
template_info = load_template(template_name, templates_dir)
|
|
358
|
+
template_path = template_info['template_docx']
|
|
359
|
+
except FileNotFoundError:
|
|
360
|
+
print(f"Warning: Template '{template_name}' not found, using default template")
|
|
361
|
+
template_path = None
|
|
362
|
+
|
|
363
|
+
# Use default template if not provided
|
|
364
|
+
if template_path is None:
|
|
365
|
+
# Try to load 'default' template from templates directory
|
|
366
|
+
default_template = resolved_templates_dir / "default" / "template.docx"
|
|
367
|
+
if default_template.exists():
|
|
368
|
+
template_path = default_template
|
|
369
|
+
else:
|
|
370
|
+
raise FileNotFoundError(
|
|
371
|
+
f"Default template not found at {default_template}. "
|
|
372
|
+
"Please ensure templates/default/template.docx exists."
|
|
373
|
+
)
|
|
374
|
+
else:
|
|
375
|
+
template_path = Path(template_path)
|
|
376
|
+
|
|
377
|
+
# Use default fonts directory if not provided
|
|
378
|
+
if fonts_dir is None:
|
|
379
|
+
# Try fonts from default template directory
|
|
380
|
+
default_fonts = resolved_templates_dir / "default" / "fonts"
|
|
381
|
+
if default_fonts.exists():
|
|
382
|
+
fonts_dir = default_fonts
|
|
383
|
+
else:
|
|
384
|
+
fonts_dir = None # No fonts directory available
|
|
385
|
+
else:
|
|
386
|
+
fonts_dir = Path(fonts_dir)
|
|
387
|
+
|
|
388
|
+
# Source directory for resolving relative image paths
|
|
389
|
+
source_dir = input_path.parent
|
|
390
|
+
|
|
391
|
+
# Read markdown content
|
|
392
|
+
markdown_content = input_path.read_text(encoding='utf-8')
|
|
393
|
+
|
|
394
|
+
# Parse frontmatter and extract remaining content
|
|
395
|
+
frontmatter, content_without_frontmatter = parse_frontmatter(markdown_content, format='markdown')
|
|
396
|
+
|
|
397
|
+
# Check for deprecated properties file
|
|
398
|
+
properties_file = input_path.with_suffix('.properties')
|
|
399
|
+
if properties_file.exists():
|
|
400
|
+
logger.warning(
|
|
401
|
+
f"Deprecated: Properties file '{properties_file.name}' found. "
|
|
402
|
+
"Please migrate to YAML frontmatter. Properties files will be removed in a future version."
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
# Extract configuration from frontmatter
|
|
406
|
+
fm_template_config = extract_template_config(frontmatter)
|
|
407
|
+
fm_conversion_options = extract_conversion_options(frontmatter)
|
|
408
|
+
fm_table_style = extract_table_style(frontmatter)
|
|
409
|
+
fm_table_profiles = extract_table_profiles(frontmatter)
|
|
410
|
+
fm_diagram_config = extract_diagram_config(frontmatter)
|
|
411
|
+
fm_code_style = extract_code_style(frontmatter)
|
|
412
|
+
fm_tree_style = extract_tree_style(frontmatter)
|
|
413
|
+
|
|
414
|
+
# Merge frontmatter settings with function parameters (CLI takes priority)
|
|
415
|
+
# Template settings: CLI > frontmatter
|
|
416
|
+
if template_name is None and fm_template_config.get('template'):
|
|
417
|
+
template_name = fm_template_config['template']
|
|
418
|
+
if templates_dir is None and fm_template_config.get('templates_dir'):
|
|
419
|
+
templates_dir = fm_template_config['templates_dir']
|
|
420
|
+
|
|
421
|
+
# Reload template_info if template_name was set from frontmatter
|
|
422
|
+
# (The initial check at line 330 ran before frontmatter was parsed)
|
|
423
|
+
if template_name and template_info is None:
|
|
424
|
+
try:
|
|
425
|
+
template_info = load_template(template_name, resolved_templates_dir)
|
|
426
|
+
template_path = Path(template_info['template_docx'])
|
|
427
|
+
except FileNotFoundError:
|
|
428
|
+
logger.warning(f"Template '{template_name}' not found in frontmatter, using default template")
|
|
429
|
+
# template_path already set to default above
|
|
430
|
+
|
|
431
|
+
# Conversion options: CLI > frontmatter > defaults
|
|
432
|
+
# Only override if CLI value is the default
|
|
433
|
+
language = frontmatter.get('language', 'en')
|
|
434
|
+
if enable_cover_page and 'enable_cover_page' in fm_conversion_options:
|
|
435
|
+
enable_cover_page = fm_conversion_options['enable_cover_page']
|
|
436
|
+
if enable_toc and 'enable_toc' in fm_conversion_options:
|
|
437
|
+
enable_toc = fm_conversion_options['enable_toc']
|
|
438
|
+
if toc_heading == "Tartalomjegyzék" and 'toc_heading' in fm_conversion_options:
|
|
439
|
+
toc_heading = fm_conversion_options['toc_heading']
|
|
440
|
+
|
|
441
|
+
# Extract TOC configuration from frontmatter
|
|
442
|
+
# Supports: toc.mode (static/dynamic), toc.max_level, toc.heading, toc.styles
|
|
443
|
+
toc_config = extract_toc_config(frontmatter)
|
|
444
|
+
|
|
445
|
+
# Override TOC config with frontmatter values
|
|
446
|
+
if not toc_config.enabled:
|
|
447
|
+
enable_toc = False
|
|
448
|
+
if toc_config.heading != "Tartalomjegyzék":
|
|
449
|
+
toc_heading = toc_config.heading
|
|
450
|
+
if diagram_format == "png" and 'diagram_format' in fm_conversion_options:
|
|
451
|
+
diagram_format = fm_conversion_options['diagram_format']
|
|
452
|
+
if diagram_width == 1200 and 'diagram_width' in fm_conversion_options:
|
|
453
|
+
diagram_width = fm_conversion_options['diagram_width']
|
|
454
|
+
if diagram_scale == 2 and 'diagram_scale' in fm_conversion_options:
|
|
455
|
+
diagram_scale = fm_conversion_options['diagram_scale']
|
|
456
|
+
if not embed_svg_in_word and 'embed_svg_in_word' in fm_conversion_options:
|
|
457
|
+
embed_svg_in_word = fm_conversion_options['embed_svg_in_word']
|
|
458
|
+
if font_name == "Source Sans Pro" and 'font_name' in fm_conversion_options:
|
|
459
|
+
font_name = fm_conversion_options['font_name']
|
|
460
|
+
if embed_fonts and 'embed_fonts' in fm_conversion_options:
|
|
461
|
+
embed_fonts = fm_conversion_options['embed_fonts']
|
|
462
|
+
if not debug and 'debug' in fm_conversion_options:
|
|
463
|
+
debug = fm_conversion_options['debug']
|
|
464
|
+
|
|
465
|
+
# Document metadata from frontmatter
|
|
466
|
+
if document_name is None:
|
|
467
|
+
document_name = frontmatter.get('document_name')
|
|
468
|
+
if document_title is None:
|
|
469
|
+
document_title = frontmatter.get('document_title')
|
|
470
|
+
|
|
471
|
+
# Build system context for variable resolution
|
|
472
|
+
# Use output filename (.docx) instead of input filename (.md) for $fileName variable
|
|
473
|
+
system_context = SystemContext(
|
|
474
|
+
file_name=output_path.name,
|
|
475
|
+
language=language,
|
|
476
|
+
has_toc_placeholder=detect_toc_placeholder(content_without_frontmatter) is not None
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
# Extract template variables from frontmatter
|
|
480
|
+
# Pass None to extract all variables from the 'variables' section
|
|
481
|
+
fm_variables = extract_variables(frontmatter)
|
|
482
|
+
|
|
483
|
+
# Merge variables: CLI > frontmatter
|
|
484
|
+
if variables is None:
|
|
485
|
+
variables = {}
|
|
486
|
+
merged_variables = {**fm_variables, **variables}
|
|
487
|
+
|
|
488
|
+
# Add system variables to merged_variables for template substitution
|
|
489
|
+
# System variables use $ prefix (e.g., $date, $fileName)
|
|
490
|
+
system_vars = get_system_variables(system_context)
|
|
491
|
+
merged_variables.update(system_vars)
|
|
492
|
+
|
|
493
|
+
# Resolve system variables in variable values (for nested references)
|
|
494
|
+
for key, value in merged_variables.items():
|
|
495
|
+
if isinstance(value, str):
|
|
496
|
+
merged_variables[key] = resolve_system_variables(value, system_context)
|
|
497
|
+
|
|
498
|
+
# Resolve system variables in content (but not {{$toc}} - handled separately)
|
|
499
|
+
markdown_content = resolve_system_variables(content_without_frontmatter, system_context)
|
|
500
|
+
|
|
501
|
+
# Normalize markdown formatting for better DOCX conversion
|
|
502
|
+
markdown_content = normalize_markdown(markdown_content)
|
|
503
|
+
|
|
504
|
+
# Check if template has its own cover page
|
|
505
|
+
template_has_cover_page = template_info and template_info.get('has_cover_page', False)
|
|
506
|
+
|
|
507
|
+
# Extract cover page info before modifying markdown
|
|
508
|
+
cover_title, cover_description, should_create_cover = '', '', False
|
|
509
|
+
if enable_cover_page and not template_has_cover_page:
|
|
510
|
+
# Only auto-generate cover page if template doesn't have one
|
|
511
|
+
cover_title, cover_description, should_create_cover = extract_title_and_description(markdown_content)
|
|
512
|
+
if should_create_cover:
|
|
513
|
+
# Demote headings (H2->H1, H3->H2, etc.) since H1 goes to cover page
|
|
514
|
+
markdown_content = demote_headings(markdown_content)
|
|
515
|
+
|
|
516
|
+
# Normalize heading levels if no H1 exists and demote_headings was not applied
|
|
517
|
+
# This promotes all headings so the minimum level becomes H1
|
|
518
|
+
# (e.g., if markdown only has H2+, H2->H1, H3->H2, etc.)
|
|
519
|
+
if not should_create_cover:
|
|
520
|
+
markdown_content = normalize_heading_levels(markdown_content)
|
|
521
|
+
|
|
522
|
+
# Create temporary directory
|
|
523
|
+
temp_dir = create_temp_dir()
|
|
524
|
+
|
|
525
|
+
try:
|
|
526
|
+
# Resolve diagram format
|
|
527
|
+
if isinstance(diagram_format, str):
|
|
528
|
+
diagram_format_enum = DiagramFormat(diagram_format)
|
|
529
|
+
else:
|
|
530
|
+
diagram_format_enum = diagram_format
|
|
531
|
+
|
|
532
|
+
# Determine actual format based on output type
|
|
533
|
+
output_suffix = output_path.suffix
|
|
534
|
+
actual_format = resolve_diagram_format(output_suffix, diagram_format_enum)
|
|
535
|
+
|
|
536
|
+
# For DOCX output with SVG, check if we need to fall back to PNG
|
|
537
|
+
if output_suffix.lower() == '.docx' and actual_format == 'svg':
|
|
538
|
+
if not embed_svg_in_word:
|
|
539
|
+
# User wants SVG but not embedding in Word - fall back to PNG for compatibility
|
|
540
|
+
actual_format = 'png'
|
|
541
|
+
elif not is_svg_embedding_available():
|
|
542
|
+
# User requested SVG embedding but python-docx-ng is not installed
|
|
543
|
+
print("Warning: SVG embedding in Word requires python-docx-ng. "
|
|
544
|
+
"Install with: pip install python-docx-ng")
|
|
545
|
+
print("Falling back to PNG format for diagrams.")
|
|
546
|
+
actual_format = 'png'
|
|
547
|
+
|
|
548
|
+
# Parse diagram sizing configuration
|
|
549
|
+
sizing_config = parse_sizing_config(frontmatter)
|
|
550
|
+
use_consistent_sizing = sizing_config.mode == SizingMode.CONSISTENT
|
|
551
|
+
|
|
552
|
+
# Generate Mermaid config for consistent styling if enabled
|
|
553
|
+
mermaid_config = None
|
|
554
|
+
if use_consistent_sizing and fm_diagram_config:
|
|
555
|
+
mermaid_opts = fm_diagram_config.get('mermaid', {})
|
|
556
|
+
mermaid_font_size = mermaid_opts.get('font_size', 14)
|
|
557
|
+
mermaid_config = generate_mermaid_config(font_size=mermaid_font_size)
|
|
558
|
+
|
|
559
|
+
# Render Mermaid diagrams with size constraints for page fitting
|
|
560
|
+
diagram_map = render_all_diagrams(
|
|
561
|
+
markdown_content,
|
|
562
|
+
temp_dir,
|
|
563
|
+
width=diagram_width,
|
|
564
|
+
scale=diagram_scale,
|
|
565
|
+
format=actual_format,
|
|
566
|
+
extract_dimensions=use_consistent_sizing,
|
|
567
|
+
mermaid_config=mermaid_config
|
|
568
|
+
)
|
|
569
|
+
|
|
570
|
+
# Log sizing warnings if any diagrams have them
|
|
571
|
+
if use_consistent_sizing:
|
|
572
|
+
for mermaid_code, diagram_info in diagram_map.items():
|
|
573
|
+
if diagram_info.logical_width and diagram_info.logical_height:
|
|
574
|
+
dims = calculate_diagram_dimensions(
|
|
575
|
+
diagram_info.logical_width,
|
|
576
|
+
diagram_info.logical_height,
|
|
577
|
+
diagram_info.units_per_inch,
|
|
578
|
+
sizing_config
|
|
579
|
+
)
|
|
580
|
+
if dims.warning:
|
|
581
|
+
logger.warning(f"Mermaid diagram: {dims.warning}")
|
|
582
|
+
|
|
583
|
+
# Replace Mermaid blocks with image references (relative to temp_dir)
|
|
584
|
+
modified_markdown = replace_mermaid_with_images(markdown_content, diagram_map, relative_to=temp_dir)
|
|
585
|
+
|
|
586
|
+
# Track diagram info for sizing (collected from all diagram types)
|
|
587
|
+
plantuml_diagrams = []
|
|
588
|
+
graphviz_map = {}
|
|
589
|
+
|
|
590
|
+
# Render PlantUML diagrams if present
|
|
591
|
+
if has_plantuml_blocks(modified_markdown, format='markdown'):
|
|
592
|
+
try:
|
|
593
|
+
plantuml_result = render_all_plantuml_diagrams(
|
|
594
|
+
modified_markdown,
|
|
595
|
+
output_dir=temp_dir,
|
|
596
|
+
format='markdown',
|
|
597
|
+
image_format=actual_format,
|
|
598
|
+
fail_on_error=False, # Continue even if PlantUML server unavailable
|
|
599
|
+
extract_dimensions=use_consistent_sizing
|
|
600
|
+
)
|
|
601
|
+
modified_markdown = plantuml_result['content']
|
|
602
|
+
plantuml_diagrams = plantuml_result.get('diagrams', [])
|
|
603
|
+
|
|
604
|
+
# Log sizing warnings for PlantUML diagrams
|
|
605
|
+
if use_consistent_sizing:
|
|
606
|
+
for diagram_info in plantuml_diagrams:
|
|
607
|
+
if diagram_info.logical_width and diagram_info.logical_height:
|
|
608
|
+
dims = calculate_diagram_dimensions(
|
|
609
|
+
diagram_info.logical_width,
|
|
610
|
+
diagram_info.logical_height,
|
|
611
|
+
diagram_info.units_per_inch,
|
|
612
|
+
sizing_config
|
|
613
|
+
)
|
|
614
|
+
if dims.warning:
|
|
615
|
+
logger.warning(f"PlantUML diagram: {dims.warning}")
|
|
616
|
+
|
|
617
|
+
if plantuml_result.get('warnings'):
|
|
618
|
+
for warning in plantuml_result['warnings']:
|
|
619
|
+
print(f"PlantUML warning: {warning}")
|
|
620
|
+
except PlantUMLRenderError as e:
|
|
621
|
+
print(f"PlantUML rendering skipped: {e}")
|
|
622
|
+
|
|
623
|
+
# Render Graphviz diagrams if present
|
|
624
|
+
if has_graphviz_blocks(modified_markdown, format='markdown'):
|
|
625
|
+
graphviz_map = render_all_graphviz_diagrams(
|
|
626
|
+
modified_markdown,
|
|
627
|
+
temp_dir,
|
|
628
|
+
format=actual_format,
|
|
629
|
+
extract_dimensions=use_consistent_sizing
|
|
630
|
+
)
|
|
631
|
+
|
|
632
|
+
# Log sizing warnings for Graphviz diagrams
|
|
633
|
+
if use_consistent_sizing:
|
|
634
|
+
for dot_code, diagram_info in graphviz_map.items():
|
|
635
|
+
if diagram_info.logical_width and diagram_info.logical_height:
|
|
636
|
+
dims = calculate_diagram_dimensions(
|
|
637
|
+
diagram_info.logical_width,
|
|
638
|
+
diagram_info.logical_height,
|
|
639
|
+
diagram_info.units_per_inch,
|
|
640
|
+
sizing_config
|
|
641
|
+
)
|
|
642
|
+
if dims.warning:
|
|
643
|
+
logger.warning(f"Graphviz diagram: {dims.warning}")
|
|
644
|
+
|
|
645
|
+
# Replace Graphviz blocks with image references
|
|
646
|
+
modified_markdown = replace_graphviz_with_images(
|
|
647
|
+
modified_markdown, graphviz_map, relative_to=temp_dir
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
# Render code blocks as syntax-highlighted images
|
|
651
|
+
# Build config from frontmatter, then apply CLI overrides
|
|
652
|
+
code_style_config = CodeStyleConfig.from_dict(fm_code_style) if fm_code_style else CodeStyleConfig()
|
|
653
|
+
# CLI overrides
|
|
654
|
+
if not enable_code_render:
|
|
655
|
+
code_style_config.enabled = False
|
|
656
|
+
if code_theme is not None:
|
|
657
|
+
code_style_config.theme = code_theme
|
|
658
|
+
if code_line_numbers:
|
|
659
|
+
code_style_config.line_numbers = True
|
|
660
|
+
|
|
661
|
+
if code_style_config.enabled:
|
|
662
|
+
code_blocks = extract_code_blocks(modified_markdown)
|
|
663
|
+
if code_blocks:
|
|
664
|
+
code_image_map = render_all_code_blocks(
|
|
665
|
+
modified_markdown,
|
|
666
|
+
temp_dir,
|
|
667
|
+
config=code_style_config
|
|
668
|
+
)
|
|
669
|
+
# Replace code blocks with image references
|
|
670
|
+
for original_text, image_path in code_image_map.items():
|
|
671
|
+
try:
|
|
672
|
+
rel_path = image_path.relative_to(temp_dir)
|
|
673
|
+
image_ref = f""
|
|
674
|
+
except ValueError:
|
|
675
|
+
image_ref = f""
|
|
676
|
+
modified_markdown = modified_markdown.replace(original_text, image_ref)
|
|
677
|
+
if code_image_map:
|
|
678
|
+
logger.info(f"Rendered {len(code_image_map)} code block(s) as images")
|
|
679
|
+
|
|
680
|
+
# Render ASCII tree blocks as images
|
|
681
|
+
# Build config from frontmatter, then apply CLI overrides
|
|
682
|
+
tree_style_config = TreeStyleConfig.from_dict(fm_tree_style) if fm_tree_style else TreeStyleConfig()
|
|
683
|
+
# CLI override
|
|
684
|
+
if not enable_tree_render:
|
|
685
|
+
tree_style_config.enabled = False
|
|
686
|
+
|
|
687
|
+
if tree_style_config.enabled:
|
|
688
|
+
tree_blocks = extract_tree_blocks(modified_markdown, tree_style_config)
|
|
689
|
+
if tree_blocks:
|
|
690
|
+
tree_image_map = render_all_tree_blocks(
|
|
691
|
+
modified_markdown,
|
|
692
|
+
temp_dir,
|
|
693
|
+
config=tree_style_config
|
|
694
|
+
)
|
|
695
|
+
# Replace tree blocks with image references
|
|
696
|
+
for original_text, image_path in tree_image_map.items():
|
|
697
|
+
try:
|
|
698
|
+
rel_path = image_path.relative_to(temp_dir)
|
|
699
|
+
image_ref = f""
|
|
700
|
+
except ValueError:
|
|
701
|
+
image_ref = f""
|
|
702
|
+
modified_markdown = modified_markdown.replace(original_text, image_ref)
|
|
703
|
+
if tree_image_map:
|
|
704
|
+
logger.info(f"Rendered {len(tree_image_map)} tree block(s) as images")
|
|
705
|
+
|
|
706
|
+
# Copy static images from source directory to temp directory
|
|
707
|
+
copy_static_images(modified_markdown, source_dir, temp_dir)
|
|
708
|
+
|
|
709
|
+
# Save debug output if requested
|
|
710
|
+
if debug:
|
|
711
|
+
save_debug_markdown(modified_markdown, output_path)
|
|
712
|
+
|
|
713
|
+
# Prepare font-related arguments
|
|
714
|
+
font_args = []
|
|
715
|
+
available_fonts = []
|
|
716
|
+
|
|
717
|
+
if fonts_dir and fonts_dir.exists():
|
|
718
|
+
available_fonts = get_available_fonts(fonts_dir)
|
|
719
|
+
if available_fonts:
|
|
720
|
+
# Add font directory to resource path
|
|
721
|
+
font_args.append(f'--resource-path={temp_dir}:{fonts_dir}')
|
|
722
|
+
|
|
723
|
+
# Convert to DOCX using pypandoc for better formatting
|
|
724
|
+
try:
|
|
725
|
+
import pypandoc
|
|
726
|
+
# Write modified markdown to temp file for pypandoc
|
|
727
|
+
temp_md = temp_dir / "modified.md"
|
|
728
|
+
temp_md.write_text(modified_markdown, encoding='utf-8')
|
|
729
|
+
|
|
730
|
+
# Build pypandoc arguments
|
|
731
|
+
pandoc_args = ['--standalone']
|
|
732
|
+
|
|
733
|
+
# Add resource path
|
|
734
|
+
if font_args:
|
|
735
|
+
pandoc_args.extend(font_args)
|
|
736
|
+
else:
|
|
737
|
+
pandoc_args.append(f'--resource-path={temp_dir}')
|
|
738
|
+
|
|
739
|
+
# Set default font if specified
|
|
740
|
+
if font_name:
|
|
741
|
+
pandoc_args.append(f'--variable=mainfont:{font_name}')
|
|
742
|
+
|
|
743
|
+
# Use template as reference document if available
|
|
744
|
+
if template_path.exists():
|
|
745
|
+
pandoc_args.append(f'--reference-doc={template_path}')
|
|
746
|
+
|
|
747
|
+
pypandoc.convert_file(
|
|
748
|
+
str(temp_md),
|
|
749
|
+
'docx',
|
|
750
|
+
outputfile=str(output_path),
|
|
751
|
+
extra_args=pandoc_args
|
|
752
|
+
)
|
|
753
|
+
except (ImportError, OSError) as e:
|
|
754
|
+
# Fallback to md-to-docx if pypandoc is not available
|
|
755
|
+
from md_to_docx import md_to_docx
|
|
756
|
+
md_to_docx(modified_markdown, str(output_path))
|
|
757
|
+
|
|
758
|
+
# Validate output was created
|
|
759
|
+
if not output_path.exists():
|
|
760
|
+
raise RuntimeError(f"Failed to create output file: {output_path}")
|
|
761
|
+
|
|
762
|
+
# Fix missing Pandoc style definitions that cause Word corruption errors
|
|
763
|
+
fix_style_references(output_path)
|
|
764
|
+
|
|
765
|
+
# Apply consistent diagram sizing if enabled
|
|
766
|
+
if use_consistent_sizing:
|
|
767
|
+
# Build size map from all diagram types
|
|
768
|
+
diagram_size_map = build_diagram_size_map(
|
|
769
|
+
mermaid_diagrams=diagram_map,
|
|
770
|
+
plantuml_diagrams=plantuml_diagrams,
|
|
771
|
+
graphviz_diagrams=graphviz_map,
|
|
772
|
+
sizing_config=sizing_config
|
|
773
|
+
)
|
|
774
|
+
if diagram_size_map:
|
|
775
|
+
resized = apply_diagram_sizes(output_path, diagram_size_map)
|
|
776
|
+
if resized:
|
|
777
|
+
logger.info(f"Applied consistent sizing to {resized} diagram(s)")
|
|
778
|
+
|
|
779
|
+
# Format tables with borders, striped rows, and styled headers
|
|
780
|
+
format_tables(output_path)
|
|
781
|
+
|
|
782
|
+
# Apply table column width profiles from frontmatter
|
|
783
|
+
if fm_table_profiles:
|
|
784
|
+
applied = apply_table_profiles(output_path, fm_table_profiles)
|
|
785
|
+
if applied:
|
|
786
|
+
logger.info(f"Applied column width profiles to {applied} table(s)")
|
|
787
|
+
|
|
788
|
+
# Fix invalid table styles that cause PDF rendering issues in LibreOffice
|
|
789
|
+
fix_table_styles_for_pdf(output_path)
|
|
790
|
+
|
|
791
|
+
# Copy template's cover page if it has one (this preserves textboxes)
|
|
792
|
+
if template_has_cover_page:
|
|
793
|
+
copy_template_cover_page(output_path, template_path)
|
|
794
|
+
|
|
795
|
+
# Add TOC (insert after cover page if template has one)
|
|
796
|
+
# When template has a cover page, TOC should always go AFTER the cover page
|
|
797
|
+
# The {{$toc}} placeholder can be used for explicit positioning within content
|
|
798
|
+
if enable_toc:
|
|
799
|
+
# Always place TOC after cover page when template has one
|
|
800
|
+
# This prevents TOC from appearing on the cover page
|
|
801
|
+
if toc_config.mode == TocMode.STATIC:
|
|
802
|
+
# Use static TOC which generates actual hyperlinked entries
|
|
803
|
+
# This works correctly for PDF conversion without Word field updates
|
|
804
|
+
add_static_toc(
|
|
805
|
+
output_path,
|
|
806
|
+
toc_heading=toc_heading,
|
|
807
|
+
max_level=toc_config.style.max_level,
|
|
808
|
+
add_page_break=True,
|
|
809
|
+
after_cover_page=template_has_cover_page,
|
|
810
|
+
style_config=toc_config.style
|
|
811
|
+
)
|
|
812
|
+
else:
|
|
813
|
+
# Use dynamic TOC (Word field code)
|
|
814
|
+
# Requires Word/LibreOffice to update field when opened
|
|
815
|
+
add_toc(
|
|
816
|
+
output_path,
|
|
817
|
+
toc_heading=toc_heading,
|
|
818
|
+
add_page_break=True,
|
|
819
|
+
after_cover_page=template_has_cover_page,
|
|
820
|
+
style_config=toc_config.style
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
# Add auto-generated cover page (only if template doesn't have one)
|
|
824
|
+
# Only title on cover page - content stays in body after TOC
|
|
825
|
+
if should_create_cover and cover_title:
|
|
826
|
+
add_cover_page(output_path, cover_title)
|
|
827
|
+
|
|
828
|
+
# Apply template (replace placeholders in header/footer)
|
|
829
|
+
if template_path.exists() and (document_name or document_title):
|
|
830
|
+
apply_template(
|
|
831
|
+
output_path,
|
|
832
|
+
template_path,
|
|
833
|
+
document_name=document_name,
|
|
834
|
+
document_title=document_title
|
|
835
|
+
)
|
|
836
|
+
|
|
837
|
+
# Apply variable substitutions using XML-based approach
|
|
838
|
+
# This handles fragmented text (placeholders split across multiple runs)
|
|
839
|
+
# which is common in Word documents due to spell-checking, formatting, etc.
|
|
840
|
+
if merged_variables:
|
|
841
|
+
# Build replacements dictionary with both {{var}} and <var> syntax
|
|
842
|
+
textbox_replacements = {}
|
|
843
|
+
for var_name, value in merged_variables.items():
|
|
844
|
+
# Replace both syntaxes with the actual value
|
|
845
|
+
textbox_replacements[f'{{{{{var_name}}}}}'] = value # {{var}}
|
|
846
|
+
textbox_replacements[f'<{var_name}>'] = value # <var> (legacy)
|
|
847
|
+
if textbox_replacements:
|
|
848
|
+
# replace_text_in_textbox handles document.xml, headers, footers, and textboxes
|
|
849
|
+
# It also handles fragmented text across multiple <w:t> elements
|
|
850
|
+
replace_text_in_textbox(output_path, output_path, textbox_replacements)
|
|
851
|
+
|
|
852
|
+
# Replace logo placeholders with actual images
|
|
853
|
+
# Parse logos from frontmatter and markdown image syntax
|
|
854
|
+
# Supports both:
|
|
855
|
+
# 1. Frontmatter: logos: { company: "images/logo.png" }
|
|
856
|
+
# 2. Markdown: 
|
|
857
|
+
frontmatter_logos = parse_logos_frontmatter(frontmatter)
|
|
858
|
+
markdown_logos = extract_logos_from_markdown(content_without_frontmatter)
|
|
859
|
+
logos_config = merge_logo_configs(frontmatter_logos, markdown_logos)
|
|
860
|
+
if logos_config:
|
|
861
|
+
template_dir = Path(template_info['path']) if template_info and template_info.get('path') else None
|
|
862
|
+
replaced = replace_logo_placeholders_in_docx(
|
|
863
|
+
output_path,
|
|
864
|
+
logos_config,
|
|
865
|
+
source_path=input_path,
|
|
866
|
+
template_path=template_dir,
|
|
867
|
+
project_root=Path.cwd()
|
|
868
|
+
)
|
|
869
|
+
if replaced:
|
|
870
|
+
logger.info(f"Replaced {replaced} logo placeholder(s)")
|
|
871
|
+
|
|
872
|
+
# Apply spacing configuration to headings and diagrams
|
|
873
|
+
# Load template spacing config if available
|
|
874
|
+
template_spacing = None
|
|
875
|
+
if template_info and template_info.get('path'):
|
|
876
|
+
template_spacing = load_template_spacing(Path(template_info['path']))
|
|
877
|
+
|
|
878
|
+
# Extract spacing from frontmatter (merges with defaults)
|
|
879
|
+
frontmatter_spacing = extract_spacing_config(frontmatter)
|
|
880
|
+
|
|
881
|
+
# Merge: defaults -> template -> frontmatter (frontmatter takes priority)
|
|
882
|
+
if template_spacing:
|
|
883
|
+
spacing_config = template_spacing.merge(frontmatter_spacing)
|
|
884
|
+
else:
|
|
885
|
+
spacing_config = frontmatter_spacing
|
|
886
|
+
|
|
887
|
+
# Apply spacing to document
|
|
888
|
+
apply_spacing_to_document(output_path, spacing_config)
|
|
889
|
+
|
|
890
|
+
# Embed fonts into the DOCX file
|
|
891
|
+
if embed_fonts:
|
|
892
|
+
# Determine template fonts directory
|
|
893
|
+
template_fonts_dir = None
|
|
894
|
+
if template_info and template_info.get('path'):
|
|
895
|
+
template_fonts_dir = Path(template_info['path']) / 'fonts'
|
|
896
|
+
|
|
897
|
+
# Default fonts directory
|
|
898
|
+
default_fonts_dir = resolved_templates_dir / 'default' / 'fonts'
|
|
899
|
+
|
|
900
|
+
# Embed fonts
|
|
901
|
+
embed_template_fonts(
|
|
902
|
+
output_path,
|
|
903
|
+
template_fonts_dir=template_fonts_dir,
|
|
904
|
+
default_fonts_dir=default_fonts_dir,
|
|
905
|
+
include_system=True
|
|
906
|
+
)
|
|
907
|
+
|
|
908
|
+
# Update field codes (TOC, page numbers, etc.) if requested
|
|
909
|
+
# Default: auto-enable when TOC is enabled
|
|
910
|
+
should_update_fields = update_fields if update_fields is not None else enable_toc
|
|
911
|
+
if should_update_fields:
|
|
912
|
+
fields_updated = update_fields_if_available(output_path)
|
|
913
|
+
if fields_updated:
|
|
914
|
+
logger.info("Field codes (TOC, page numbers) updated successfully")
|
|
915
|
+
elif enable_toc:
|
|
916
|
+
logger.warning(
|
|
917
|
+
"Could not update field codes automatically. "
|
|
918
|
+
"LibreOffice is required for TOC generation. "
|
|
919
|
+
"Please update fields manually in Word (Ctrl+A, F9) or install LibreOffice."
|
|
920
|
+
)
|
|
921
|
+
|
|
922
|
+
finally:
|
|
923
|
+
# Clean up temporary files
|
|
924
|
+
cleanup_temp_files(temp_dir)
|
|
925
|
+
|
|
926
|
+
# Clean up extracted fonts
|
|
927
|
+
if fonts_dir and fonts_dir.exists():
|
|
928
|
+
cleanup_extracted_fonts(fonts_dir)
|