@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,735 @@
|
|
|
1
|
+
"""PDF conversion logic using local LibreOffice or Docker-based Gotenberg service.
|
|
2
|
+
|
|
3
|
+
Provides functions to convert DOCX, Markdown, and AsciiDoc files to PDF format.
|
|
4
|
+
Prefers local LibreOffice installation for better compatibility, falls back to
|
|
5
|
+
gotenberg/gotenberg:8 Docker image when local LibreOffice is not available.
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import tempfile
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Dict, List, Optional, Tuple, Union
|
|
14
|
+
import urllib.request
|
|
15
|
+
import urllib.error
|
|
16
|
+
|
|
17
|
+
from .pdf_server import get_server, PDFServerError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def find_local_libreoffice() -> Optional[str]:
|
|
21
|
+
"""Find local LibreOffice installation.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
Path to LibreOffice soffice binary, or None if not found.
|
|
25
|
+
"""
|
|
26
|
+
# Check common locations
|
|
27
|
+
candidates = [
|
|
28
|
+
# macOS
|
|
29
|
+
'/Applications/LibreOffice.app/Contents/MacOS/soffice',
|
|
30
|
+
# Linux
|
|
31
|
+
'/usr/bin/libreoffice',
|
|
32
|
+
'/usr/bin/soffice',
|
|
33
|
+
'/usr/local/bin/libreoffice',
|
|
34
|
+
'/usr/local/bin/soffice',
|
|
35
|
+
# Snap on Linux
|
|
36
|
+
'/snap/bin/libreoffice',
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
# Check PATH
|
|
40
|
+
soffice_path = shutil.which('soffice')
|
|
41
|
+
if soffice_path:
|
|
42
|
+
return soffice_path
|
|
43
|
+
|
|
44
|
+
libreoffice_path = shutil.which('libreoffice')
|
|
45
|
+
if libreoffice_path:
|
|
46
|
+
return libreoffice_path
|
|
47
|
+
|
|
48
|
+
# Check common locations
|
|
49
|
+
for candidate in candidates:
|
|
50
|
+
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
|
|
51
|
+
return candidate
|
|
52
|
+
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _find_libreoffice_python(libreoffice_path: str) -> Optional[str]:
|
|
57
|
+
"""Find the Python interpreter bundled with LibreOffice.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
libreoffice_path: Path to LibreOffice soffice binary.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
Path to LibreOffice's Python interpreter, or None if not found.
|
|
64
|
+
"""
|
|
65
|
+
lo_dir = Path(libreoffice_path).parent
|
|
66
|
+
|
|
67
|
+
# macOS: /Applications/LibreOffice.app/Contents/MacOS/soffice
|
|
68
|
+
# Python is at: /Applications/LibreOffice.app/Contents/Resources/python
|
|
69
|
+
if 'MacOS' in str(lo_dir):
|
|
70
|
+
python_path = lo_dir.parent / 'Resources' / 'python'
|
|
71
|
+
if python_path.exists():
|
|
72
|
+
return str(python_path)
|
|
73
|
+
|
|
74
|
+
# Linux: /usr/bin/libreoffice or /usr/bin/soffice
|
|
75
|
+
# Python with uno is typically the system Python with python3-uno package
|
|
76
|
+
# Check if system Python has uno
|
|
77
|
+
try:
|
|
78
|
+
result = subprocess.run(
|
|
79
|
+
['python3', '-c', 'import uno'],
|
|
80
|
+
capture_output=True,
|
|
81
|
+
timeout=5
|
|
82
|
+
)
|
|
83
|
+
if result.returncode == 0:
|
|
84
|
+
return 'python3'
|
|
85
|
+
except Exception:
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _convert_with_toc_update(
|
|
92
|
+
docx_path: Path,
|
|
93
|
+
output_path: Path,
|
|
94
|
+
libreoffice_path: str
|
|
95
|
+
) -> bool:
|
|
96
|
+
"""Convert DOCX to PDF with TOC update using LibreOffice Python/UNO.
|
|
97
|
+
|
|
98
|
+
This starts LibreOffice with a socket listener, runs a Python script via UNO
|
|
99
|
+
to update all indexes and export to PDF, then terminates LibreOffice.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
docx_path: Path to input DOCX file.
|
|
103
|
+
output_path: Path to output PDF file.
|
|
104
|
+
libreoffice_path: Path to LibreOffice soffice binary.
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
True if conversion succeeded, False if it failed (caller should fallback).
|
|
108
|
+
|
|
109
|
+
Note:
|
|
110
|
+
This approach requires the uno Python module which comes with LibreOffice.
|
|
111
|
+
If uno is not available or the conversion fails, returns False so the
|
|
112
|
+
caller can fall back to the standard conversion method.
|
|
113
|
+
"""
|
|
114
|
+
import time
|
|
115
|
+
|
|
116
|
+
output_dir = output_path.parent
|
|
117
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
|
|
119
|
+
# Find LibreOffice Python first - if not available, skip this method
|
|
120
|
+
lo_python = _find_libreoffice_python(libreoffice_path)
|
|
121
|
+
if lo_python is None:
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
# Create a temporary Python script for the conversion
|
|
125
|
+
script_content = f'''#!/usr/bin/env python3
|
|
126
|
+
"""LibreOffice UNO script to update TOC and export to PDF."""
|
|
127
|
+
import sys
|
|
128
|
+
import time
|
|
129
|
+
|
|
130
|
+
def main():
|
|
131
|
+
try:
|
|
132
|
+
import uno
|
|
133
|
+
from com.sun.star.beans import PropertyValue
|
|
134
|
+
except ImportError:
|
|
135
|
+
print("ERROR: uno module not available", file=sys.stderr)
|
|
136
|
+
sys.exit(1)
|
|
137
|
+
|
|
138
|
+
# Connect to LibreOffice
|
|
139
|
+
max_retries = 30
|
|
140
|
+
for attempt in range(max_retries):
|
|
141
|
+
try:
|
|
142
|
+
localContext = uno.getComponentContext()
|
|
143
|
+
resolver = localContext.ServiceManager.createInstanceWithContext(
|
|
144
|
+
"com.sun.star.bridge.UnoUrlResolver", localContext)
|
|
145
|
+
ctx = resolver.resolve(
|
|
146
|
+
"uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
|
|
147
|
+
break
|
|
148
|
+
except Exception:
|
|
149
|
+
if attempt < max_retries - 1:
|
|
150
|
+
time.sleep(0.5)
|
|
151
|
+
else:
|
|
152
|
+
print("ERROR: Could not connect to LibreOffice", file=sys.stderr)
|
|
153
|
+
sys.exit(1)
|
|
154
|
+
|
|
155
|
+
smgr = ctx.ServiceManager
|
|
156
|
+
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
|
|
157
|
+
|
|
158
|
+
# Load document
|
|
159
|
+
doc_url = "file://{docx_path.absolute().as_posix()}"
|
|
160
|
+
load_props = (
|
|
161
|
+
PropertyValue(Name="Hidden", Value=True),
|
|
162
|
+
)
|
|
163
|
+
doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, load_props)
|
|
164
|
+
|
|
165
|
+
if doc is None:
|
|
166
|
+
print("ERROR: Could not load document", file=sys.stderr)
|
|
167
|
+
sys.exit(1)
|
|
168
|
+
|
|
169
|
+
# Update all indexes (TOC, etc.)
|
|
170
|
+
try:
|
|
171
|
+
if doc.supportsService("com.sun.star.text.GenericTextDocument"):
|
|
172
|
+
indexes = doc.getDocumentIndexes()
|
|
173
|
+
count = indexes.getCount()
|
|
174
|
+
for i in range(count):
|
|
175
|
+
indexes.getByIndex(i).update()
|
|
176
|
+
print(f"Updated {{count}} index(es)")
|
|
177
|
+
except Exception as e:
|
|
178
|
+
print(f"Warning: Could not update indexes: {{e}}", file=sys.stderr)
|
|
179
|
+
|
|
180
|
+
# Export to PDF with embedded fonts
|
|
181
|
+
# Create PDF filter data with font embedding options
|
|
182
|
+
pdf_filter_data = (
|
|
183
|
+
PropertyValue(Name="EmbedStandardFonts", Value=True),
|
|
184
|
+
PropertyValue(Name="EmbedLinkedFonts", Value=True),
|
|
185
|
+
PropertyValue(Name="UseTaggedPDF", Value=True),
|
|
186
|
+
PropertyValue(Name="ExportBookmarks", Value=True),
|
|
187
|
+
)
|
|
188
|
+
pdf_props = (
|
|
189
|
+
PropertyValue(Name="FilterName", Value="writer_pdf_Export"),
|
|
190
|
+
PropertyValue(Name="FilterData", Value=pdf_filter_data),
|
|
191
|
+
)
|
|
192
|
+
pdf_url = "file://{output_path.absolute().as_posix()}"
|
|
193
|
+
doc.storeToURL(pdf_url, pdf_props)
|
|
194
|
+
|
|
195
|
+
# Close document
|
|
196
|
+
doc.close(True)
|
|
197
|
+
|
|
198
|
+
# Terminate LibreOffice
|
|
199
|
+
desktop.terminate()
|
|
200
|
+
|
|
201
|
+
print("SUCCESS")
|
|
202
|
+
|
|
203
|
+
if __name__ == "__main__":
|
|
204
|
+
main()
|
|
205
|
+
'''
|
|
206
|
+
|
|
207
|
+
# Write the script to a temp file
|
|
208
|
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
|
|
209
|
+
f.write(script_content)
|
|
210
|
+
script_path = f.name
|
|
211
|
+
|
|
212
|
+
lo_process = None
|
|
213
|
+
try:
|
|
214
|
+
# Start LibreOffice with socket listener
|
|
215
|
+
lo_process = subprocess.Popen(
|
|
216
|
+
[
|
|
217
|
+
libreoffice_path,
|
|
218
|
+
'--headless',
|
|
219
|
+
'--invisible',
|
|
220
|
+
'--nologo',
|
|
221
|
+
'--nofirststartwizard',
|
|
222
|
+
'--accept=socket,host=localhost,port=2002;urp;'
|
|
223
|
+
],
|
|
224
|
+
stdout=subprocess.DEVNULL,
|
|
225
|
+
stderr=subprocess.DEVNULL
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
# Give LibreOffice time to start
|
|
229
|
+
time.sleep(2)
|
|
230
|
+
|
|
231
|
+
# Run the script using LibreOffice's Python
|
|
232
|
+
result = subprocess.run(
|
|
233
|
+
[lo_python, script_path],
|
|
234
|
+
capture_output=True,
|
|
235
|
+
text=True,
|
|
236
|
+
timeout=120
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# Check if successful
|
|
240
|
+
if result.returncode == 0 and output_path.exists():
|
|
241
|
+
return True
|
|
242
|
+
else:
|
|
243
|
+
return False
|
|
244
|
+
|
|
245
|
+
except Exception:
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
finally:
|
|
249
|
+
# Clean up
|
|
250
|
+
try:
|
|
251
|
+
os.unlink(script_path)
|
|
252
|
+
except OSError:
|
|
253
|
+
pass
|
|
254
|
+
if lo_process:
|
|
255
|
+
try:
|
|
256
|
+
lo_process.terminate()
|
|
257
|
+
lo_process.wait(timeout=5)
|
|
258
|
+
except Exception:
|
|
259
|
+
try:
|
|
260
|
+
lo_process.kill()
|
|
261
|
+
except Exception:
|
|
262
|
+
pass
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _convert_with_local_libreoffice(
|
|
266
|
+
docx_path: Path,
|
|
267
|
+
output_path: Path,
|
|
268
|
+
libreoffice_path: str
|
|
269
|
+
) -> None:
|
|
270
|
+
"""Convert DOCX to PDF using local LibreOffice.
|
|
271
|
+
|
|
272
|
+
Args:
|
|
273
|
+
docx_path: Path to input DOCX file.
|
|
274
|
+
output_path: Path to output PDF file.
|
|
275
|
+
libreoffice_path: Path to LibreOffice soffice binary.
|
|
276
|
+
|
|
277
|
+
Raises:
|
|
278
|
+
PDFConversionError: If conversion fails.
|
|
279
|
+
"""
|
|
280
|
+
# LibreOffice outputs to the same directory as input by default,
|
|
281
|
+
# or to --outdir if specified. We need to handle this.
|
|
282
|
+
output_dir = output_path.parent
|
|
283
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
284
|
+
|
|
285
|
+
# Run LibreOffice in headless mode with font embedding
|
|
286
|
+
# Use writer_pdf_Export filter with EmbedStandardFonts option
|
|
287
|
+
result = subprocess.run(
|
|
288
|
+
[
|
|
289
|
+
libreoffice_path,
|
|
290
|
+
'--headless',
|
|
291
|
+
'--convert-to', 'pdf:writer_pdf_Export:{"EmbedStandardFonts":{"type":"boolean","value":"true"}}',
|
|
292
|
+
'--outdir', str(output_dir),
|
|
293
|
+
str(docx_path)
|
|
294
|
+
],
|
|
295
|
+
capture_output=True,
|
|
296
|
+
text=True,
|
|
297
|
+
timeout=120
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
if result.returncode != 0:
|
|
301
|
+
raise PDFConversionError(
|
|
302
|
+
f"LibreOffice conversion failed: {result.stderr}"
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
# LibreOffice names the output based on input filename
|
|
306
|
+
expected_output = output_dir / f"{docx_path.stem}.pdf"
|
|
307
|
+
|
|
308
|
+
if not expected_output.exists():
|
|
309
|
+
raise PDFConversionError(
|
|
310
|
+
f"LibreOffice did not create expected output file: {expected_output}"
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
# Rename if needed
|
|
314
|
+
if expected_output != output_path:
|
|
315
|
+
expected_output.rename(output_path)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
class PDFConversionError(Exception):
|
|
319
|
+
"""Exception raised for PDF conversion errors."""
|
|
320
|
+
pass
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
@dataclass
|
|
324
|
+
class PDFOptions:
|
|
325
|
+
"""Options for PDF conversion.
|
|
326
|
+
|
|
327
|
+
Attributes:
|
|
328
|
+
pdf_format: PDF format - 'pdf' (standard) or 'pdf/a' (archival).
|
|
329
|
+
page_size: Page size - 'a4' (default), 'letter', etc.
|
|
330
|
+
keep_docx: Keep intermediate DOCX file when converting from MD/AsciiDoc.
|
|
331
|
+
"""
|
|
332
|
+
pdf_format: str = 'pdf'
|
|
333
|
+
page_size: str = 'a4'
|
|
334
|
+
keep_docx: bool = True
|
|
335
|
+
|
|
336
|
+
def __post_init__(self):
|
|
337
|
+
"""Validate options."""
|
|
338
|
+
valid_formats = ('pdf', 'pdf/a')
|
|
339
|
+
if self.pdf_format.lower() not in valid_formats:
|
|
340
|
+
raise ValueError(f"Invalid pdf_format: {self.pdf_format}. Must be one of: {valid_formats}")
|
|
341
|
+
|
|
342
|
+
valid_sizes = ('a4', 'letter', 'legal', 'a3', 'a5')
|
|
343
|
+
if self.page_size.lower() not in valid_sizes:
|
|
344
|
+
raise ValueError(f"Invalid page_size: {self.page_size}. Must be one of: {valid_sizes}")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@dataclass
|
|
348
|
+
class BatchConversionResult:
|
|
349
|
+
"""Result of batch PDF conversion.
|
|
350
|
+
|
|
351
|
+
Attributes:
|
|
352
|
+
successful: List of successfully converted file paths.
|
|
353
|
+
failed: Dictionary mapping failed file paths to error messages.
|
|
354
|
+
total: Total number of files processed.
|
|
355
|
+
"""
|
|
356
|
+
successful: List[Path] = field(default_factory=list)
|
|
357
|
+
failed: Dict[Path, str] = field(default_factory=dict)
|
|
358
|
+
total: int = 0
|
|
359
|
+
|
|
360
|
+
@property
|
|
361
|
+
def success_count(self) -> int:
|
|
362
|
+
"""Number of successfully converted files."""
|
|
363
|
+
return len(self.successful)
|
|
364
|
+
|
|
365
|
+
@property
|
|
366
|
+
def failure_count(self) -> int:
|
|
367
|
+
"""Number of failed conversions."""
|
|
368
|
+
return len(self.failed)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _send_conversion_request(docx_path: Path, base_url: str) -> bytes:
|
|
372
|
+
"""Send DOCX file to Gotenberg server and get PDF bytes.
|
|
373
|
+
|
|
374
|
+
Args:
|
|
375
|
+
docx_path: Path to DOCX file.
|
|
376
|
+
base_url: Base URL of the Gotenberg server.
|
|
377
|
+
|
|
378
|
+
Returns:
|
|
379
|
+
PDF file content as bytes.
|
|
380
|
+
|
|
381
|
+
Raises:
|
|
382
|
+
PDFConversionError: If conversion fails.
|
|
383
|
+
"""
|
|
384
|
+
# Gotenberg LibreOffice conversion endpoint
|
|
385
|
+
url = f"{base_url}/forms/libreoffice/convert"
|
|
386
|
+
|
|
387
|
+
# Read DOCX file
|
|
388
|
+
docx_content = docx_path.read_bytes()
|
|
389
|
+
|
|
390
|
+
# Build multipart form data for Gotenberg
|
|
391
|
+
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
|
|
392
|
+
body = []
|
|
393
|
+
|
|
394
|
+
# Add file field (Gotenberg expects 'files' as field name)
|
|
395
|
+
body.append(f'--{boundary}'.encode())
|
|
396
|
+
body.append(f'Content-Disposition: form-data; name="files"; filename="{docx_path.name}"'.encode())
|
|
397
|
+
body.append(b'Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|
|
398
|
+
body.append(b'')
|
|
399
|
+
body.append(docx_content)
|
|
400
|
+
|
|
401
|
+
body.append(f'--{boundary}--'.encode())
|
|
402
|
+
|
|
403
|
+
body_bytes = b'\r\n'.join(body)
|
|
404
|
+
|
|
405
|
+
# Create request
|
|
406
|
+
request = urllib.request.Request(
|
|
407
|
+
url,
|
|
408
|
+
data=body_bytes,
|
|
409
|
+
headers={
|
|
410
|
+
'Content-Type': f'multipart/form-data; boundary={boundary}',
|
|
411
|
+
'Content-Length': str(len(body_bytes))
|
|
412
|
+
},
|
|
413
|
+
method='POST'
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
try:
|
|
417
|
+
with urllib.request.urlopen(request, timeout=120) as response:
|
|
418
|
+
if response.status != 200:
|
|
419
|
+
raise PDFConversionError(f"Conversion failed with status {response.status}")
|
|
420
|
+
return response.read()
|
|
421
|
+
except urllib.error.HTTPError as e:
|
|
422
|
+
raise PDFConversionError(f"Conversion failed: HTTP {e.code} - {e.reason}")
|
|
423
|
+
except urllib.error.URLError as e:
|
|
424
|
+
raise PDFConversionError(f"Connection to PDF server failed: {e.reason}")
|
|
425
|
+
except TimeoutError:
|
|
426
|
+
raise PDFConversionError("Conversion timed out after 120 seconds")
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def convert_docx_to_pdf(
|
|
430
|
+
input_path: Union[str, Path],
|
|
431
|
+
output_path: Union[str, Path],
|
|
432
|
+
pdf_format: str = 'pdf',
|
|
433
|
+
page_size: str = 'a4',
|
|
434
|
+
use_docker: bool = False,
|
|
435
|
+
update_toc: bool = True
|
|
436
|
+
) -> None:
|
|
437
|
+
"""Convert DOCX file to PDF.
|
|
438
|
+
|
|
439
|
+
Prefers local LibreOffice installation for better table rendering compatibility.
|
|
440
|
+
Falls back to Docker-based Gotenberg service if local LibreOffice is not available.
|
|
441
|
+
|
|
442
|
+
Args:
|
|
443
|
+
input_path: Path to input DOCX file.
|
|
444
|
+
output_path: Path to output PDF file.
|
|
445
|
+
pdf_format: PDF format - 'pdf' (standard) or 'pdf/a' (archival).
|
|
446
|
+
page_size: Page size - 'a4' (default), 'letter', etc.
|
|
447
|
+
use_docker: Force use of Docker/Gotenberg even if local LibreOffice is available.
|
|
448
|
+
update_toc: Update Table of Contents before PDF export (default: True).
|
|
449
|
+
This ensures page numbers in the TOC are correct. Requires LibreOffice
|
|
450
|
+
Python/UNO support. If unavailable, falls back to standard conversion.
|
|
451
|
+
|
|
452
|
+
Raises:
|
|
453
|
+
FileNotFoundError: If input file does not exist.
|
|
454
|
+
PDFServerError: If Docker/server is not available and no local LibreOffice.
|
|
455
|
+
PDFConversionError: If conversion fails.
|
|
456
|
+
"""
|
|
457
|
+
input_path = Path(input_path)
|
|
458
|
+
output_path = Path(output_path)
|
|
459
|
+
|
|
460
|
+
# Validate input
|
|
461
|
+
if not input_path.exists():
|
|
462
|
+
raise FileNotFoundError(f"Input file does not exist: {input_path}")
|
|
463
|
+
|
|
464
|
+
# Validate options
|
|
465
|
+
options = PDFOptions(pdf_format=pdf_format, page_size=page_size)
|
|
466
|
+
|
|
467
|
+
# Try local LibreOffice first (better table rendering compatibility)
|
|
468
|
+
if not use_docker:
|
|
469
|
+
libreoffice_path = find_local_libreoffice()
|
|
470
|
+
if libreoffice_path:
|
|
471
|
+
# First try with TOC update if requested (uses UNO API for proper page numbers)
|
|
472
|
+
if update_toc and _convert_with_toc_update(input_path, output_path, libreoffice_path):
|
|
473
|
+
return
|
|
474
|
+
# Fall back to standard conversion if TOC update not requested or fails
|
|
475
|
+
_convert_with_local_libreoffice(input_path, output_path, libreoffice_path)
|
|
476
|
+
return
|
|
477
|
+
|
|
478
|
+
# Fall back to Docker/Gotenberg
|
|
479
|
+
server = get_server()
|
|
480
|
+
base_url = server.ensure_running()
|
|
481
|
+
|
|
482
|
+
# Convert
|
|
483
|
+
pdf_bytes = _send_conversion_request(input_path, base_url)
|
|
484
|
+
|
|
485
|
+
# Write output
|
|
486
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
487
|
+
output_path.write_bytes(pdf_bytes)
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def convert_md_to_pdf(
|
|
491
|
+
input_path: Union[str, Path],
|
|
492
|
+
output_path: Union[str, Path],
|
|
493
|
+
keep_docx: bool = True,
|
|
494
|
+
pdf_format: str = 'pdf',
|
|
495
|
+
page_size: str = 'a4',
|
|
496
|
+
template_name: Optional[str] = None,
|
|
497
|
+
templates_dir: Optional[Union[str, Path]] = None,
|
|
498
|
+
**md_kwargs
|
|
499
|
+
) -> Path:
|
|
500
|
+
"""Convert Markdown file to PDF via intermediate DOCX.
|
|
501
|
+
|
|
502
|
+
Args:
|
|
503
|
+
input_path: Path to input Markdown file.
|
|
504
|
+
output_path: Path to output PDF file.
|
|
505
|
+
keep_docx: Keep intermediate DOCX file (default: True).
|
|
506
|
+
pdf_format: PDF format - 'pdf' (standard) or 'pdf/a' (archival).
|
|
507
|
+
page_size: Page size - 'a4' (default), 'letter', etc.
|
|
508
|
+
template_name: Optional template name for DOCX conversion.
|
|
509
|
+
templates_dir: Directory containing templates.
|
|
510
|
+
**md_kwargs: Additional arguments passed to convert_md_to_docx.
|
|
511
|
+
|
|
512
|
+
Returns:
|
|
513
|
+
Path to intermediate DOCX file (if keep_docx=True) or None.
|
|
514
|
+
|
|
515
|
+
Raises:
|
|
516
|
+
FileNotFoundError: If input file does not exist.
|
|
517
|
+
PDFServerError: If Docker/server is not available.
|
|
518
|
+
PDFConversionError: If conversion fails.
|
|
519
|
+
"""
|
|
520
|
+
from .converter import convert_md_to_docx
|
|
521
|
+
|
|
522
|
+
input_path = Path(input_path)
|
|
523
|
+
output_path = Path(output_path)
|
|
524
|
+
|
|
525
|
+
# Validate input
|
|
526
|
+
if not input_path.exists():
|
|
527
|
+
raise FileNotFoundError(f"Input file does not exist: {input_path}")
|
|
528
|
+
|
|
529
|
+
# Determine intermediate DOCX path
|
|
530
|
+
docx_path = output_path.with_suffix('.docx')
|
|
531
|
+
|
|
532
|
+
try:
|
|
533
|
+
# Convert MD to DOCX
|
|
534
|
+
convert_md_to_docx(
|
|
535
|
+
input_path,
|
|
536
|
+
docx_path,
|
|
537
|
+
template_name=template_name,
|
|
538
|
+
templates_dir=templates_dir,
|
|
539
|
+
**md_kwargs
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
# Convert DOCX to PDF
|
|
543
|
+
convert_docx_to_pdf(
|
|
544
|
+
docx_path,
|
|
545
|
+
output_path,
|
|
546
|
+
pdf_format=pdf_format,
|
|
547
|
+
page_size=page_size
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
return docx_path if keep_docx else None
|
|
551
|
+
|
|
552
|
+
finally:
|
|
553
|
+
# Clean up intermediate file if not keeping
|
|
554
|
+
if not keep_docx and docx_path.exists():
|
|
555
|
+
docx_path.unlink()
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def convert_adoc_to_pdf(
|
|
559
|
+
input_path: Union[str, Path],
|
|
560
|
+
output_path: Union[str, Path],
|
|
561
|
+
keep_docx: bool = True,
|
|
562
|
+
pdf_format: str = 'pdf',
|
|
563
|
+
page_size: str = 'a4',
|
|
564
|
+
template_path: Optional[Union[str, Path]] = None,
|
|
565
|
+
**adoc_kwargs
|
|
566
|
+
) -> Path:
|
|
567
|
+
"""Convert AsciiDoc file to PDF via intermediate DOCX.
|
|
568
|
+
|
|
569
|
+
Args:
|
|
570
|
+
input_path: Path to input AsciiDoc file.
|
|
571
|
+
output_path: Path to output PDF file.
|
|
572
|
+
keep_docx: Keep intermediate DOCX file (default: True).
|
|
573
|
+
pdf_format: PDF format - 'pdf' (standard) or 'pdf/a' (archival).
|
|
574
|
+
page_size: Page size - 'a4' (default), 'letter', etc.
|
|
575
|
+
template_path: Optional path to DOCX template for styling.
|
|
576
|
+
**adoc_kwargs: Additional arguments passed to convert_adoc_to_docx.
|
|
577
|
+
|
|
578
|
+
Returns:
|
|
579
|
+
Path to intermediate DOCX file (if keep_docx=True) or None.
|
|
580
|
+
|
|
581
|
+
Raises:
|
|
582
|
+
FileNotFoundError: If input file does not exist.
|
|
583
|
+
PDFServerError: If Docker/server is not available.
|
|
584
|
+
PDFConversionError: If conversion fails.
|
|
585
|
+
"""
|
|
586
|
+
from .asciidoc_converter import convert_adoc_to_docx
|
|
587
|
+
|
|
588
|
+
input_path = Path(input_path)
|
|
589
|
+
output_path = Path(output_path)
|
|
590
|
+
|
|
591
|
+
# Validate input
|
|
592
|
+
if not input_path.exists():
|
|
593
|
+
raise FileNotFoundError(f"Input file does not exist: {input_path}")
|
|
594
|
+
|
|
595
|
+
# Determine intermediate DOCX path
|
|
596
|
+
docx_path = output_path.with_suffix('.docx')
|
|
597
|
+
|
|
598
|
+
try:
|
|
599
|
+
# Convert AsciiDoc to DOCX
|
|
600
|
+
convert_adoc_to_docx(
|
|
601
|
+
input_path,
|
|
602
|
+
docx_path,
|
|
603
|
+
template_path=template_path,
|
|
604
|
+
**adoc_kwargs
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
# Convert DOCX to PDF
|
|
608
|
+
convert_docx_to_pdf(
|
|
609
|
+
docx_path,
|
|
610
|
+
output_path,
|
|
611
|
+
pdf_format=pdf_format,
|
|
612
|
+
page_size=page_size
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
return docx_path if keep_docx else None
|
|
616
|
+
|
|
617
|
+
finally:
|
|
618
|
+
# Clean up intermediate file if not keeping
|
|
619
|
+
if not keep_docx and docx_path.exists():
|
|
620
|
+
docx_path.unlink()
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def convert_to_pdf(
|
|
624
|
+
input_path: Union[str, Path],
|
|
625
|
+
output_path: Union[str, Path],
|
|
626
|
+
keep_docx: bool = True,
|
|
627
|
+
pdf_format: str = 'pdf',
|
|
628
|
+
page_size: str = 'a4',
|
|
629
|
+
**kwargs
|
|
630
|
+
) -> Optional[Path]:
|
|
631
|
+
"""Convert document to PDF with automatic format detection.
|
|
632
|
+
|
|
633
|
+
Detects input format based on file extension and uses the appropriate
|
|
634
|
+
converter (DOCX, Markdown, or AsciiDoc).
|
|
635
|
+
|
|
636
|
+
Args:
|
|
637
|
+
input_path: Path to input file (.docx, .md, .markdown, .adoc, .asciidoc, .asc).
|
|
638
|
+
output_path: Path to output PDF file.
|
|
639
|
+
keep_docx: Keep intermediate DOCX file when converting from MD/AsciiDoc.
|
|
640
|
+
pdf_format: PDF format - 'pdf' (standard) or 'pdf/a' (archival).
|
|
641
|
+
page_size: Page size - 'a4' (default), 'letter', etc.
|
|
642
|
+
**kwargs: Additional arguments passed to the specific converter.
|
|
643
|
+
|
|
644
|
+
Returns:
|
|
645
|
+
Path to intermediate DOCX file (if applicable and keep_docx=True) or None.
|
|
646
|
+
|
|
647
|
+
Raises:
|
|
648
|
+
FileNotFoundError: If input file does not exist.
|
|
649
|
+
ValueError: If input format cannot be detected.
|
|
650
|
+
PDFServerError: If Docker/server is not available.
|
|
651
|
+
PDFConversionError: If conversion fails.
|
|
652
|
+
"""
|
|
653
|
+
input_path = Path(input_path)
|
|
654
|
+
ext = input_path.suffix.lower()
|
|
655
|
+
|
|
656
|
+
if ext == '.docx':
|
|
657
|
+
convert_docx_to_pdf(
|
|
658
|
+
input_path,
|
|
659
|
+
output_path,
|
|
660
|
+
pdf_format=pdf_format,
|
|
661
|
+
page_size=page_size
|
|
662
|
+
)
|
|
663
|
+
return None
|
|
664
|
+
|
|
665
|
+
elif ext in ('.md', '.markdown'):
|
|
666
|
+
return convert_md_to_pdf(
|
|
667
|
+
input_path,
|
|
668
|
+
output_path,
|
|
669
|
+
keep_docx=keep_docx,
|
|
670
|
+
pdf_format=pdf_format,
|
|
671
|
+
page_size=page_size,
|
|
672
|
+
**kwargs
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
elif ext in ('.adoc', '.asciidoc', '.asc'):
|
|
676
|
+
return convert_adoc_to_pdf(
|
|
677
|
+
input_path,
|
|
678
|
+
output_path,
|
|
679
|
+
keep_docx=keep_docx,
|
|
680
|
+
pdf_format=pdf_format,
|
|
681
|
+
page_size=page_size,
|
|
682
|
+
**kwargs
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
else:
|
|
686
|
+
raise ValueError(
|
|
687
|
+
f"Cannot detect format for file: {input_path}. "
|
|
688
|
+
"Supported extensions: .docx, .md, .markdown, .adoc, .asciidoc, .asc"
|
|
689
|
+
)
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def batch_convert_to_pdf(
|
|
693
|
+
input_paths: List[Union[str, Path]],
|
|
694
|
+
output_dir: Union[str, Path],
|
|
695
|
+
keep_docx: bool = True,
|
|
696
|
+
pdf_format: str = 'pdf',
|
|
697
|
+
page_size: str = 'a4',
|
|
698
|
+
**kwargs
|
|
699
|
+
) -> BatchConversionResult:
|
|
700
|
+
"""Convert multiple files to PDF.
|
|
701
|
+
|
|
702
|
+
Args:
|
|
703
|
+
input_paths: List of input file paths.
|
|
704
|
+
output_dir: Directory for output PDF files.
|
|
705
|
+
keep_docx: Keep intermediate DOCX files when converting from MD/AsciiDoc.
|
|
706
|
+
pdf_format: PDF format - 'pdf' (standard) or 'pdf/a' (archival).
|
|
707
|
+
page_size: Page size - 'a4' (default), 'letter', etc.
|
|
708
|
+
**kwargs: Additional arguments passed to converters.
|
|
709
|
+
|
|
710
|
+
Returns:
|
|
711
|
+
BatchConversionResult with lists of successful and failed conversions.
|
|
712
|
+
"""
|
|
713
|
+
output_dir = Path(output_dir)
|
|
714
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
715
|
+
|
|
716
|
+
result = BatchConversionResult(total=len(input_paths))
|
|
717
|
+
|
|
718
|
+
for input_path in input_paths:
|
|
719
|
+
input_path = Path(input_path)
|
|
720
|
+
output_path = output_dir / f"{input_path.stem}.pdf"
|
|
721
|
+
|
|
722
|
+
try:
|
|
723
|
+
convert_to_pdf(
|
|
724
|
+
input_path,
|
|
725
|
+
output_path,
|
|
726
|
+
keep_docx=keep_docx,
|
|
727
|
+
pdf_format=pdf_format,
|
|
728
|
+
page_size=page_size,
|
|
729
|
+
**kwargs
|
|
730
|
+
)
|
|
731
|
+
result.successful.append(output_path)
|
|
732
|
+
except Exception as e:
|
|
733
|
+
result.failed[input_path] = str(e)
|
|
734
|
+
|
|
735
|
+
return result
|