minipdf 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.
minipdf-0.1.0/LICENSE ADDED
@@ -0,0 +1,200 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any form of the Work that is based on
40
+ (or derived from) the Work and for which the editorial revisions,
41
+ annotations, elaborations, or other modifications represent, as a whole,
42
+ an original work of authorship. For the purposes of this License,
43
+ Derivative Works shall not include works that remain separable from,
44
+ or merely link (or bind by name) to the interfaces of, the Work and
45
+ Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding those notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ 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
+ APPENDIX: How to apply the Apache License to your work.
178
+
179
+ To apply the Apache License to your work, attach the following
180
+ boilerplate notice, with the fields enclosed by brackets "[]"
181
+ replaced with your own identifying information. (Don't include
182
+ the brackets!) The text should be enclosed in the appropriate
183
+ comment syntax for the file format. We also recommend that a
184
+ file or class name and description of purpose be included on the
185
+ same "printed page" as the copyright notice for easier
186
+ identification within third-party archives.
187
+
188
+ Copyright [yyyy] [name of copyright owner]
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
minipdf-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: minipdf
3
+ Version: 0.1.0
4
+ Summary: Pure Python Office-to-PDF conversion engine
5
+ Author: MiniPdf contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/mini-software/MiniPdf
8
+ Project-URL: Repository, https://github.com/mini-software/MiniPdf
9
+ Classifier: Development Status :: 2 - Pre-Alpha
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: dev
20
+ Requires-Dist: build>=1.2; extra == "dev"
21
+ Requires-Dist: mypy>=1.11; extra == "dev"
22
+ Requires-Dist: pypdf>=5; extra == "dev"
23
+ Requires-Dist: pytest>=8; extra == "dev"
24
+ Requires-Dist: ruff>=0.9; extra == "dev"
25
+ Requires-Dist: twine>=6; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # MiniPdf for Python
29
+
30
+ Experimental pure Python implementation of MiniPdf. The initial release
31
+ converts basic DOCX paragraphs to PDF 1.4 without requiring Microsoft Office,
32
+ LibreOffice, .NET, or Rust at runtime.
33
+
34
+ The package requires Python 3.10 or later. XLSX support is planned; PPTX is not
35
+ currently supported.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install minipdf
41
+ ```
42
+
43
+ ## Python API
44
+
45
+ ```python
46
+ import minipdf
47
+
48
+ minipdf.convert_to_pdf("report.docx", "report.pdf")
49
+ pdf_bytes = minipdf.convert_to_pdf_bytes("report.docx")
50
+ ```
51
+
52
+ ## Command Line
53
+
54
+ ```bash
55
+ minipdf report.docx
56
+ minipdf convert report.docx -o report.pdf
57
+ minipdf report.docx --paper-size a4
58
+ minipdf report.docx --page-width 400 --page-height 500
59
+ ```
60
+
61
+ ## Initial Scope
62
+
63
+ Version 0.1 supports document page geometry, margins, paragraphs, explicit page
64
+ breaks, and basic bold, italic, and font-size run formatting. Text currently
65
+ uses PDF built-in Latin fonts. Tables, images, embedded fonts, CJK/RTL shaping,
66
+ headers, footers, lists, XLSX, and PPTX are not yet supported.
@@ -0,0 +1,39 @@
1
+ # MiniPdf for Python
2
+
3
+ Experimental pure Python implementation of MiniPdf. The initial release
4
+ converts basic DOCX paragraphs to PDF 1.4 without requiring Microsoft Office,
5
+ LibreOffice, .NET, or Rust at runtime.
6
+
7
+ The package requires Python 3.10 or later. XLSX support is planned; PPTX is not
8
+ currently supported.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pip install minipdf
14
+ ```
15
+
16
+ ## Python API
17
+
18
+ ```python
19
+ import minipdf
20
+
21
+ minipdf.convert_to_pdf("report.docx", "report.pdf")
22
+ pdf_bytes = minipdf.convert_to_pdf_bytes("report.docx")
23
+ ```
24
+
25
+ ## Command Line
26
+
27
+ ```bash
28
+ minipdf report.docx
29
+ minipdf convert report.docx -o report.pdf
30
+ minipdf report.docx --paper-size a4
31
+ minipdf report.docx --page-width 400 --page-height 500
32
+ ```
33
+
34
+ ## Initial Scope
35
+
36
+ Version 0.1 supports document page geometry, margins, paragraphs, explicit page
37
+ breaks, and basic bold, italic, and font-size run formatting. Text currently
38
+ uses PDF built-in Latin fonts. Tables, images, embedded fonts, CJK/RTL shaping,
39
+ headers, footers, lists, XLSX, and PPTX are not yet supported.
@@ -0,0 +1,58 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "minipdf"
7
+ version = "0.1.0"
8
+ description = "Pure Python Office-to-PDF conversion engine"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "MiniPdf contributors" }]
14
+ classifiers = [
15
+ "Development Status :: 2 - Pre-Alpha",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "build>=1.2",
27
+ "mypy>=1.11",
28
+ "pypdf>=5",
29
+ "pytest>=8",
30
+ "ruff>=0.9",
31
+ "twine>=6",
32
+ ]
33
+
34
+ [project.scripts]
35
+ minipdf = "minipdf.cli:main"
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/mini-software/MiniPdf"
39
+ Repository = "https://github.com/mini-software/MiniPdf"
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
43
+
44
+ [tool.pytest.ini_options]
45
+ addopts = "-ra"
46
+ pythonpath = ["src"]
47
+ testpaths = ["tests"]
48
+
49
+ [tool.ruff]
50
+ line-length = 100
51
+ target-version = "py310"
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "F", "I", "UP", "B", "SIM"]
55
+
56
+ [tool.mypy]
57
+ python_version = "3.10"
58
+ strict = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,28 @@
1
+ from .api import (
2
+ convert_bytes_to_pdf,
3
+ convert_to_pdf,
4
+ convert_to_pdf_bytes,
5
+ register_font,
6
+ registered_fonts,
7
+ )
8
+ from .errors import InvalidInputError, MiniPdfError, PackageError, UnsupportedFormatError
9
+ from .office import OfficeFormat, detect_office_format
10
+ from .options import ConversionOptions, PageSize
11
+
12
+ __all__ = [
13
+ "ConversionOptions",
14
+ "InvalidInputError",
15
+ "MiniPdfError",
16
+ "OfficeFormat",
17
+ "PackageError",
18
+ "PageSize",
19
+ "UnsupportedFormatError",
20
+ "convert_bytes_to_pdf",
21
+ "convert_to_pdf",
22
+ "convert_to_pdf_bytes",
23
+ "detect_office_format",
24
+ "register_font",
25
+ "registered_fonts",
26
+ ]
27
+
28
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from threading import RLock
6
+
7
+ from .docx import convert_docx
8
+ from .errors import UnsupportedFormatError
9
+ from .office import OfficeFormat, detect_office_format
10
+ from .options import ConversionOptions
11
+
12
+ PathLike = str | os.PathLike[str]
13
+ _font_lock = RLock()
14
+ _fonts: list[tuple[str, bytes]] = []
15
+
16
+
17
+ def register_font(name: str, font_data: bytes) -> None:
18
+ with _font_lock:
19
+ _fonts.append((name, bytes(font_data)))
20
+
21
+
22
+ def registered_fonts() -> tuple[tuple[str, bytes], ...]:
23
+ with _font_lock:
24
+ return tuple(_fonts)
25
+
26
+
27
+ def convert_bytes_to_pdf(
28
+ data: bytes | bytearray | memoryview,
29
+ options: ConversionOptions | None = None,
30
+ ) -> bytes:
31
+ source = bytes(data)
32
+ document_format = detect_office_format(source)
33
+ if document_format is OfficeFormat.DOCX:
34
+ return convert_docx(source, options or ConversionOptions())
35
+ if document_format is OfficeFormat.XLSX:
36
+ raise UnsupportedFormatError("XLSX conversion is planned but not yet supported")
37
+ if document_format is OfficeFormat.PPTX:
38
+ raise UnsupportedFormatError("PPTX conversion is not supported")
39
+ raise UnsupportedFormatError("unsupported or unknown Office document format")
40
+
41
+
42
+ def convert_to_pdf_bytes(
43
+ input_path: PathLike,
44
+ options: ConversionOptions | None = None,
45
+ ) -> bytes:
46
+ return convert_bytes_to_pdf(Path(input_path).read_bytes(), options)
47
+
48
+
49
+ def convert_to_pdf(
50
+ input_path: PathLike,
51
+ output_path: PathLike,
52
+ options: ConversionOptions | None = None,
53
+ ) -> None:
54
+ Path(output_path).write_bytes(convert_to_pdf_bytes(input_path, options))
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from collections.abc import Sequence
6
+ from pathlib import Path
7
+
8
+ from .api import convert_to_pdf
9
+ from .errors import MiniPdfError
10
+ from .options import ConversionOptions, PageSize
11
+
12
+
13
+ def _parser() -> argparse.ArgumentParser:
14
+ parser = argparse.ArgumentParser(prog="minipdf", description="Convert Office files to PDF.")
15
+ parser.add_argument("input", type=Path)
16
+ parser.add_argument("-o", "--output", type=Path)
17
+ parser.add_argument("--paper-size", choices=("a4", "letter"))
18
+ parser.add_argument("--page-width", type=float)
19
+ parser.add_argument("--page-height", type=float)
20
+ return parser
21
+
22
+
23
+ def _options(args: argparse.Namespace, parser: argparse.ArgumentParser) -> ConversionOptions:
24
+ custom_supplied = args.page_width is not None or args.page_height is not None
25
+ if args.paper_size and custom_supplied:
26
+ parser.error("use either --paper-size or --page-width/--page-height, not both")
27
+ if (args.page_width is None) != (args.page_height is None):
28
+ parser.error("--page-width and --page-height must be specified together")
29
+ if args.paper_size == "a4":
30
+ return ConversionOptions(PageSize.A4)
31
+ if args.paper_size == "letter":
32
+ return ConversionOptions(PageSize.LETTER)
33
+ if custom_supplied:
34
+ return ConversionOptions(PageSize(args.page_width, args.page_height))
35
+ return ConversionOptions()
36
+
37
+
38
+ def main(argv: Sequence[str] | None = None) -> int:
39
+ arguments = list(sys.argv[1:] if argv is None else argv)
40
+ if arguments[:1] == ["convert"]:
41
+ arguments.pop(0)
42
+ parser = _parser()
43
+ args = parser.parse_args(arguments)
44
+ output = args.output or args.input.with_suffix(".pdf")
45
+ try:
46
+ convert_to_pdf(args.input, output, _options(args, parser))
47
+ except (MiniPdfError, OSError, ValueError) as error:
48
+ parser.exit(1, f"Error: {error}\n")
49
+ print(output)
50
+ return 0
@@ -0,0 +1,146 @@
1
+ from __future__ import annotations
2
+
3
+ import textwrap
4
+ import xml.etree.ElementTree as ET
5
+ from dataclasses import dataclass
6
+
7
+ from .errors import PackageError
8
+ from .office import OfficePackage
9
+ from .options import ConversionOptions, PageSize
10
+ from .pdf import PdfDocument, TextStyle
11
+
12
+ WORD_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
13
+ W = f"{{{WORD_NS}}}"
14
+ DEFAULT_MARGIN = 54.0
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class Run:
19
+ text: str
20
+ style: TextStyle
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class Paragraph:
25
+ runs: tuple[Run, ...]
26
+ page_break_before: bool = False
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Document:
31
+ paragraphs: tuple[Paragraph, ...]
32
+ page_size: PageSize
33
+ margins: tuple[float, float, float, float]
34
+
35
+
36
+ def _points(value: str | None, default: float) -> float:
37
+ if value is None:
38
+ return default
39
+ try:
40
+ return float(value) / 20.0
41
+ except ValueError:
42
+ return default
43
+
44
+
45
+ def read_document(package: OfficePackage) -> Document:
46
+ document_xml = package.read("word/document.xml")
47
+ if document_xml is None:
48
+ raise PackageError("DOCX package is missing word/document.xml")
49
+ try:
50
+ root = ET.fromstring(document_xml)
51
+ except ET.ParseError as error:
52
+ raise PackageError("word/document.xml is malformed") from error
53
+ body = root.find(f"{W}body")
54
+ if body is None:
55
+ raise PackageError("word/document.xml is missing the document body")
56
+
57
+ section = body.find(f"{W}sectPr")
58
+ size = section.find(f"{W}pgSz") if section is not None else None
59
+ margins = section.find(f"{W}pgMar") if section is not None else None
60
+ page_size = PageSize(
61
+ _points(size.get(f"{W}w") if size is not None else None, PageSize.A4.width),
62
+ _points(size.get(f"{W}h") if size is not None else None, PageSize.A4.height),
63
+ )
64
+ page_margins = tuple(
65
+ _points(margins.get(f"{W}{name}") if margins is not None else None, DEFAULT_MARGIN)
66
+ for name in ("top", "right", "bottom", "left")
67
+ )
68
+
69
+ paragraphs: list[Paragraph] = []
70
+ for paragraph_node in body.findall(f"{W}p"):
71
+ page_break = paragraph_node.find(f".//{W}pageBreakBefore") is not None
72
+ runs: list[Run] = []
73
+ for run_node in paragraph_node.findall(f"{W}r"):
74
+ properties = run_node.find(f"{W}rPr")
75
+ size_node = properties.find(f"{W}sz") if properties is not None else None
76
+ style = TextStyle(
77
+ size=_points(size_node.get(f"{W}val") if size_node is not None else None, 11.0),
78
+ bold=properties is not None and properties.find(f"{W}b") is not None,
79
+ italic=properties is not None and properties.find(f"{W}i") is not None,
80
+ )
81
+ chunks: list[str] = []
82
+ for child in run_node:
83
+ if child.tag == f"{W}t":
84
+ chunks.append(child.text or "")
85
+ elif child.tag == f"{W}tab":
86
+ chunks.append("\t")
87
+ elif child.tag == f"{W}br":
88
+ break_type = child.get(f"{W}type")
89
+ if break_type == "page":
90
+ if chunks:
91
+ runs.append(Run("".join(chunks), style))
92
+ chunks = []
93
+ if runs:
94
+ paragraphs.append(Paragraph(tuple(runs), page_break))
95
+ runs = []
96
+ page_break = True
97
+ else:
98
+ chunks.append("\n")
99
+ if chunks:
100
+ runs.append(Run("".join(chunks), style))
101
+ paragraphs.append(Paragraph(tuple(runs), page_break))
102
+
103
+ return Document(tuple(paragraphs), page_size, page_margins) # type: ignore[arg-type]
104
+
105
+
106
+ def render_document(document: Document, options: ConversionOptions) -> bytes:
107
+ page_size = options.page_size or document.page_size
108
+ top, right, bottom, left = document.margins
109
+ pdf = PdfDocument()
110
+ page = pdf.add_page(page_size.width, page_size.height)
111
+ cursor_y = page_size.height - top
112
+ available_width = page_size.width - left - right
113
+
114
+ for paragraph in document.paragraphs:
115
+ if paragraph.page_break_before and page.operations:
116
+ page = pdf.add_page(page_size.width, page_size.height)
117
+ cursor_y = page_size.height - top
118
+ if not paragraph.runs:
119
+ cursor_y -= 16.0
120
+ continue
121
+ for run in paragraph.runs:
122
+ average_width = max(run.style.size * 0.5, 1.0)
123
+ columns = max(1, int(available_width / average_width))
124
+ lines = run.text.splitlines() or [""]
125
+ for source_line in lines:
126
+ wrapped = textwrap.wrap(
127
+ source_line,
128
+ width=columns,
129
+ replace_whitespace=False,
130
+ drop_whitespace=False,
131
+ break_long_words=True,
132
+ ) or [""]
133
+ for line in wrapped:
134
+ line_height = max(16.0, run.style.size * 1.2)
135
+ if cursor_y - line_height < bottom:
136
+ page = pdf.add_page(page_size.width, page_size.height)
137
+ cursor_y = page_size.height - top
138
+ cursor_y -= line_height
139
+ page.add_text(line, left, cursor_y, run.style)
140
+ cursor_y -= 5.6
141
+ return pdf.to_bytes()
142
+
143
+
144
+ def convert_docx(data: bytes, options: ConversionOptions) -> bytes:
145
+ package = OfficePackage(data)
146
+ return render_document(read_document(package), options)
@@ -0,0 +1,14 @@
1
+ class MiniPdfError(Exception):
2
+ """Base exception for MiniPdf conversion failures."""
3
+
4
+
5
+ class InvalidInputError(MiniPdfError, ValueError):
6
+ """Raised when an input or conversion option is invalid."""
7
+
8
+
9
+ class UnsupportedFormatError(MiniPdfError):
10
+ """Raised when an Office package format is not supported."""
11
+
12
+
13
+ class PackageError(MiniPdfError):
14
+ """Raised when an Office ZIP package is malformed or unsafe."""
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import zipfile
5
+ from enum import Enum
6
+
7
+ from .errors import PackageError
8
+
9
+ MAX_ENTRY_SIZE = 64 * 1024 * 1024
10
+ MAX_PACKAGE_SIZE = 256 * 1024 * 1024
11
+
12
+
13
+ class OfficeFormat(Enum):
14
+ UNKNOWN = "unknown"
15
+ XLSX = "xlsx"
16
+ DOCX = "docx"
17
+ PPTX = "pptx"
18
+
19
+
20
+ class OfficePackage:
21
+ def __init__(self, data: bytes) -> None:
22
+ try:
23
+ self._archive = zipfile.ZipFile(io.BytesIO(data))
24
+ except (OSError, zipfile.BadZipFile) as error:
25
+ raise PackageError("input is not a valid Office ZIP package") from error
26
+ self._validate()
27
+
28
+ def _validate(self) -> None:
29
+ total_size = 0
30
+ for entry in self._archive.infolist():
31
+ normalized = entry.filename.replace("\\", "/")
32
+ parts = normalized.split("/")
33
+ if normalized.startswith("/") or ".." in parts:
34
+ raise PackageError(f"unsafe package path: {entry.filename}")
35
+ if entry.flag_bits & 0x1:
36
+ raise PackageError("encrypted Office packages are not supported")
37
+ if entry.file_size > MAX_ENTRY_SIZE:
38
+ raise PackageError(f"package entry is too large: {entry.filename}")
39
+ total_size += entry.file_size
40
+ if total_size > MAX_PACKAGE_SIZE:
41
+ raise PackageError("Office package expands beyond the safety limit")
42
+
43
+ @property
44
+ def format(self) -> OfficeFormat:
45
+ names = (entry.filename.replace("\\", "/") for entry in self._archive.infolist())
46
+ roots = {name.split("/", 1)[0] for name in names if "/" in name}
47
+ if "word" in roots:
48
+ return OfficeFormat.DOCX
49
+ if "xl" in roots:
50
+ return OfficeFormat.XLSX
51
+ if "ppt" in roots:
52
+ return OfficeFormat.PPTX
53
+ return OfficeFormat.UNKNOWN
54
+
55
+ def read(self, name: str) -> bytes | None:
56
+ try:
57
+ return self._archive.read(name)
58
+ except KeyError:
59
+ return None
60
+ except (OSError, RuntimeError, zipfile.BadZipFile) as error:
61
+ raise PackageError(f"cannot read package entry: {name}") from error
62
+
63
+
64
+ def detect_office_format(data: bytes) -> OfficeFormat:
65
+ return OfficePackage(data).format
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from typing import ClassVar
6
+
7
+ from .errors import InvalidInputError
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class PageSize:
12
+ """PDF page dimensions measured in points."""
13
+
14
+ width: float
15
+ height: float
16
+
17
+ A4: ClassVar[PageSize]
18
+ LETTER: ClassVar[PageSize]
19
+
20
+ def __post_init__(self) -> None:
21
+ if (
22
+ not math.isfinite(self.width)
23
+ or not math.isfinite(self.height)
24
+ or self.width <= 0
25
+ or self.height <= 0
26
+ ):
27
+ raise InvalidInputError("page width and height must be positive finite values")
28
+
29
+
30
+ PageSize.A4 = PageSize(595.28, 841.89)
31
+ PageSize.LETTER = PageSize(612.0, 792.0)
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class ConversionOptions:
36
+ """Options shared by all supported Office converters."""
37
+
38
+ page_size: PageSize | None = None
@@ -0,0 +1,128 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+
6
+ def _number(value: float) -> str:
7
+ return f"{value:.3f}".rstrip("0").rstrip(".") or "0"
8
+
9
+
10
+ def _pdf_text(value: str) -> bytes:
11
+ encoded = value.encode("cp1252", errors="replace")
12
+ return encoded.replace(b"\\", b"\\\\").replace(b"(", b"\\(").replace(b")", b"\\)")
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class TextStyle:
17
+ size: float = 11.0
18
+ bold: bool = False
19
+ italic: bool = False
20
+
21
+ @property
22
+ def resource(self) -> str:
23
+ if self.bold and self.italic:
24
+ return "F4"
25
+ if self.bold:
26
+ return "F2"
27
+ if self.italic:
28
+ return "F3"
29
+ return "F1"
30
+
31
+
32
+ @dataclass(slots=True)
33
+ class PdfPage:
34
+ width: float
35
+ height: float
36
+ operations: list[bytes] = field(default_factory=list)
37
+
38
+ def add_text(self, text: str, x: float, y: float, style: TextStyle) -> None:
39
+ self.operations.append(
40
+ b"BT /"
41
+ + style.resource.encode("ascii")
42
+ + b" "
43
+ + _number(style.size).encode("ascii")
44
+ + b" Tf 0 0 0 rg 1 0 0 1 "
45
+ + _number(x).encode("ascii")
46
+ + b" "
47
+ + _number(y).encode("ascii")
48
+ + b" Tm ("
49
+ + _pdf_text(text)
50
+ + b") Tj ET\n"
51
+ )
52
+
53
+ def content(self) -> bytes:
54
+ return b"".join(self.operations)
55
+
56
+
57
+ @dataclass(slots=True)
58
+ class PdfDocument:
59
+ pages: list[PdfPage] = field(default_factory=list)
60
+
61
+ def add_page(self, width: float, height: float) -> PdfPage:
62
+ page = PdfPage(width, height)
63
+ self.pages.append(page)
64
+ return page
65
+
66
+ def to_bytes(self) -> bytes:
67
+ if not self.pages:
68
+ self.add_page(595.28, 841.89)
69
+
70
+ page_count = len(self.pages)
71
+ font_start = 3 + page_count * 2
72
+ objects: list[bytes] = [
73
+ b"<< /Type /Catalog /Pages 2 0 R >>",
74
+ b"<< /Type /Pages /Kids ["
75
+ + b" ".join(f"{3 + index * 2} 0 R".encode("ascii") for index in range(page_count))
76
+ + f"] /Count {page_count} >>".encode("ascii"),
77
+ ]
78
+
79
+ for index, page in enumerate(self.pages):
80
+ page_id = 3 + index * 2
81
+ content_id = page_id + 1
82
+ resources = (
83
+ f"/Font << /F1 {font_start} 0 R /F2 {font_start + 1} 0 R "
84
+ f"/F3 {font_start + 2} 0 R /F4 {font_start + 3} 0 R >>"
85
+ )
86
+ objects.append(
87
+ (
88
+ f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {_number(page.width)} "
89
+ f"{_number(page.height)}] /Resources << {resources} >> "
90
+ f"/Contents {content_id} 0 R >>"
91
+ ).encode("ascii")
92
+ )
93
+ content = page.content()
94
+ objects.append(
95
+ f"<< /Length {len(content)} >>\nstream\n".encode("ascii") + content + b"endstream"
96
+ )
97
+
98
+ for base_font in (
99
+ "Helvetica",
100
+ "Helvetica-Bold",
101
+ "Helvetica-Oblique",
102
+ "Helvetica-BoldOblique",
103
+ ):
104
+ font_object = (
105
+ f"<< /Type /Font /Subtype /Type1 /BaseFont /{base_font} "
106
+ "/Encoding /WinAnsiEncoding >>"
107
+ )
108
+ objects.append(font_object.encode("ascii"))
109
+
110
+ output = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
111
+ offsets = [0]
112
+ for object_id, content in enumerate(objects, start=1):
113
+ offsets.append(len(output))
114
+ output.extend(f"{object_id} 0 obj\n".encode("ascii"))
115
+ output.extend(content)
116
+ output.extend(b"\nendobj\n")
117
+ xref_offset = len(output)
118
+ output.extend(f"xref\n0 {len(objects) + 1}\n".encode("ascii"))
119
+ output.extend(b"0000000000 65535 f \n")
120
+ for offset in offsets[1:]:
121
+ output.extend(f"{offset:010d} 00000 n \n".encode("ascii"))
122
+ output.extend(
123
+ (
124
+ f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n"
125
+ f"startxref\n{xref_offset}\n%%EOF\n"
126
+ ).encode("ascii")
127
+ )
128
+ return bytes(output)
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: minipdf
3
+ Version: 0.1.0
4
+ Summary: Pure Python Office-to-PDF conversion engine
5
+ Author: MiniPdf contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/mini-software/MiniPdf
8
+ Project-URL: Repository, https://github.com/mini-software/MiniPdf
9
+ Classifier: Development Status :: 2 - Pre-Alpha
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: dev
20
+ Requires-Dist: build>=1.2; extra == "dev"
21
+ Requires-Dist: mypy>=1.11; extra == "dev"
22
+ Requires-Dist: pypdf>=5; extra == "dev"
23
+ Requires-Dist: pytest>=8; extra == "dev"
24
+ Requires-Dist: ruff>=0.9; extra == "dev"
25
+ Requires-Dist: twine>=6; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # MiniPdf for Python
29
+
30
+ Experimental pure Python implementation of MiniPdf. The initial release
31
+ converts basic DOCX paragraphs to PDF 1.4 without requiring Microsoft Office,
32
+ LibreOffice, .NET, or Rust at runtime.
33
+
34
+ The package requires Python 3.10 or later. XLSX support is planned; PPTX is not
35
+ currently supported.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install minipdf
41
+ ```
42
+
43
+ ## Python API
44
+
45
+ ```python
46
+ import minipdf
47
+
48
+ minipdf.convert_to_pdf("report.docx", "report.pdf")
49
+ pdf_bytes = minipdf.convert_to_pdf_bytes("report.docx")
50
+ ```
51
+
52
+ ## Command Line
53
+
54
+ ```bash
55
+ minipdf report.docx
56
+ minipdf convert report.docx -o report.pdf
57
+ minipdf report.docx --paper-size a4
58
+ minipdf report.docx --page-width 400 --page-height 500
59
+ ```
60
+
61
+ ## Initial Scope
62
+
63
+ Version 0.1 supports document page geometry, margins, paragraphs, explicit page
64
+ breaks, and basic bold, italic, and font-size run formatting. Text currently
65
+ uses PDF built-in Latin fonts. Tables, images, embedded fonts, CJK/RTL shaping,
66
+ headers, footers, lists, XLSX, and PPTX are not yet supported.
@@ -0,0 +1,22 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/minipdf/__init__.py
5
+ src/minipdf/__main__.py
6
+ src/minipdf/api.py
7
+ src/minipdf/cli.py
8
+ src/minipdf/docx.py
9
+ src/minipdf/errors.py
10
+ src/minipdf/office.py
11
+ src/minipdf/options.py
12
+ src/minipdf/pdf.py
13
+ src/minipdf.egg-info/PKG-INFO
14
+ src/minipdf.egg-info/SOURCES.txt
15
+ src/minipdf.egg-info/dependency_links.txt
16
+ src/minipdf.egg-info/entry_points.txt
17
+ src/minipdf.egg-info/requires.txt
18
+ src/minipdf.egg-info/top_level.txt
19
+ tests/test_api.py
20
+ tests/test_cli.py
21
+ tests/test_docx.py
22
+ tests/test_options.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ minipdf = minipdf.cli:main
@@ -0,0 +1,8 @@
1
+
2
+ [dev]
3
+ build>=1.2
4
+ mypy>=1.11
5
+ pypdf>=5
6
+ pytest>=8
7
+ ruff>=0.9
8
+ twine>=6
@@ -0,0 +1 @@
1
+ minipdf
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import zipfile
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+ from helpers import create_docx
9
+
10
+ from minipdf import (
11
+ OfficeFormat,
12
+ PackageError,
13
+ UnsupportedFormatError,
14
+ convert_bytes_to_pdf,
15
+ convert_to_pdf,
16
+ convert_to_pdf_bytes,
17
+ detect_office_format,
18
+ )
19
+
20
+
21
+ def test_path_and_bytes_apis_produce_identical_output(tmp_path: Path) -> None:
22
+ input_path = tmp_path / "sample.docx"
23
+ output_path = tmp_path / "sample.pdf"
24
+ input_path.write_bytes(create_docx())
25
+
26
+ expected = convert_bytes_to_pdf(input_path.read_bytes())
27
+ assert convert_to_pdf_bytes(input_path) == expected
28
+ convert_to_pdf(input_path, output_path)
29
+ assert output_path.read_bytes() == expected
30
+
31
+
32
+ def test_detects_docx_package() -> None:
33
+ assert detect_office_format(create_docx()) is OfficeFormat.DOCX
34
+
35
+
36
+ def test_rejects_unknown_office_package() -> None:
37
+ package = io.BytesIO()
38
+ with zipfile.ZipFile(package, "w") as archive:
39
+ archive.writestr("custom/data.xml", "<data/>")
40
+
41
+ with pytest.raises(UnsupportedFormatError, match="unknown"):
42
+ convert_bytes_to_pdf(package.getvalue())
43
+
44
+
45
+ def test_rejects_non_zip_input() -> None:
46
+ with pytest.raises(PackageError, match="valid Office ZIP"):
47
+ convert_bytes_to_pdf(b"not a zip")
48
+
49
+
50
+ def test_rejects_unsafe_package_paths() -> None:
51
+ package = io.BytesIO()
52
+ with zipfile.ZipFile(package, "w") as archive:
53
+ archive.writestr("word/document.xml", "<document/>")
54
+ archive.writestr("../escape.xml", "<escape/>")
55
+
56
+ with pytest.raises(PackageError, match="unsafe package path"):
57
+ detect_office_format(package.getvalue())
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from helpers import create_docx
8
+ from pypdf import PdfReader
9
+
10
+
11
+ def test_cli_converts_with_default_output_name(tmp_path: Path) -> None:
12
+ input_path = tmp_path / "sample.docx"
13
+ input_path.write_bytes(create_docx())
14
+
15
+ result = subprocess.run(
16
+ [sys.executable, "-m", "minipdf", str(input_path)],
17
+ check=False,
18
+ capture_output=True,
19
+ text=True,
20
+ )
21
+
22
+ output_path = input_path.with_suffix(".pdf")
23
+ assert result.returncode == 0
24
+ assert result.stdout.strip() == str(output_path)
25
+ assert result.stderr == ""
26
+ assert len(PdfReader(output_path).pages) == 1
27
+
28
+
29
+ def test_cli_supports_convert_command_and_page_size(tmp_path: Path) -> None:
30
+ input_path = tmp_path / "sample.docx"
31
+ output_path = tmp_path / "custom.pdf"
32
+ input_path.write_bytes(create_docx())
33
+
34
+ result = subprocess.run(
35
+ [
36
+ sys.executable,
37
+ "-m",
38
+ "minipdf",
39
+ "convert",
40
+ str(input_path),
41
+ "-o",
42
+ str(output_path),
43
+ "--paper-size",
44
+ "a4",
45
+ ],
46
+ check=False,
47
+ capture_output=True,
48
+ text=True,
49
+ )
50
+
51
+ assert result.returncode == 0
52
+ page = PdfReader(output_path).pages[0]
53
+ assert float(page.mediabox.width) == 595.28
54
+ assert float(page.mediabox.height) == 841.89
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+
5
+ from helpers import create_docx
6
+ from pypdf import PdfReader
7
+
8
+ from minipdf import ConversionOptions, PageSize, convert_bytes_to_pdf
9
+
10
+
11
+ def test_converts_basic_docx_to_parseable_pdf() -> None:
12
+ pdf = convert_bytes_to_pdf(create_docx())
13
+
14
+ assert pdf.startswith(b"%PDF-1.4")
15
+ assert pdf.endswith(b"%%EOF\n")
16
+ reader = PdfReader(io.BytesIO(pdf))
17
+ assert len(reader.pages) == 1
18
+ assert reader.pages[0].extract_text() == "Hello from Python MiniPdf\nSecond paragraph"
19
+ assert float(reader.pages[0].mediabox.width) == 612.0
20
+ assert float(reader.pages[0].mediabox.height) == 792.0
21
+
22
+
23
+ def test_preserves_explicit_page_breaks() -> None:
24
+ reader = PdfReader(io.BytesIO(convert_bytes_to_pdf(create_docx(page_break=True))))
25
+
26
+ assert len(reader.pages) == 2
27
+ assert reader.pages[0].extract_text() == "Hello from Python MiniPdf"
28
+ assert reader.pages[1].extract_text() == "Second paragraph"
29
+
30
+
31
+ def test_api_page_size_overrides_document_geometry() -> None:
32
+ options = ConversionOptions(PageSize(400, 500))
33
+ reader = PdfReader(io.BytesIO(convert_bytes_to_pdf(create_docx(), options)))
34
+
35
+ assert float(reader.pages[0].mediabox.width) == 400.0
36
+ assert float(reader.pages[0].mediabox.height) == 500.0
37
+
38
+
39
+ def test_output_is_deterministic() -> None:
40
+ source = create_docx()
41
+
42
+ assert convert_bytes_to_pdf(source) == convert_bytes_to_pdf(source)
@@ -0,0 +1,24 @@
1
+ import math
2
+
3
+ import pytest
4
+
5
+ from minipdf import ConversionOptions, InvalidInputError, PageSize
6
+
7
+
8
+ def test_exposes_standard_page_sizes() -> None:
9
+ assert PageSize(595.28, 841.89) == PageSize.A4
10
+ assert PageSize(612.0, 792.0) == PageSize.LETTER
11
+
12
+
13
+ @pytest.mark.parametrize(
14
+ ("width", "height"),
15
+ [(0, 10), (-1, 10), (10, 0), (10, -1), (math.inf, 10), (10, math.nan)],
16
+ )
17
+ def test_rejects_invalid_page_dimensions(width: float, height: float) -> None:
18
+ with pytest.raises(InvalidInputError, match="positive finite"):
19
+ PageSize(width, height)
20
+
21
+
22
+ def test_conversion_options_default_to_document_page_size() -> None:
23
+ assert ConversionOptions().page_size is None
24
+ assert ConversionOptions(page_size=PageSize.LETTER).page_size == PageSize.LETTER