docx2pdf-libre 0.1.0__tar.gz
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-0.1.0/LICENSE +189 -0
- docx2pdf_libre-0.1.0/MANIFEST.in +17 -0
- docx2pdf_libre-0.1.0/PKG-INFO +231 -0
- docx2pdf_libre-0.1.0/README.md +205 -0
- docx2pdf_libre-0.1.0/pyproject.toml +99 -0
- docx2pdf_libre-0.1.0/setup.cfg +4 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre/__init__.py +52 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre/converter.py +431 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre/exceptions.py +49 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre/libreoffice.py +174 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre/models.py +59 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre/py.typed +0 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre.egg-info/PKG-INFO +231 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre.egg-info/SOURCES.txt +14 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre.egg-info/dependency_links.txt +1 -0
- docx2pdf_libre-0.1.0/src/docx2pdf_libre.egg-info/top_level.txt +1 -0
|
@@ -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,17 @@
|
|
|
1
|
+
include pyproject.toml
|
|
2
|
+
include README.md
|
|
3
|
+
include LICENSE
|
|
4
|
+
recursive-include src/docx2pdf_libre *.py
|
|
5
|
+
include src/docx2pdf_libre/py.typed
|
|
6
|
+
|
|
7
|
+
prune cli
|
|
8
|
+
prune tests
|
|
9
|
+
prune scripts
|
|
10
|
+
prune specs
|
|
11
|
+
prune .specify
|
|
12
|
+
prune .github
|
|
13
|
+
prune .quality
|
|
14
|
+
prune 0_Certificados_2026-2
|
|
15
|
+
exclude .gitignore
|
|
16
|
+
exclude requirements.txt
|
|
17
|
+
global-exclude __pycache__ *.py[cod] *.docx *.pdf
|
|
@@ -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,205 @@
|
|
|
1
|
+
# docx2pdf-libre
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
> **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.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Zero external Python dependencies:** Uses only the Python 3.11+ standard library and the system LibreOffice executable (`soffice` / `libreoffice`).
|
|
10
|
+
- **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.
|
|
11
|
+
- **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.
|
|
12
|
+
- **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).
|
|
13
|
+
- **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.
|
|
14
|
+
|
|
15
|
+
## Prerequisites
|
|
16
|
+
|
|
17
|
+
- **Python 3.11+**
|
|
18
|
+
- **LibreOffice** installed and available via `soffice` or `libreoffice` (or explicitly configured via `libreoffice_path` / `LIBREOFFICE_PATH`):
|
|
19
|
+
- Ubuntu / Debian: `sudo apt install libreoffice` (or `libreoffice-writer` for a smaller headless footprint)
|
|
20
|
+
- macOS: `brew install --cask libreoffice`
|
|
21
|
+
- Windows: install LibreOffice from [libreoffice.org](https://www.libreoffice.org/)
|
|
22
|
+
- **Fonts:** Install the same fonts used inside your source documents on the host machine to avoid font substitution or reflow.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Using the Python Library (PyPI)
|
|
27
|
+
|
|
28
|
+
### Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install docx2pdf-libre
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Or with `uv`:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
uv add docx2pdf-libre
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Convert a Single File
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from docx2pdf_libre import convert_file
|
|
44
|
+
|
|
45
|
+
# Writes report.pdf beside report.docx
|
|
46
|
+
result = convert_file("documents/report.docx")
|
|
47
|
+
print(result.output, result.size_bytes, f"{result.duration_seconds:.2f}s")
|
|
48
|
+
|
|
49
|
+
# Write to a specific output file or directory
|
|
50
|
+
result = convert_file(
|
|
51
|
+
"documents/report.docx",
|
|
52
|
+
output="exports/final-report.pdf",
|
|
53
|
+
overwrite=True,
|
|
54
|
+
timeout=60.0,
|
|
55
|
+
)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Convert Raw Bytes in Memory
|
|
59
|
+
|
|
60
|
+
Ideal for APIs, background workers, and cloud storage pipelines where you do not want to manage temporary files manually:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from pathlib import Path
|
|
64
|
+
from docx2pdf_libre import convert_bytes
|
|
65
|
+
|
|
66
|
+
docx_data = Path("documents/invoice.docx").read_bytes()
|
|
67
|
+
pdf_bytes = convert_bytes(docx_data, filename="invoice.docx", timeout=60.0)
|
|
68
|
+
Path("exports/invoice.pdf").write_bytes(pdf_bytes)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Convert a Directory (Batch, Recursive & Parallel)
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from docx2pdf_libre import convert_directory
|
|
75
|
+
|
|
76
|
+
batch = convert_directory(
|
|
77
|
+
"documents/",
|
|
78
|
+
output_dir="exports/pdfs", # Defaults to documents/pdfs when omitted
|
|
79
|
+
extensions=(".docx", ".rtf"), # Defaults to (".docx",)
|
|
80
|
+
recursive=True,
|
|
81
|
+
preserve_structure=True,
|
|
82
|
+
max_workers=4,
|
|
83
|
+
overwrite=True,
|
|
84
|
+
timeout=120.0,
|
|
85
|
+
on_progress=lambda done, total, path: print(f"[{done}/{total}] {path.name}"),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
print(f"Converted {batch.succeeded_count}/{batch.total} files in {batch.duration_seconds:.2f}s")
|
|
89
|
+
if not batch.ok:
|
|
90
|
+
for failure in batch.failed:
|
|
91
|
+
print(f"FAILED {failure.source}: {failure.error}")
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Office temporary lock files (`~$*.docx`), Windows alternate data streams (`*:Zone.Identifier`), and the target output directory itself are automatically excluded during discovery.
|
|
95
|
+
|
|
96
|
+
### Inspect LibreOffice Availability
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from docx2pdf_libre import find_libreoffice, get_libreoffice_version
|
|
100
|
+
|
|
101
|
+
executable = find_libreoffice()
|
|
102
|
+
version = get_libreoffice_version()
|
|
103
|
+
print(executable, "->", version)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Public API Overview
|
|
107
|
+
|
|
108
|
+
| Symbol | Purpose |
|
|
109
|
+
| --- | --- |
|
|
110
|
+
| `convert_file(source, output=None, *, timeout=120.0, overwrite=False, libreoffice_path=None, allowed_extensions=...)` | Converts one file to PDF and returns `ConversionResult`. |
|
|
111
|
+
| `convert_bytes(data, *, filename="document.docx", timeout=120.0, libreoffice_path=None, allowed_extensions=...)` | Converts document bytes in memory and returns PDF `bytes`. |
|
|
112
|
+
| `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`. |
|
|
113
|
+
| `discover_documents(source_dir, *, extensions=(".docx",), recursive=False, exclude_dirs=None)` | Lists eligible documents ignoring lock files, `:Zone.Identifier`, and excluded folders. |
|
|
114
|
+
| `find_libreoffice(explicit_path=None)` | Resolves the `soffice` / `libreoffice` executable path (supports `LIBREOFFICE_PATH`). |
|
|
115
|
+
| `get_libreoffice_version(libreoffice_path=None, *, timeout=15.0)` | Queries `soffice --version`. |
|
|
116
|
+
|
|
117
|
+
### Error Handling
|
|
118
|
+
|
|
119
|
+
All library exceptions inherit from `Docx2PdfError`:
|
|
120
|
+
|
|
121
|
+
- `LibreOfficeNotFoundError` *(also `FileNotFoundError`)* — LibreOffice binary is missing or not executable.
|
|
122
|
+
- `InvalidInputError` *(also `ValueError`)* — missing input file/folder, unsupported extension, empty bytes, or invalid options (`timeout <= 0`, `max_workers < 1`).
|
|
123
|
+
- `ConversionTimeoutError` *(also `TimeoutError`)* — LibreOffice exceeded `timeout`.
|
|
124
|
+
- `ConversionError` — LibreOffice exited non-zero or failed to generate a valid `%PDF-` file (exposes `.source`, `.returncode`, `.stderr`).
|
|
125
|
+
- `FileExistsError` — destination PDF already exists and `overwrite=False`.
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from docx2pdf_libre import ConversionError, LibreOfficeNotFoundError, convert_file
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
convert_file("contract.docx")
|
|
132
|
+
except LibreOfficeNotFoundError as exc:
|
|
133
|
+
print("Install LibreOffice first:", exc)
|
|
134
|
+
except ConversionError as exc:
|
|
135
|
+
print(f"Conversion failed (code={exc.returncode}): {exc.stderr}")
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
## Using the Local CLI (Repository Only)
|
|
141
|
+
|
|
142
|
+
> **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.
|
|
143
|
+
|
|
144
|
+
### Local Setup
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
python3 -m venv .venv
|
|
148
|
+
source .venv/bin/activate
|
|
149
|
+
pip install -r requirements.txt
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### CLI Commands
|
|
153
|
+
|
|
154
|
+
Convert all `.docx` files in a folder (outputs to `<folder>/pdfs` by default):
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
python cli/docx2pdf_cli.py path/to/folder
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Convert a single file:
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
python cli/docx2pdf_cli.py path/to/document.docx
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Use custom output folder, recursion, multiple extensions, parallel workers, and overwrite:
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
python cli/docx2pdf_cli.py path/to/folder \
|
|
170
|
+
--outdir-name output_pdf \
|
|
171
|
+
--recursive \
|
|
172
|
+
--extensions .docx,.doc,.odt,.rtf \
|
|
173
|
+
--workers 4 \
|
|
174
|
+
--timeout 90 \
|
|
175
|
+
--overwrite
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Show all CLI options:
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
python cli/docx2pdf_cli.py --help
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
## Layout Fidelity & Headless Troubleshooting
|
|
187
|
+
|
|
188
|
+
- **Fonts:** LibreOffice renders using the fonts installed on the OS. Missing fonts cause fallback substitutions and pagination drift.
|
|
189
|
+
- **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.
|
|
190
|
+
- **Custom LibreOffice binary:** Pass `libreoffice_path="/path/to/soffice"` or set the `LIBREOFFICE_PATH` environment variable.
|
|
191
|
+
|
|
192
|
+
## Development & Quality Gate
|
|
193
|
+
|
|
194
|
+
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):
|
|
195
|
+
|
|
196
|
+
```bash
|
|
197
|
+
python3 -m venv .venv
|
|
198
|
+
source .venv/bin/activate
|
|
199
|
+
pip install -e . --group dev
|
|
200
|
+
python scripts/verify_quality.py
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## License
|
|
204
|
+
|
|
205
|
+
Apache-2.0 — see [LICENSE](LICENSE).
|