docx2pdf-libre 0.1.0__py3-none-any.whl
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.
- docx2pdf_libre/__init__.py +52 -0
- docx2pdf_libre/converter.py +431 -0
- docx2pdf_libre/exceptions.py +49 -0
- docx2pdf_libre/libreoffice.py +174 -0
- docx2pdf_libre/models.py +59 -0
- docx2pdf_libre/py.typed +0 -0
- docx2pdf_libre-0.1.0.dist-info/METADATA +231 -0
- docx2pdf_libre-0.1.0.dist-info/RECORD +11 -0
- docx2pdf_libre-0.1.0.dist-info/WHEEL +5 -0
- docx2pdf_libre-0.1.0.dist-info/licenses/LICENSE +189 -0
- docx2pdf_libre-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Zero-dependency Python library for converting Office documents to PDF via LibreOffice."""
|
|
2
|
+
|
|
3
|
+
from docx2pdf_libre.converter import (
|
|
4
|
+
convert_bytes,
|
|
5
|
+
convert_directory,
|
|
6
|
+
convert_file,
|
|
7
|
+
discover_documents,
|
|
8
|
+
normalize_extensions,
|
|
9
|
+
)
|
|
10
|
+
from docx2pdf_libre.exceptions import (
|
|
11
|
+
ConversionError,
|
|
12
|
+
ConversionTimeoutError,
|
|
13
|
+
Docx2PdfError,
|
|
14
|
+
InvalidInputError,
|
|
15
|
+
LibreOfficeNotFoundError,
|
|
16
|
+
)
|
|
17
|
+
from docx2pdf_libre.libreoffice import (
|
|
18
|
+
DEFAULT_BATCH_EXTENSIONS,
|
|
19
|
+
DEFAULT_SUPPORTED_EXTENSIONS,
|
|
20
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
21
|
+
find_libreoffice,
|
|
22
|
+
get_libreoffice_version,
|
|
23
|
+
)
|
|
24
|
+
from docx2pdf_libre.models import (
|
|
25
|
+
BatchConversionResult,
|
|
26
|
+
ConversionFailure,
|
|
27
|
+
ConversionResult,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.0"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"__version__",
|
|
34
|
+
"DEFAULT_BATCH_EXTENSIONS",
|
|
35
|
+
"DEFAULT_SUPPORTED_EXTENSIONS",
|
|
36
|
+
"DEFAULT_TIMEOUT_SECONDS",
|
|
37
|
+
"BatchConversionResult",
|
|
38
|
+
"ConversionError",
|
|
39
|
+
"ConversionFailure",
|
|
40
|
+
"ConversionResult",
|
|
41
|
+
"ConversionTimeoutError",
|
|
42
|
+
"Docx2PdfError",
|
|
43
|
+
"InvalidInputError",
|
|
44
|
+
"LibreOfficeNotFoundError",
|
|
45
|
+
"convert_bytes",
|
|
46
|
+
"convert_directory",
|
|
47
|
+
"convert_file",
|
|
48
|
+
"discover_documents",
|
|
49
|
+
"find_libreoffice",
|
|
50
|
+
"get_libreoffice_version",
|
|
51
|
+
"normalize_extensions",
|
|
52
|
+
]
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"""Core document discovery and PDF conversion API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import tempfile
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable, Iterable
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from docx2pdf_libre.exceptions import (
|
|
14
|
+
ConversionError,
|
|
15
|
+
ConversionTimeoutError,
|
|
16
|
+
InvalidInputError,
|
|
17
|
+
)
|
|
18
|
+
from docx2pdf_libre.libreoffice import (
|
|
19
|
+
DEFAULT_BATCH_EXTENSIONS,
|
|
20
|
+
DEFAULT_SUPPORTED_EXTENSIONS,
|
|
21
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
22
|
+
find_libreoffice,
|
|
23
|
+
run_libreoffice_pdf_conversion,
|
|
24
|
+
)
|
|
25
|
+
from docx2pdf_libre.models import BatchConversionResult, ConversionFailure, ConversionResult
|
|
26
|
+
|
|
27
|
+
PDF_MAGIC_HEADER = b"%PDF-"
|
|
28
|
+
ProgressCallback = Callable[[int, int, Path], None]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def normalize_extensions(extensions: Iterable[str]) -> tuple[str, ...]:
|
|
32
|
+
"""Normalize file extensions into lowercase dot-prefixed tuples."""
|
|
33
|
+
normalized: list[str] = []
|
|
34
|
+
seen: set[str] = set()
|
|
35
|
+
for raw_ext in extensions:
|
|
36
|
+
cleaned = raw_ext.strip().lower()
|
|
37
|
+
if not cleaned or cleaned == ".":
|
|
38
|
+
raise InvalidInputError(f"Invalid file extension: {raw_ext!r}.")
|
|
39
|
+
if not cleaned.startswith("."):
|
|
40
|
+
cleaned = f".{cleaned}"
|
|
41
|
+
if cleaned not in seen:
|
|
42
|
+
seen.add(cleaned)
|
|
43
|
+
normalized.append(cleaned)
|
|
44
|
+
if not normalized:
|
|
45
|
+
raise InvalidInputError("At least one file extension must be provided.")
|
|
46
|
+
return tuple(normalized)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _is_ignored_document_name(file_name: str) -> bool:
|
|
50
|
+
return file_name.startswith("~$") or file_name.endswith(":Zone.Identifier")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _is_within_any(path: Path, excluded_roots: tuple[Path, ...]) -> bool:
|
|
54
|
+
resolved = path.resolve()
|
|
55
|
+
for excluded in excluded_roots:
|
|
56
|
+
if resolved == excluded or excluded in resolved.parents:
|
|
57
|
+
return True
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def discover_documents(
|
|
62
|
+
source_dir: str | Path,
|
|
63
|
+
*,
|
|
64
|
+
extensions: Iterable[str] = DEFAULT_BATCH_EXTENSIONS,
|
|
65
|
+
recursive: bool = False,
|
|
66
|
+
exclude_dirs: Iterable[str | Path] | None = None,
|
|
67
|
+
) -> list[Path]:
|
|
68
|
+
"""Discover convertible documents in `source_dir`, ignoring lock files and ADS streams."""
|
|
69
|
+
root = Path(source_dir)
|
|
70
|
+
if not root.exists() or not root.is_dir():
|
|
71
|
+
raise InvalidInputError(f"Source directory does not exist or is not a directory: {root}")
|
|
72
|
+
|
|
73
|
+
allowed = set(normalize_extensions(extensions))
|
|
74
|
+
excluded_roots = tuple(Path(item).resolve() for item in (exclude_dirs or ()))
|
|
75
|
+
|
|
76
|
+
iterator = root.rglob("*") if recursive else root.iterdir()
|
|
77
|
+
discovered: list[Path] = []
|
|
78
|
+
for candidate in iterator:
|
|
79
|
+
if not candidate.is_file():
|
|
80
|
+
continue
|
|
81
|
+
if _is_ignored_document_name(candidate.name):
|
|
82
|
+
continue
|
|
83
|
+
if candidate.suffix.lower() not in allowed:
|
|
84
|
+
continue
|
|
85
|
+
if excluded_roots and _is_within_any(candidate.parent, excluded_roots):
|
|
86
|
+
continue
|
|
87
|
+
discovered.append(candidate)
|
|
88
|
+
|
|
89
|
+
return sorted(discovered, key=lambda item: item.as_posix())
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _resolve_output_pdf_path(source_path: Path, output: str | Path | None) -> Path:
|
|
93
|
+
if output is None:
|
|
94
|
+
return source_path.with_suffix(".pdf")
|
|
95
|
+
target = Path(output)
|
|
96
|
+
if target.exists() and target.is_dir():
|
|
97
|
+
return target / f"{source_path.stem}.pdf"
|
|
98
|
+
if not target.exists() and target.suffix == "":
|
|
99
|
+
return target / f"{source_path.stem}.pdf"
|
|
100
|
+
return target
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _verify_pdf_file(pdf_path: Path, source_path: Path, returncode: int, stderr: str) -> int:
|
|
104
|
+
if not pdf_path.exists():
|
|
105
|
+
raise ConversionError(
|
|
106
|
+
f"LibreOffice did not produce expected PDF for '{source_path.name}'.",
|
|
107
|
+
source=source_path,
|
|
108
|
+
returncode=returncode,
|
|
109
|
+
stderr=stderr,
|
|
110
|
+
)
|
|
111
|
+
size_bytes = pdf_path.stat().st_size
|
|
112
|
+
if size_bytes == 0:
|
|
113
|
+
raise ConversionError(
|
|
114
|
+
f"LibreOffice produced an empty PDF for '{source_path.name}'.",
|
|
115
|
+
source=source_path,
|
|
116
|
+
returncode=returncode,
|
|
117
|
+
stderr=stderr,
|
|
118
|
+
)
|
|
119
|
+
with pdf_path.open("rb") as handle:
|
|
120
|
+
header = handle.read(len(PDF_MAGIC_HEADER))
|
|
121
|
+
if header != PDF_MAGIC_HEADER:
|
|
122
|
+
raise ConversionError(
|
|
123
|
+
f"Generated file for '{source_path.name}' is not a valid PDF.",
|
|
124
|
+
source=source_path,
|
|
125
|
+
returncode=returncode,
|
|
126
|
+
stderr=stderr,
|
|
127
|
+
)
|
|
128
|
+
return size_bytes
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def convert_file(
|
|
132
|
+
source: str | Path,
|
|
133
|
+
output: str | Path | None = None,
|
|
134
|
+
*,
|
|
135
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
136
|
+
overwrite: bool = False,
|
|
137
|
+
libreoffice_path: str | Path | None = None,
|
|
138
|
+
allowed_extensions: Iterable[str] | None = DEFAULT_SUPPORTED_EXTENSIONS,
|
|
139
|
+
) -> ConversionResult:
|
|
140
|
+
"""Convert a single document file to PDF using headless LibreOffice."""
|
|
141
|
+
if timeout <= 0:
|
|
142
|
+
raise InvalidInputError("timeout must be greater than zero.")
|
|
143
|
+
|
|
144
|
+
source_path = Path(source)
|
|
145
|
+
if not source_path.exists() or not source_path.is_file():
|
|
146
|
+
raise InvalidInputError(f"Source file does not exist or is not a file: {source_path}")
|
|
147
|
+
|
|
148
|
+
if allowed_extensions is not None:
|
|
149
|
+
normalized_allowed = normalize_extensions(allowed_extensions)
|
|
150
|
+
if source_path.suffix.lower() not in normalized_allowed:
|
|
151
|
+
raise InvalidInputError(
|
|
152
|
+
f"Unsupported file extension '{source_path.suffix}' for '{source_path.name}'. "
|
|
153
|
+
f"Allowed extensions: {', '.join(normalized_allowed)}."
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
output_path = _resolve_output_pdf_path(source_path, output)
|
|
157
|
+
if output_path.exists() and not overwrite:
|
|
158
|
+
raise FileExistsError(
|
|
159
|
+
f"Destination PDF already exists: {output_path}. Pass overwrite=True to replace it."
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
executable = find_libreoffice(libreoffice_path)
|
|
163
|
+
started = time.perf_counter()
|
|
164
|
+
|
|
165
|
+
with tempfile.TemporaryDirectory(prefix="docx2pdf_libre_") as temp_dir_str:
|
|
166
|
+
temp_root = Path(temp_dir_str)
|
|
167
|
+
staging_dir = temp_root / "staging"
|
|
168
|
+
profile_dir = temp_root / "profile"
|
|
169
|
+
|
|
170
|
+
completed = run_libreoffice_pdf_conversion(
|
|
171
|
+
source_path=source_path.resolve(),
|
|
172
|
+
staging_output_dir=staging_dir,
|
|
173
|
+
profile_dir=profile_dir,
|
|
174
|
+
runtime_root=temp_root,
|
|
175
|
+
libreoffice_executable=executable,
|
|
176
|
+
timeout=timeout,
|
|
177
|
+
)
|
|
178
|
+
stderr_text = completed.stderr.strip()
|
|
179
|
+
if completed.returncode != 0:
|
|
180
|
+
raise ConversionError(
|
|
181
|
+
f"LibreOffice failed to convert '{source_path.name}' "
|
|
182
|
+
f"(exit code {completed.returncode}).",
|
|
183
|
+
source=source_path,
|
|
184
|
+
returncode=completed.returncode,
|
|
185
|
+
stderr=stderr_text,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
staged_pdf = staging_dir / f"{source_path.stem}.pdf"
|
|
189
|
+
size_bytes = _verify_pdf_file(staged_pdf, source_path, completed.returncode, stderr_text)
|
|
190
|
+
|
|
191
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
192
|
+
shutil.move(str(staged_pdf), str(output_path))
|
|
193
|
+
|
|
194
|
+
duration = time.perf_counter() - started
|
|
195
|
+
return ConversionResult(
|
|
196
|
+
source=source_path,
|
|
197
|
+
output=output_path,
|
|
198
|
+
duration_seconds=duration,
|
|
199
|
+
libreoffice_path=executable,
|
|
200
|
+
size_bytes=size_bytes,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def convert_bytes(
|
|
205
|
+
data: bytes,
|
|
206
|
+
*,
|
|
207
|
+
filename: str = "document.docx",
|
|
208
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
209
|
+
libreoffice_path: str | Path | None = None,
|
|
210
|
+
allowed_extensions: Iterable[str] | None = DEFAULT_SUPPORTED_EXTENSIONS,
|
|
211
|
+
) -> bytes:
|
|
212
|
+
"""Convert raw document bytes in memory and return the generated PDF bytes."""
|
|
213
|
+
if not data:
|
|
214
|
+
raise InvalidInputError("Input document bytes must not be empty.")
|
|
215
|
+
|
|
216
|
+
safe_name = Path(filename).name
|
|
217
|
+
if not safe_name or safe_name in {".", ".."} or safe_name != filename:
|
|
218
|
+
raise InvalidInputError(
|
|
219
|
+
f"filename must be a plain file name without directory components: {filename!r}"
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
with tempfile.TemporaryDirectory(prefix="docx2pdf_bytes_") as temp_dir_str:
|
|
223
|
+
temp_root = Path(temp_dir_str)
|
|
224
|
+
source_path = temp_root / safe_name
|
|
225
|
+
output_path = temp_root / f"{source_path.stem}.pdf"
|
|
226
|
+
source_path.write_bytes(data)
|
|
227
|
+
|
|
228
|
+
convert_file(
|
|
229
|
+
source_path,
|
|
230
|
+
output_path,
|
|
231
|
+
timeout=timeout,
|
|
232
|
+
overwrite=True,
|
|
233
|
+
libreoffice_path=libreoffice_path,
|
|
234
|
+
allowed_extensions=allowed_extensions,
|
|
235
|
+
)
|
|
236
|
+
return output_path.read_bytes()
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _resolve_batch_target(
|
|
240
|
+
document_path: Path,
|
|
241
|
+
source_root: Path,
|
|
242
|
+
output_root: Path,
|
|
243
|
+
*,
|
|
244
|
+
recursive: bool,
|
|
245
|
+
preserve_structure: bool,
|
|
246
|
+
) -> Path:
|
|
247
|
+
if recursive and preserve_structure:
|
|
248
|
+
relative_parent = document_path.parent.relative_to(source_root)
|
|
249
|
+
return output_root / relative_parent / f"{document_path.stem}.pdf"
|
|
250
|
+
return output_root / f"{document_path.stem}.pdf"
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _convert_batch_item(
|
|
254
|
+
document_path: Path,
|
|
255
|
+
target_pdf: Path,
|
|
256
|
+
*,
|
|
257
|
+
timeout: float,
|
|
258
|
+
overwrite: bool,
|
|
259
|
+
executable: Path,
|
|
260
|
+
normalized_extensions: tuple[str, ...],
|
|
261
|
+
) -> ConversionResult | ConversionFailure:
|
|
262
|
+
started = time.perf_counter()
|
|
263
|
+
try:
|
|
264
|
+
return convert_file(
|
|
265
|
+
document_path,
|
|
266
|
+
target_pdf,
|
|
267
|
+
timeout=timeout,
|
|
268
|
+
overwrite=overwrite,
|
|
269
|
+
libreoffice_path=executable,
|
|
270
|
+
allowed_extensions=normalized_extensions,
|
|
271
|
+
)
|
|
272
|
+
except ConversionTimeoutError as exc:
|
|
273
|
+
return ConversionFailure(
|
|
274
|
+
source=document_path,
|
|
275
|
+
error=str(exc),
|
|
276
|
+
returncode=None,
|
|
277
|
+
stderr="",
|
|
278
|
+
duration_seconds=time.perf_counter() - started,
|
|
279
|
+
)
|
|
280
|
+
except ConversionError as exc:
|
|
281
|
+
return ConversionFailure(
|
|
282
|
+
source=document_path,
|
|
283
|
+
error=str(exc),
|
|
284
|
+
returncode=exc.returncode,
|
|
285
|
+
stderr=exc.stderr,
|
|
286
|
+
duration_seconds=time.perf_counter() - started,
|
|
287
|
+
)
|
|
288
|
+
except FileExistsError as exc:
|
|
289
|
+
return ConversionFailure(
|
|
290
|
+
source=document_path,
|
|
291
|
+
error=str(exc),
|
|
292
|
+
returncode=None,
|
|
293
|
+
stderr="",
|
|
294
|
+
duration_seconds=time.perf_counter() - started,
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def convert_directory(
|
|
299
|
+
source_dir: str | Path,
|
|
300
|
+
output_dir: str | Path | None = None,
|
|
301
|
+
*,
|
|
302
|
+
outdir_name: str = "pdfs",
|
|
303
|
+
extensions: Iterable[str] = DEFAULT_BATCH_EXTENSIONS,
|
|
304
|
+
recursive: bool = False,
|
|
305
|
+
preserve_structure: bool = True,
|
|
306
|
+
overwrite: bool = False,
|
|
307
|
+
max_workers: int = 1,
|
|
308
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
309
|
+
fail_fast: bool = False,
|
|
310
|
+
libreoffice_path: str | Path | None = None,
|
|
311
|
+
on_progress: ProgressCallback | None = None,
|
|
312
|
+
) -> BatchConversionResult:
|
|
313
|
+
"""Convert all matching documents in `source_dir` into PDFs inside `output_dir`."""
|
|
314
|
+
if max_workers < 1:
|
|
315
|
+
raise InvalidInputError("max_workers must be at least 1.")
|
|
316
|
+
if timeout <= 0:
|
|
317
|
+
raise InvalidInputError("timeout must be greater than zero.")
|
|
318
|
+
|
|
319
|
+
source_root = Path(source_dir)
|
|
320
|
+
if not source_root.exists() or not source_root.is_dir():
|
|
321
|
+
raise InvalidInputError(
|
|
322
|
+
f"Source directory does not exist or is not a directory: {source_root}"
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
if output_dir is None:
|
|
326
|
+
cleaned_outdir_name = outdir_name.strip()
|
|
327
|
+
if not cleaned_outdir_name:
|
|
328
|
+
raise InvalidInputError("outdir_name must not be empty when output_dir is None.")
|
|
329
|
+
resolved_output_dir = source_root / cleaned_outdir_name
|
|
330
|
+
else:
|
|
331
|
+
resolved_output_dir = Path(output_dir)
|
|
332
|
+
|
|
333
|
+
normalized_extensions = normalize_extensions(extensions)
|
|
334
|
+
executable = find_libreoffice(libreoffice_path)
|
|
335
|
+
started = time.perf_counter()
|
|
336
|
+
|
|
337
|
+
documents = discover_documents(
|
|
338
|
+
source_root,
|
|
339
|
+
extensions=normalized_extensions,
|
|
340
|
+
recursive=recursive,
|
|
341
|
+
exclude_dirs=(resolved_output_dir,),
|
|
342
|
+
)
|
|
343
|
+
resolved_output_dir.mkdir(parents=True, exist_ok=True)
|
|
344
|
+
|
|
345
|
+
succeeded: list[ConversionResult] = []
|
|
346
|
+
failed: list[ConversionFailure] = []
|
|
347
|
+
total_documents = len(documents)
|
|
348
|
+
|
|
349
|
+
if max_workers == 1 or total_documents <= 1:
|
|
350
|
+
for index, doc_path in enumerate(documents, start=1):
|
|
351
|
+
target_pdf = _resolve_batch_target(
|
|
352
|
+
doc_path,
|
|
353
|
+
source_root,
|
|
354
|
+
resolved_output_dir,
|
|
355
|
+
recursive=recursive,
|
|
356
|
+
preserve_structure=preserve_structure,
|
|
357
|
+
)
|
|
358
|
+
outcome = _convert_batch_item(
|
|
359
|
+
doc_path,
|
|
360
|
+
target_pdf,
|
|
361
|
+
timeout=timeout,
|
|
362
|
+
overwrite=overwrite,
|
|
363
|
+
executable=executable,
|
|
364
|
+
normalized_extensions=normalized_extensions,
|
|
365
|
+
)
|
|
366
|
+
if isinstance(outcome, ConversionResult):
|
|
367
|
+
succeeded.append(outcome)
|
|
368
|
+
else:
|
|
369
|
+
if fail_fast:
|
|
370
|
+
raise ConversionError(
|
|
371
|
+
outcome.error,
|
|
372
|
+
source=outcome.source,
|
|
373
|
+
returncode=outcome.returncode,
|
|
374
|
+
stderr=outcome.stderr,
|
|
375
|
+
)
|
|
376
|
+
failed.append(outcome)
|
|
377
|
+
if on_progress is not None:
|
|
378
|
+
on_progress(index, total_documents, doc_path)
|
|
379
|
+
else:
|
|
380
|
+
progress_lock = threading.Lock()
|
|
381
|
+
completed_count = 0
|
|
382
|
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
383
|
+
future_map = {
|
|
384
|
+
executor.submit(
|
|
385
|
+
_convert_batch_item,
|
|
386
|
+
doc_path,
|
|
387
|
+
_resolve_batch_target(
|
|
388
|
+
doc_path,
|
|
389
|
+
source_root,
|
|
390
|
+
resolved_output_dir,
|
|
391
|
+
recursive=recursive,
|
|
392
|
+
preserve_structure=preserve_structure,
|
|
393
|
+
),
|
|
394
|
+
timeout=timeout,
|
|
395
|
+
overwrite=overwrite,
|
|
396
|
+
executable=executable,
|
|
397
|
+
normalized_extensions=normalized_extensions,
|
|
398
|
+
): doc_path
|
|
399
|
+
for doc_path in documents
|
|
400
|
+
}
|
|
401
|
+
for future in as_completed(future_map):
|
|
402
|
+
doc_path = future_map[future]
|
|
403
|
+
outcome = future.result()
|
|
404
|
+
if isinstance(outcome, ConversionResult):
|
|
405
|
+
succeeded.append(outcome)
|
|
406
|
+
else:
|
|
407
|
+
if fail_fast:
|
|
408
|
+
for pending in future_map:
|
|
409
|
+
pending.cancel()
|
|
410
|
+
raise ConversionError(
|
|
411
|
+
outcome.error,
|
|
412
|
+
source=outcome.source,
|
|
413
|
+
returncode=outcome.returncode,
|
|
414
|
+
stderr=outcome.stderr,
|
|
415
|
+
)
|
|
416
|
+
failed.append(outcome)
|
|
417
|
+
if on_progress is not None:
|
|
418
|
+
with progress_lock:
|
|
419
|
+
completed_count += 1
|
|
420
|
+
on_progress(completed_count, total_documents, doc_path)
|
|
421
|
+
|
|
422
|
+
succeeded.sort(key=lambda item: item.source.as_posix())
|
|
423
|
+
failed.sort(key=lambda item: item.source.as_posix())
|
|
424
|
+
|
|
425
|
+
return BatchConversionResult(
|
|
426
|
+
source_dir=source_root,
|
|
427
|
+
output_dir=resolved_output_dir,
|
|
428
|
+
succeeded=tuple(succeeded),
|
|
429
|
+
failed=tuple(failed),
|
|
430
|
+
duration_seconds=time.perf_counter() - started,
|
|
431
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Domain exception hierarchy for docx2pdf-libre."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Docx2PdfError(Exception):
|
|
9
|
+
"""Base exception for all docx2pdf-libre errors."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LibreOfficeNotFoundError(Docx2PdfError, FileNotFoundError):
|
|
13
|
+
"""Raised when the LibreOffice executable cannot be located or executed."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InvalidInputError(Docx2PdfError, ValueError):
|
|
17
|
+
"""Raised when input files, directories, bytes, or conversion options are invalid."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ConversionTimeoutError(Docx2PdfError, TimeoutError):
|
|
21
|
+
"""Raised when a LibreOffice conversion exceeds the configured timeout."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
message: str,
|
|
26
|
+
*,
|
|
27
|
+
source: Path | None = None,
|
|
28
|
+
timeout: float | None = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
super().__init__(message)
|
|
31
|
+
self.source = source
|
|
32
|
+
self.timeout = timeout
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ConversionError(Docx2PdfError):
|
|
36
|
+
"""Raised when LibreOffice fails to convert a document into a valid PDF."""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
message: str,
|
|
41
|
+
*,
|
|
42
|
+
source: Path | None = None,
|
|
43
|
+
returncode: int | None = None,
|
|
44
|
+
stderr: str = "",
|
|
45
|
+
) -> None:
|
|
46
|
+
super().__init__(message)
|
|
47
|
+
self.source = source
|
|
48
|
+
self.returncode = returncode
|
|
49
|
+
self.stderr = stderr
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""LibreOffice executable discovery and isolated headless subprocess execution."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
|
|
8
|
+
# Invokes a validated LibreOffice executable with list arguments and shell=False.
|
|
9
|
+
import subprocess # nosec B404
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from docx2pdf_libre.exceptions import (
|
|
14
|
+
ConversionError,
|
|
15
|
+
ConversionTimeoutError,
|
|
16
|
+
InvalidInputError,
|
|
17
|
+
LibreOfficeNotFoundError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
DEFAULT_SUPPORTED_EXTENSIONS: tuple[str, ...] = (".docx", ".doc", ".odt", ".rtf")
|
|
21
|
+
DEFAULT_BATCH_EXTENSIONS: tuple[str, ...] = (".docx",)
|
|
22
|
+
DEFAULT_TIMEOUT_SECONDS: float = 120.0
|
|
23
|
+
LIBREOFFICE_ENV_VAR = "LIBREOFFICE_PATH"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _validate_executable(candidate: Path, origin: str) -> Path:
|
|
27
|
+
resolved = candidate.expanduser()
|
|
28
|
+
if not resolved.exists() or not resolved.is_file():
|
|
29
|
+
raise LibreOfficeNotFoundError(
|
|
30
|
+
f"LibreOffice executable not found at {resolved} (from {origin})."
|
|
31
|
+
)
|
|
32
|
+
if not os.access(resolved, os.X_OK):
|
|
33
|
+
raise LibreOfficeNotFoundError(
|
|
34
|
+
f"LibreOffice path is not executable: {resolved} (from {origin})."
|
|
35
|
+
)
|
|
36
|
+
return resolved.resolve()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _platform_fallback_candidates() -> tuple[Path, ...]:
|
|
40
|
+
if sys.platform == "darwin":
|
|
41
|
+
return (Path("/Applications/LibreOffice.app/Contents/MacOS/soffice"),)
|
|
42
|
+
if sys.platform == "win32":
|
|
43
|
+
return (
|
|
44
|
+
Path(r"C:\Program Files\LibreOffice\program\soffice.exe"),
|
|
45
|
+
Path(r"C:\Program Files (x86)\LibreOffice\program\soffice.exe"),
|
|
46
|
+
)
|
|
47
|
+
return ()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def find_libreoffice(explicit_path: str | Path | None = None) -> Path:
|
|
51
|
+
"""Locate a usable LibreOffice executable (`soffice` or `libreoffice`).
|
|
52
|
+
|
|
53
|
+
Resolution order:
|
|
54
|
+
1. `explicit_path` argument, if provided.
|
|
55
|
+
2. `LIBREOFFICE_PATH` environment variable, if set.
|
|
56
|
+
3. `soffice` and `libreoffice` on `PATH`.
|
|
57
|
+
4. Standard platform installation locations on macOS/Windows.
|
|
58
|
+
"""
|
|
59
|
+
if explicit_path is not None:
|
|
60
|
+
return _validate_executable(Path(explicit_path), "explicit libreoffice_path")
|
|
61
|
+
|
|
62
|
+
env_override = os.environ.get(LIBREOFFICE_ENV_VAR)
|
|
63
|
+
if env_override:
|
|
64
|
+
return _validate_executable(Path(env_override), LIBREOFFICE_ENV_VAR)
|
|
65
|
+
|
|
66
|
+
for command_name in ("soffice", "libreoffice"):
|
|
67
|
+
found = shutil.which(command_name)
|
|
68
|
+
if found:
|
|
69
|
+
return Path(found).resolve()
|
|
70
|
+
|
|
71
|
+
for fallback in _platform_fallback_candidates():
|
|
72
|
+
if fallback.is_file() and os.access(fallback, os.X_OK):
|
|
73
|
+
return fallback.resolve()
|
|
74
|
+
|
|
75
|
+
raise LibreOfficeNotFoundError(
|
|
76
|
+
"LibreOffice executable ('soffice' or 'libreoffice') was not found. "
|
|
77
|
+
"Install LibreOffice (e.g., `sudo apt install libreoffice` or "
|
|
78
|
+
"`brew install --cask libreoffice`) "
|
|
79
|
+
f"or pass `libreoffice_path` / set {LIBREOFFICE_ENV_VAR}."
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def build_headless_env(runtime_root: Path) -> dict[str, str]:
|
|
84
|
+
"""Build a subprocess environment with a writable XDG_RUNTIME_DIR when needed."""
|
|
85
|
+
env = dict(os.environ)
|
|
86
|
+
if os.name == "posix":
|
|
87
|
+
xdg_runtime = env.get("XDG_RUNTIME_DIR")
|
|
88
|
+
xdg_path = Path(xdg_runtime) if xdg_runtime else None
|
|
89
|
+
if xdg_path is None or not xdg_path.is_dir() or not os.access(xdg_path, os.W_OK):
|
|
90
|
+
fallback_runtime = runtime_root / "xdg-runtime"
|
|
91
|
+
fallback_runtime.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
92
|
+
env["XDG_RUNTIME_DIR"] = str(fallback_runtime)
|
|
93
|
+
return env
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def get_libreoffice_version(
|
|
97
|
+
libreoffice_path: str | Path | None = None,
|
|
98
|
+
*,
|
|
99
|
+
timeout: float = 15.0,
|
|
100
|
+
) -> str:
|
|
101
|
+
"""Return the version banner reported by LibreOffice (`soffice --version`)."""
|
|
102
|
+
if timeout <= 0:
|
|
103
|
+
raise InvalidInputError("timeout must be greater than zero.")
|
|
104
|
+
|
|
105
|
+
executable = find_libreoffice(libreoffice_path)
|
|
106
|
+
command = [str(executable), "--version"]
|
|
107
|
+
try:
|
|
108
|
+
# Executable path is validated and shell=False is enforced.
|
|
109
|
+
completed = subprocess.run( # nosec B603
|
|
110
|
+
command,
|
|
111
|
+
capture_output=True,
|
|
112
|
+
text=True,
|
|
113
|
+
timeout=timeout,
|
|
114
|
+
check=False,
|
|
115
|
+
)
|
|
116
|
+
except subprocess.TimeoutExpired as exc:
|
|
117
|
+
raise ConversionTimeoutError(
|
|
118
|
+
f"LibreOffice version check timed out after {timeout:.1f}s.",
|
|
119
|
+
timeout=timeout,
|
|
120
|
+
) from exc
|
|
121
|
+
|
|
122
|
+
output_text = (completed.stdout or completed.stderr).strip()
|
|
123
|
+
if completed.returncode != 0 or not output_text:
|
|
124
|
+
raise ConversionError(
|
|
125
|
+
f"Failed to query LibreOffice version (exit code {completed.returncode}).",
|
|
126
|
+
returncode=completed.returncode,
|
|
127
|
+
stderr=completed.stderr.strip(),
|
|
128
|
+
)
|
|
129
|
+
return output_text.splitlines()[0].strip()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def run_libreoffice_pdf_conversion(
|
|
133
|
+
*,
|
|
134
|
+
source_path: Path,
|
|
135
|
+
staging_output_dir: Path,
|
|
136
|
+
profile_dir: Path,
|
|
137
|
+
runtime_root: Path,
|
|
138
|
+
libreoffice_executable: Path,
|
|
139
|
+
timeout: float,
|
|
140
|
+
) -> subprocess.CompletedProcess[str]:
|
|
141
|
+
"""Run LibreOffice headless PDF conversion with an isolated user profile."""
|
|
142
|
+
profile_dir.mkdir(parents=True, exist_ok=True)
|
|
143
|
+
staging_output_dir.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
command = [
|
|
145
|
+
str(libreoffice_executable),
|
|
146
|
+
"--headless",
|
|
147
|
+
"--nologo",
|
|
148
|
+
"--nodefault",
|
|
149
|
+
"--nofirststartwizard",
|
|
150
|
+
"--norestore",
|
|
151
|
+
f"-env:UserInstallation={profile_dir.resolve().as_uri()}",
|
|
152
|
+
"--convert-to",
|
|
153
|
+
"pdf",
|
|
154
|
+
"--outdir",
|
|
155
|
+
str(staging_output_dir),
|
|
156
|
+
str(source_path),
|
|
157
|
+
]
|
|
158
|
+
env = build_headless_env(runtime_root)
|
|
159
|
+
try:
|
|
160
|
+
# Executable path is validated and shell=False is enforced.
|
|
161
|
+
return subprocess.run( # nosec B603
|
|
162
|
+
command,
|
|
163
|
+
capture_output=True,
|
|
164
|
+
text=True,
|
|
165
|
+
timeout=timeout,
|
|
166
|
+
env=env,
|
|
167
|
+
check=False,
|
|
168
|
+
)
|
|
169
|
+
except subprocess.TimeoutExpired as exc:
|
|
170
|
+
raise ConversionTimeoutError(
|
|
171
|
+
f"Conversion of '{source_path.name}' timed out after {timeout:.1f}s.",
|
|
172
|
+
source=source_path,
|
|
173
|
+
timeout=timeout,
|
|
174
|
+
) from exc
|
docx2pdf_libre/models.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Immutable result data models for docx2pdf-libre."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class ConversionResult:
|
|
11
|
+
"""Outcome of a successful single-document conversion."""
|
|
12
|
+
|
|
13
|
+
source: Path
|
|
14
|
+
output: Path
|
|
15
|
+
duration_seconds: float
|
|
16
|
+
libreoffice_path: Path
|
|
17
|
+
size_bytes: int
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class ConversionFailure:
|
|
22
|
+
"""Diagnostic record for a failed conversion inside a batch."""
|
|
23
|
+
|
|
24
|
+
source: Path
|
|
25
|
+
error: str
|
|
26
|
+
returncode: int | None = None
|
|
27
|
+
stderr: str = ""
|
|
28
|
+
duration_seconds: float = 0.0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class BatchConversionResult:
|
|
33
|
+
"""Aggregated outcome of a directory batch conversion."""
|
|
34
|
+
|
|
35
|
+
source_dir: Path
|
|
36
|
+
output_dir: Path
|
|
37
|
+
succeeded: tuple[ConversionResult, ...]
|
|
38
|
+
failed: tuple[ConversionFailure, ...]
|
|
39
|
+
duration_seconds: float
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def total(self) -> int:
|
|
43
|
+
"""Total number of documents processed."""
|
|
44
|
+
return len(self.succeeded) + len(self.failed)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def succeeded_count(self) -> int:
|
|
48
|
+
"""Number of documents converted successfully."""
|
|
49
|
+
return len(self.succeeded)
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def failed_count(self) -> int:
|
|
53
|
+
"""Number of documents that failed conversion."""
|
|
54
|
+
return len(self.failed)
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def ok(self) -> bool:
|
|
58
|
+
"""Return True when every processed document succeeded."""
|
|
59
|
+
return len(self.failed) == 0
|
docx2pdf_libre/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: docx2pdf-libre
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-dependency Python library for converting DOCX and Office documents to PDF via headless LibreOffice.
|
|
5
|
+
Author-email: Clayton Fraga <claytonfraga@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/claytonfraga/docx2pdf-libre
|
|
8
|
+
Project-URL: Repository, https://github.com/claytonfraga/docx2pdf-libre
|
|
9
|
+
Project-URL: Issues, https://github.com/claytonfraga/docx2pdf-libre/issues
|
|
10
|
+
Keywords: docx,pdf,docx2pdf,libreoffice,soffice,document-conversion,headless
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Office/Business
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# docx2pdf-libre
|
|
28
|
+
|
|
29
|
+
Zero-dependency Python library for converting `.docx` (and `.doc`, `.odt`, `.rtf`) documents to PDF using headless LibreOffice — safe for parallel workloads, web backends, CI, Docker, and WSL.
|
|
30
|
+
|
|
31
|
+
> **Package scope note:** The package published to PyPI (`docx2pdf-libre`) is a **pure Python library** with **zero external runtime dependencies** and no CLI entry points. A repository-local CLI (`cli/docx2pdf_cli.py`) is also maintained in this repo for interactive terminal workflows and is intentionally excluded from the PyPI distribution.
|
|
32
|
+
|
|
33
|
+
## Features
|
|
34
|
+
|
|
35
|
+
- **Zero external Python dependencies:** Uses only the Python 3.11+ standard library and the system LibreOffice executable (`soffice` / `libreoffice`).
|
|
36
|
+
- **Concurrency-safe by design:** Every conversion runs in an isolated temporary LibreOffice user profile (`-env:UserInstallation=file://...`), preventing profile lock collisions during parallel batch jobs or web requests.
|
|
37
|
+
- **Headless & WSL friendly:** Automatically supplies a private writable `XDG_RUNTIME_DIR` fallback when the host environment lacks one, while keeping `HOME` intact so user-installed fonts remain available.
|
|
38
|
+
- **Flexible inputs:** Convert a single file (`convert_file`), raw in-memory bytes (`convert_bytes`), or an entire directory tree (`convert_directory` with optional recursion, structure preservation, multi-extension filtering, and parallel workers).
|
|
39
|
+
- **Explicit typed contracts:** Ships PEP 561 `py.typed` annotations, frozen dataclasses (`ConversionResult`, `ConversionFailure`, `BatchConversionResult`), PDF header verification (`%PDF-`), configurable timeouts, and a dedicated exception hierarchy.
|
|
40
|
+
|
|
41
|
+
## Prerequisites
|
|
42
|
+
|
|
43
|
+
- **Python 3.11+**
|
|
44
|
+
- **LibreOffice** installed and available via `soffice` or `libreoffice` (or explicitly configured via `libreoffice_path` / `LIBREOFFICE_PATH`):
|
|
45
|
+
- Ubuntu / Debian: `sudo apt install libreoffice` (or `libreoffice-writer` for a smaller headless footprint)
|
|
46
|
+
- macOS: `brew install --cask libreoffice`
|
|
47
|
+
- Windows: install LibreOffice from [libreoffice.org](https://www.libreoffice.org/)
|
|
48
|
+
- **Fonts:** Install the same fonts used inside your source documents on the host machine to avoid font substitution or reflow.
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## Using the Python Library (PyPI)
|
|
53
|
+
|
|
54
|
+
### Installation
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install docx2pdf-libre
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Or with `uv`:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
uv add docx2pdf-libre
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Convert a Single File
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from docx2pdf_libre import convert_file
|
|
70
|
+
|
|
71
|
+
# Writes report.pdf beside report.docx
|
|
72
|
+
result = convert_file("documents/report.docx")
|
|
73
|
+
print(result.output, result.size_bytes, f"{result.duration_seconds:.2f}s")
|
|
74
|
+
|
|
75
|
+
# Write to a specific output file or directory
|
|
76
|
+
result = convert_file(
|
|
77
|
+
"documents/report.docx",
|
|
78
|
+
output="exports/final-report.pdf",
|
|
79
|
+
overwrite=True,
|
|
80
|
+
timeout=60.0,
|
|
81
|
+
)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Convert Raw Bytes in Memory
|
|
85
|
+
|
|
86
|
+
Ideal for APIs, background workers, and cloud storage pipelines where you do not want to manage temporary files manually:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from pathlib import Path
|
|
90
|
+
from docx2pdf_libre import convert_bytes
|
|
91
|
+
|
|
92
|
+
docx_data = Path("documents/invoice.docx").read_bytes()
|
|
93
|
+
pdf_bytes = convert_bytes(docx_data, filename="invoice.docx", timeout=60.0)
|
|
94
|
+
Path("exports/invoice.pdf").write_bytes(pdf_bytes)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Convert a Directory (Batch, Recursive & Parallel)
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from docx2pdf_libre import convert_directory
|
|
101
|
+
|
|
102
|
+
batch = convert_directory(
|
|
103
|
+
"documents/",
|
|
104
|
+
output_dir="exports/pdfs", # Defaults to documents/pdfs when omitted
|
|
105
|
+
extensions=(".docx", ".rtf"), # Defaults to (".docx",)
|
|
106
|
+
recursive=True,
|
|
107
|
+
preserve_structure=True,
|
|
108
|
+
max_workers=4,
|
|
109
|
+
overwrite=True,
|
|
110
|
+
timeout=120.0,
|
|
111
|
+
on_progress=lambda done, total, path: print(f"[{done}/{total}] {path.name}"),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
print(f"Converted {batch.succeeded_count}/{batch.total} files in {batch.duration_seconds:.2f}s")
|
|
115
|
+
if not batch.ok:
|
|
116
|
+
for failure in batch.failed:
|
|
117
|
+
print(f"FAILED {failure.source}: {failure.error}")
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Office temporary lock files (`~$*.docx`), Windows alternate data streams (`*:Zone.Identifier`), and the target output directory itself are automatically excluded during discovery.
|
|
121
|
+
|
|
122
|
+
### Inspect LibreOffice Availability
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from docx2pdf_libre import find_libreoffice, get_libreoffice_version
|
|
126
|
+
|
|
127
|
+
executable = find_libreoffice()
|
|
128
|
+
version = get_libreoffice_version()
|
|
129
|
+
print(executable, "->", version)
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Public API Overview
|
|
133
|
+
|
|
134
|
+
| Symbol | Purpose |
|
|
135
|
+
| --- | --- |
|
|
136
|
+
| `convert_file(source, output=None, *, timeout=120.0, overwrite=False, libreoffice_path=None, allowed_extensions=...)` | Converts one file to PDF and returns `ConversionResult`. |
|
|
137
|
+
| `convert_bytes(data, *, filename="document.docx", timeout=120.0, libreoffice_path=None, allowed_extensions=...)` | Converts document bytes in memory and returns PDF `bytes`. |
|
|
138
|
+
| `convert_directory(source_dir, output_dir=None, *, outdir_name="pdfs", extensions=(".docx",), recursive=False, preserve_structure=True, overwrite=False, max_workers=1, timeout=120.0, fail_fast=False, libreoffice_path=None, on_progress=None)` | Converts matching files in a folder and returns `BatchConversionResult`. |
|
|
139
|
+
| `discover_documents(source_dir, *, extensions=(".docx",), recursive=False, exclude_dirs=None)` | Lists eligible documents ignoring lock files, `:Zone.Identifier`, and excluded folders. |
|
|
140
|
+
| `find_libreoffice(explicit_path=None)` | Resolves the `soffice` / `libreoffice` executable path (supports `LIBREOFFICE_PATH`). |
|
|
141
|
+
| `get_libreoffice_version(libreoffice_path=None, *, timeout=15.0)` | Queries `soffice --version`. |
|
|
142
|
+
|
|
143
|
+
### Error Handling
|
|
144
|
+
|
|
145
|
+
All library exceptions inherit from `Docx2PdfError`:
|
|
146
|
+
|
|
147
|
+
- `LibreOfficeNotFoundError` *(also `FileNotFoundError`)* — LibreOffice binary is missing or not executable.
|
|
148
|
+
- `InvalidInputError` *(also `ValueError`)* — missing input file/folder, unsupported extension, empty bytes, or invalid options (`timeout <= 0`, `max_workers < 1`).
|
|
149
|
+
- `ConversionTimeoutError` *(also `TimeoutError`)* — LibreOffice exceeded `timeout`.
|
|
150
|
+
- `ConversionError` — LibreOffice exited non-zero or failed to generate a valid `%PDF-` file (exposes `.source`, `.returncode`, `.stderr`).
|
|
151
|
+
- `FileExistsError` — destination PDF already exists and `overwrite=False`.
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from docx2pdf_libre import ConversionError, LibreOfficeNotFoundError, convert_file
|
|
155
|
+
|
|
156
|
+
try:
|
|
157
|
+
convert_file("contract.docx")
|
|
158
|
+
except LibreOfficeNotFoundError as exc:
|
|
159
|
+
print("Install LibreOffice first:", exc)
|
|
160
|
+
except ConversionError as exc:
|
|
161
|
+
print(f"Conversion failed (code={exc.returncode}): {exc.stderr}")
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Using the Local CLI (Repository Only)
|
|
167
|
+
|
|
168
|
+
> **Important:** The CLI (`cli/docx2pdf_cli.py`) is **not included in the PyPI package** to keep `docx2pdf-libre` dependency-free (`typer` and `rich` are only used locally). Clone the repository to use the CLI.
|
|
169
|
+
|
|
170
|
+
### Local Setup
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
python3 -m venv .venv
|
|
174
|
+
source .venv/bin/activate
|
|
175
|
+
pip install -r requirements.txt
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### CLI Commands
|
|
179
|
+
|
|
180
|
+
Convert all `.docx` files in a folder (outputs to `<folder>/pdfs` by default):
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
python cli/docx2pdf_cli.py path/to/folder
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Convert a single file:
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
python cli/docx2pdf_cli.py path/to/document.docx
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Use custom output folder, recursion, multiple extensions, parallel workers, and overwrite:
|
|
193
|
+
|
|
194
|
+
```bash
|
|
195
|
+
python cli/docx2pdf_cli.py path/to/folder \
|
|
196
|
+
--outdir-name output_pdf \
|
|
197
|
+
--recursive \
|
|
198
|
+
--extensions .docx,.doc,.odt,.rtf \
|
|
199
|
+
--workers 4 \
|
|
200
|
+
--timeout 90 \
|
|
201
|
+
--overwrite
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Show all CLI options:
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
python cli/docx2pdf_cli.py --help
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
---
|
|
211
|
+
|
|
212
|
+
## Layout Fidelity & Headless Troubleshooting
|
|
213
|
+
|
|
214
|
+
- **Fonts:** LibreOffice renders using the fonts installed on the OS. Missing fonts cause fallback substitutions and pagination drift.
|
|
215
|
+
- **Headless / WSL / Containers:** `docx2pdf-libre` automatically creates an isolated LibreOffice user profile per conversion and a writable `XDG_RUNTIME_DIR` fallback when needed, avoiding common `dconf` or profile-lock failures.
|
|
216
|
+
- **Custom LibreOffice binary:** Pass `libreoffice_path="/path/to/soffice"` or set the `LIBREOFFICE_PATH` environment variable.
|
|
217
|
+
|
|
218
|
+
## Development & Quality Gate
|
|
219
|
+
|
|
220
|
+
This project follows **GitHub Spec Kit** (`.specify/` and `specs/`). Run the full local quality gate (linting, formatting, strict typing, security scan, dependency audit, real LibreOffice test suite with >=90% line and branch coverage, wheel/sdist packaging audit, and clean-venv smoke test):
|
|
221
|
+
|
|
222
|
+
```bash
|
|
223
|
+
python3 -m venv .venv
|
|
224
|
+
source .venv/bin/activate
|
|
225
|
+
pip install -e . --group dev
|
|
226
|
+
python scripts/verify_quality.py
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## License
|
|
230
|
+
|
|
231
|
+
Apache-2.0 — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
docx2pdf_libre/__init__.py,sha256=w-_0Y7rBY0qGVkajoL6P0Fa3yejhF2k8ql1bTEZ97PE,1245
|
|
2
|
+
docx2pdf_libre/converter.py,sha256=j8gEXCDFIxguVwjuc9LFyVm5qb9OZgKe12xl7AfZyg4,15286
|
|
3
|
+
docx2pdf_libre/exceptions.py,sha256=w80n0ziMO6ciFPP6dT9eYVEJ-N3O_Gd5uH-WH532fhM,1317
|
|
4
|
+
docx2pdf_libre/libreoffice.py,sha256=es_jIf6VsVTJVE34uH62IHDwgiQZlzkXWkUjQZ8baTo,6057
|
|
5
|
+
docx2pdf_libre/models.py,sha256=UJhpNTeGdwbRYCbxUIqXCgVm-UtbjCx_fmbXrPmM5-M,1503
|
|
6
|
+
docx2pdf_libre/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
docx2pdf_libre-0.1.0.dist-info/licenses/LICENSE,sha256=BzNc-eYIB3Z-67FipI6GvyLpYXJgkNQC3uGZQTd0VGI,10685
|
|
8
|
+
docx2pdf_libre-0.1.0.dist-info/METADATA,sha256=bM9e8JFCeQigfMEu0MBShlnusn9w1x5lOnPfoMDi9H0,9644
|
|
9
|
+
docx2pdf_libre-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
docx2pdf_libre-0.1.0.dist-info/top_level.txt,sha256=l3gUHk9rvOpj9Mn_dnk5Nr3lRLvkNLlIIpIb2P0qYrI,15
|
|
11
|
+
docx2pdf_libre-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within the display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE file from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the contents of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including but not limited to the warranties of
|
|
148
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
|
|
149
|
+
NON-INFRINGEMENT. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may establish a separate
|
|
167
|
+
warranty, support, or additional liability obligations and/or rights
|
|
168
|
+
consistent with this License. However, in accepting such obligations,
|
|
169
|
+
You may act only on Your own behalf and on Your sole responsibility,
|
|
170
|
+
not on behalf of any other Contributor, and only if You agree to
|
|
171
|
+
indemnify, defend, and hold each Contributor harmless for any liability
|
|
172
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
173
|
+
of your accepting any such warranty or additional liability.
|
|
174
|
+
|
|
175
|
+
END OF TERMS AND CONDITIONS
|
|
176
|
+
|
|
177
|
+
Copyright 2026 Clayton Fraga
|
|
178
|
+
|
|
179
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
180
|
+
you may not use this file except in compliance with the License.
|
|
181
|
+
You may obtain a copy of the License at
|
|
182
|
+
|
|
183
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
184
|
+
|
|
185
|
+
Unless required by applicable law or agreed to in writing, software
|
|
186
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
187
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
188
|
+
See the License for the specific language governing permissions and
|
|
189
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
docx2pdf_libre
|