pdf2zugferd 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.
- pdf2zugferd-0.1.0/LICENSE +202 -0
- pdf2zugferd-0.1.0/PKG-INFO +94 -0
- pdf2zugferd-0.1.0/README.md +69 -0
- pdf2zugferd-0.1.0/pyproject.toml +83 -0
- pdf2zugferd-0.1.0/pyproject.toml.orig +63 -0
- pdf2zugferd-0.1.0/src/pdf2zugferd/__init__.py +3 -0
- pdf2zugferd-0.1.0/src/pdf2zugferd/__main__.py +3 -0
- pdf2zugferd-0.1.0/src/pdf2zugferd/cli.py +68 -0
- pdf2zugferd-0.1.0/src/pdf2zugferd/config.py +73 -0
- pdf2zugferd-0.1.0/src/pdf2zugferd/extract.py +158 -0
- pdf2zugferd-0.1.0/src/pdf2zugferd/models.py +38 -0
- pdf2zugferd-0.1.0/src/pdf2zugferd/py.typed +0 -0
- pdf2zugferd-0.1.0/src/pdf2zugferd/zugferd.py +98 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pdf2zugferd
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Convert invoice PDFs from LibreOffice/MS Office into ZUGFeRD (EN 16931) PDFs
|
|
5
|
+
Keywords: zugferd,factur-x,e-invoice,en16931,xrechnung,pdf
|
|
6
|
+
Author: Pascal Zimmermann
|
|
7
|
+
Author-email: Pascal Zimmermann <pascal.zimmermann@theiotstudio.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
13
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
|
+
Classifier: Natural Language :: German
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Dist: drafthorse>=2025.2.0
|
|
22
|
+
Requires-Dist: pdfplumber>=0.11.10
|
|
23
|
+
Requires-Python: >=3.12
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# pdf2zugferd
|
|
27
|
+
|
|
28
|
+
Turn an invoice PDF exported from LibreOffice, OpenOffice or MS Office into a
|
|
29
|
+
**ZUGFeRD / Factur-X (EN 16931)** PDF: the original pages plus an embedded,
|
|
30
|
+
schema-validated `factur-x.xml`.
|
|
31
|
+
|
|
32
|
+
The invoice data is read straight from the PDF text layer, so no OCR is
|
|
33
|
+
needed for office-generated PDFs. Seller data and IBAN come from a config file.
|
|
34
|
+
|
|
35
|
+
> **Heads-up: template-based tool.** This is not a generic PDF-to-e-invoice
|
|
36
|
+
> converter. It only understands one fixed German invoice layout (see
|
|
37
|
+
> [Supported invoice layout](#supported-invoice-layout)) and issues invoices
|
|
38
|
+
> without VAT (Kleinunternehmer, § 19 UStG). PDFs with a different layout are
|
|
39
|
+
> rejected, not guessed. The output is provided as is, without warranty: validate
|
|
40
|
+
> it with your own validator before relying on it for legal purposes.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
The tool is published on [PyPI](https://pypi.org/project/pdf2zugferd/) as
|
|
45
|
+
`pdf2zugferd` (Python >= 3.12). The package, the import name and the command
|
|
46
|
+
are all called `pdf2zugferd`.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
uvx pdf2zugferd --help # run without installing
|
|
50
|
+
pipx install pdf2zugferd # or: pip install pdf2zugferd
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
cp config.example.toml config.toml # fill in your data
|
|
57
|
+
pdf2zugferd invoice.pdf -c config.toml # -> invoice_zugferd.pdf
|
|
58
|
+
pdf2zugferd invoice.pdf -c config.toml -o out.pdf --xml-only --force
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Without Python, download a single-file binary from the GitHub release
|
|
62
|
+
(Linux, Windows, macOS), or run from source with [uv](https://docs.astral.sh/uv/):
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
uv sync
|
|
66
|
+
uv run pdf2zugferd invoice.pdf -c config.toml
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Supported invoice layout
|
|
70
|
+
|
|
71
|
+
The parser targets one fixed template (German labels `Rechnungsdatum`,
|
|
72
|
+
`Rechnungsnummer`, `Kundennummer`, a position table, `Betrag … €`,
|
|
73
|
+
`Zahlungsziel beträgt N Tage`). Totals are cross-checked and the tool aborts
|
|
74
|
+
instead of emitting a wrong e-invoice. Invoices are issued without VAT
|
|
75
|
+
(Kleinunternehmer, § 19 UStG, tax category `E`).
|
|
76
|
+
|
|
77
|
+
## Limitations
|
|
78
|
+
|
|
79
|
+
- The output is not converted to PDF/A-3 (fonts are not re-embedded). Most
|
|
80
|
+
receiving software only needs the embedded XML; strict PDF/A validators may
|
|
81
|
+
complain. Export the source as PDF/A-1b from LibreOffice if you need it.
|
|
82
|
+
- Scanned PDFs are rejected; run them through OCR (e.g. `ocrmypdf`) first.
|
|
83
|
+
|
|
84
|
+
## Development
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
uv run ruff format . && uv run ruff check .
|
|
88
|
+
uv run pytest # unit + e2e (CLI)
|
|
89
|
+
uv run bandit -r src && uv run pip-audit --skip-editable
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## License
|
|
93
|
+
|
|
94
|
+
Apache-2.0, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# pdf2zugferd
|
|
2
|
+
|
|
3
|
+
Turn an invoice PDF exported from LibreOffice, OpenOffice or MS Office into a
|
|
4
|
+
**ZUGFeRD / Factur-X (EN 16931)** PDF: the original pages plus an embedded,
|
|
5
|
+
schema-validated `factur-x.xml`.
|
|
6
|
+
|
|
7
|
+
The invoice data is read straight from the PDF text layer, so no OCR is
|
|
8
|
+
needed for office-generated PDFs. Seller data and IBAN come from a config file.
|
|
9
|
+
|
|
10
|
+
> **Heads-up: template-based tool.** This is not a generic PDF-to-e-invoice
|
|
11
|
+
> converter. It only understands one fixed German invoice layout (see
|
|
12
|
+
> [Supported invoice layout](#supported-invoice-layout)) and issues invoices
|
|
13
|
+
> without VAT (Kleinunternehmer, § 19 UStG). PDFs with a different layout are
|
|
14
|
+
> rejected, not guessed. The output is provided as is, without warranty: validate
|
|
15
|
+
> it with your own validator before relying on it for legal purposes.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
The tool is published on [PyPI](https://pypi.org/project/pdf2zugferd/) as
|
|
20
|
+
`pdf2zugferd` (Python >= 3.12). The package, the import name and the command
|
|
21
|
+
are all called `pdf2zugferd`.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
uvx pdf2zugferd --help # run without installing
|
|
25
|
+
pipx install pdf2zugferd # or: pip install pdf2zugferd
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
cp config.example.toml config.toml # fill in your data
|
|
32
|
+
pdf2zugferd invoice.pdf -c config.toml # -> invoice_zugferd.pdf
|
|
33
|
+
pdf2zugferd invoice.pdf -c config.toml -o out.pdf --xml-only --force
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Without Python, download a single-file binary from the GitHub release
|
|
37
|
+
(Linux, Windows, macOS), or run from source with [uv](https://docs.astral.sh/uv/):
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
uv sync
|
|
41
|
+
uv run pdf2zugferd invoice.pdf -c config.toml
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Supported invoice layout
|
|
45
|
+
|
|
46
|
+
The parser targets one fixed template (German labels `Rechnungsdatum`,
|
|
47
|
+
`Rechnungsnummer`, `Kundennummer`, a position table, `Betrag … €`,
|
|
48
|
+
`Zahlungsziel beträgt N Tage`). Totals are cross-checked and the tool aborts
|
|
49
|
+
instead of emitting a wrong e-invoice. Invoices are issued without VAT
|
|
50
|
+
(Kleinunternehmer, § 19 UStG, tax category `E`).
|
|
51
|
+
|
|
52
|
+
## Limitations
|
|
53
|
+
|
|
54
|
+
- The output is not converted to PDF/A-3 (fonts are not re-embedded). Most
|
|
55
|
+
receiving software only needs the embedded XML; strict PDF/A validators may
|
|
56
|
+
complain. Export the source as PDF/A-1b from LibreOffice if you need it.
|
|
57
|
+
- Scanned PDFs are rejected; run them through OCR (e.g. `ocrmypdf`) first.
|
|
58
|
+
|
|
59
|
+
## Development
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
uv run ruff format . && uv run ruff check .
|
|
63
|
+
uv run pytest # unit + e2e (CLI)
|
|
64
|
+
uv run bandit -r src && uv run pip-audit --skip-editable
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
Apache-2.0, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pdf2zugferd"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Convert invoice PDFs from LibreOffice/MS Office into ZUGFeRD (EN 16931) PDFs"
|
|
5
|
+
license = "Apache-2.0"
|
|
6
|
+
license-files = ["LICENSE"]
|
|
7
|
+
keywords = [
|
|
8
|
+
"zugferd",
|
|
9
|
+
"factur-x",
|
|
10
|
+
"e-invoice",
|
|
11
|
+
"en16931",
|
|
12
|
+
"xrechnung",
|
|
13
|
+
"pdf",
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Environment :: Console",
|
|
18
|
+
"Intended Audience :: End Users/Desktop",
|
|
19
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
20
|
+
"Natural Language :: German",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
25
|
+
"Topic :: Office/Business :: Financial :: Accounting",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
readme = "README.md"
|
|
29
|
+
requires-python = ">=3.12"
|
|
30
|
+
dependencies = [
|
|
31
|
+
"drafthorse>=2025.2.0",
|
|
32
|
+
"pdfplumber>=0.11.10",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[[project.authors]]
|
|
36
|
+
name = "Pascal Zimmermann"
|
|
37
|
+
email = "pascal.zimmermann@theiotstudio.com"
|
|
38
|
+
|
|
39
|
+
[project.scripts]
|
|
40
|
+
pdf2zugferd = "pdf2zugferd.cli:main"
|
|
41
|
+
|
|
42
|
+
[build-system]
|
|
43
|
+
requires = ["uv_build>=0.11.7,<0.14.0"]
|
|
44
|
+
build-backend = "uv_build"
|
|
45
|
+
|
|
46
|
+
[dependency-groups]
|
|
47
|
+
dev = [
|
|
48
|
+
"bandit>=1.9.4",
|
|
49
|
+
"lxml>=6.1.3",
|
|
50
|
+
"pip-audit>=2.10.1",
|
|
51
|
+
"pyinstaller>=6.22.3",
|
|
52
|
+
"pypdf>=6.21.1",
|
|
53
|
+
"pytest>=9.1.1",
|
|
54
|
+
"pytest-cov>=7.1.0",
|
|
55
|
+
"reportlab>=5.0.1",
|
|
56
|
+
"ruff>=0.17.1",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
[tool.ruff]
|
|
60
|
+
line-length = 88
|
|
61
|
+
target-version = "py312"
|
|
62
|
+
|
|
63
|
+
[tool.ruff.lint]
|
|
64
|
+
select = [
|
|
65
|
+
"E",
|
|
66
|
+
"F",
|
|
67
|
+
"I",
|
|
68
|
+
"B",
|
|
69
|
+
"UP",
|
|
70
|
+
"S",
|
|
71
|
+
"SIM",
|
|
72
|
+
"RUF",
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
[tool.ruff.lint.per-file-ignores]
|
|
76
|
+
"tests/*" = [
|
|
77
|
+
"S101",
|
|
78
|
+
"S603",
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
[tool.pytest.ini_options]
|
|
82
|
+
testpaths = ["tests"]
|
|
83
|
+
addopts = "--cov=pdf2zugferd --cov-report=term-missing"
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pdf2zugferd"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Convert invoice PDFs from LibreOffice/MS Office into ZUGFeRD (EN 16931) PDFs"
|
|
5
|
+
license = "Apache-2.0"
|
|
6
|
+
license-files = ["LICENSE"]
|
|
7
|
+
keywords = ["zugferd", "factur-x", "e-invoice", "en16931", "xrechnung", "pdf"]
|
|
8
|
+
classifiers = [
|
|
9
|
+
"Development Status :: 3 - Alpha",
|
|
10
|
+
"Environment :: Console",
|
|
11
|
+
"Intended Audience :: End Users/Desktop",
|
|
12
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
13
|
+
"Natural Language :: German",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
18
|
+
"Topic :: Office/Business :: Financial :: Accounting",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
readme = "README.md"
|
|
22
|
+
authors = [
|
|
23
|
+
{ name = "Pascal Zimmermann", email = "pascal.zimmermann@theiotstudio.com" }
|
|
24
|
+
]
|
|
25
|
+
requires-python = ">=3.12"
|
|
26
|
+
dependencies = [
|
|
27
|
+
"drafthorse>=2025.2.0",
|
|
28
|
+
"pdfplumber>=0.11.10",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["uv_build>=0.11.7,<0.14.0"]
|
|
33
|
+
build-backend = "uv_build"
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
dev = [
|
|
37
|
+
"bandit>=1.9.4",
|
|
38
|
+
"lxml>=6.1.3",
|
|
39
|
+
"pip-audit>=2.10.1",
|
|
40
|
+
"pyinstaller>=6.22.3",
|
|
41
|
+
"pypdf>=6.21.1",
|
|
42
|
+
"pytest>=9.1.1",
|
|
43
|
+
"pytest-cov>=7.1.0",
|
|
44
|
+
"reportlab>=5.0.1",
|
|
45
|
+
"ruff>=0.17.1",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[project.scripts]
|
|
49
|
+
pdf2zugferd = "pdf2zugferd.cli:main"
|
|
50
|
+
|
|
51
|
+
[tool.ruff]
|
|
52
|
+
line-length = 88
|
|
53
|
+
target-version = "py312"
|
|
54
|
+
|
|
55
|
+
[tool.ruff.lint]
|
|
56
|
+
select = ["E", "F", "I", "B", "UP", "S", "SIM", "RUF"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint.per-file-ignores]
|
|
59
|
+
"tests/*" = ["S101", "S603"]
|
|
60
|
+
|
|
61
|
+
[tool.pytest.ini_options]
|
|
62
|
+
testpaths = ["tests"]
|
|
63
|
+
addopts = "--cov=pdf2zugferd --cov-report=term-missing"
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Command line entry point."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .config import ConfigError, load_config
|
|
11
|
+
from .extract import ExtractionError, extract_invoice
|
|
12
|
+
from .zugferd import build_xml, embed
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
parser = argparse.ArgumentParser(
|
|
17
|
+
prog="pdf2zugferd",
|
|
18
|
+
description="Convert an invoice PDF into a ZUGFeRD (EN 16931) PDF.",
|
|
19
|
+
)
|
|
20
|
+
parser.add_argument("pdf", type=Path, help="input invoice PDF")
|
|
21
|
+
parser.add_argument(
|
|
22
|
+
"-c", "--config", type=Path, required=True, help="seller TOML config"
|
|
23
|
+
)
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"-o",
|
|
26
|
+
"--output",
|
|
27
|
+
type=Path,
|
|
28
|
+
help="output PDF (default: <input>_zugferd.pdf next to the input)",
|
|
29
|
+
)
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"--xml-only", action="store_true", help="also write the XML next to the output"
|
|
32
|
+
)
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--force", action="store_true", help="overwrite existing output files"
|
|
35
|
+
)
|
|
36
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
37
|
+
return parser
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main(argv: list[str] | None = None) -> int:
|
|
41
|
+
args = build_parser().parse_args(argv)
|
|
42
|
+
pdf: Path = args.pdf
|
|
43
|
+
output: Path = args.output or pdf.with_name(f"{pdf.stem}_zugferd.pdf")
|
|
44
|
+
if output.resolve() == pdf.resolve():
|
|
45
|
+
print("error: output must differ from input", file=sys.stderr)
|
|
46
|
+
return 2
|
|
47
|
+
xml_path = output.with_suffix(".xml")
|
|
48
|
+
targets = [output, xml_path] if args.xml_only else [output]
|
|
49
|
+
existing = [t for t in targets if t.exists()]
|
|
50
|
+
if existing and not args.force:
|
|
51
|
+
print(f"error: {existing[0]} exists (use --force)", file=sys.stderr)
|
|
52
|
+
return 2
|
|
53
|
+
try:
|
|
54
|
+
seller = load_config(args.config)
|
|
55
|
+
invoice = extract_invoice(pdf)
|
|
56
|
+
xml = build_xml(invoice, seller)
|
|
57
|
+
embed(pdf, xml, output)
|
|
58
|
+
if args.xml_only:
|
|
59
|
+
xml_path.write_bytes(xml)
|
|
60
|
+
except (ConfigError, ExtractionError, OSError) as exc:
|
|
61
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
62
|
+
return 1
|
|
63
|
+
print(f"wrote {output}")
|
|
64
|
+
return 0
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Seller configuration loaded from a TOML file kept outside the repository."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import tomllib
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .models import Party
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ConfigError(ValueError):
|
|
13
|
+
"""Raised when the configuration file is missing or incomplete."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class SellerConfig:
|
|
18
|
+
party: Party
|
|
19
|
+
tax_number: str
|
|
20
|
+
iban: str
|
|
21
|
+
bic: str | None
|
|
22
|
+
email: str | None
|
|
23
|
+
phone: str | None
|
|
24
|
+
exemption_reason: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_REQUIRED = ("name", "street", "postcode", "city", "tax_number", "iban")
|
|
28
|
+
_DEFAULT_REASON = (
|
|
29
|
+
"Gemäß § 19 Abs. 1 UStG wird keine Umsatzsteuer als Kleinunternehmer ausgewiesen."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _clean_iban(value: str) -> str:
|
|
34
|
+
iban = "".join(value.split()).upper()
|
|
35
|
+
if not (15 <= len(iban) <= 34) or not iban.isalnum():
|
|
36
|
+
raise ConfigError("seller.iban is not a valid IBAN")
|
|
37
|
+
digits = "".join(str(int(c, 36)) for c in iban[4:] + iban[:4])
|
|
38
|
+
if int(digits) % 97 != 1:
|
|
39
|
+
raise ConfigError("seller.iban has an invalid checksum")
|
|
40
|
+
return iban
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def load_config(path: Path) -> SellerConfig:
|
|
44
|
+
try:
|
|
45
|
+
with path.open("rb") as fh:
|
|
46
|
+
data = tomllib.load(fh)
|
|
47
|
+
except FileNotFoundError as exc:
|
|
48
|
+
raise ConfigError(f"config file not found: {path}") from exc
|
|
49
|
+
except tomllib.TOMLDecodeError as exc:
|
|
50
|
+
raise ConfigError(f"config file is not valid TOML: {exc}") from exc
|
|
51
|
+
|
|
52
|
+
seller = data.get("seller")
|
|
53
|
+
if not isinstance(seller, dict):
|
|
54
|
+
raise ConfigError("config needs a [seller] table")
|
|
55
|
+
missing = [k for k in _REQUIRED if not str(seller.get(k, "")).strip()]
|
|
56
|
+
if missing:
|
|
57
|
+
raise ConfigError(f"seller config is missing: {', '.join(missing)}")
|
|
58
|
+
|
|
59
|
+
return SellerConfig(
|
|
60
|
+
party=Party(
|
|
61
|
+
name=seller["name"],
|
|
62
|
+
street=seller["street"],
|
|
63
|
+
postcode=str(seller["postcode"]),
|
|
64
|
+
city=seller["city"],
|
|
65
|
+
country=seller.get("country", "DE"),
|
|
66
|
+
),
|
|
67
|
+
tax_number=seller["tax_number"],
|
|
68
|
+
iban=_clean_iban(seller["iban"]),
|
|
69
|
+
bic=seller.get("bic"),
|
|
70
|
+
email=seller.get("email"),
|
|
71
|
+
phone=seller.get("phone"),
|
|
72
|
+
exemption_reason=seller.get("exemption_reason", _DEFAULT_REASON),
|
|
73
|
+
)
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Extract invoice data from a text-based PDF produced by an office suite."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from decimal import Decimal, InvalidOperation
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import pdfplumber
|
|
11
|
+
|
|
12
|
+
from .models import Invoice, Line, Party
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ExtractionError(ValueError):
|
|
16
|
+
"""Raised when the PDF does not contain the expected invoice layout."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
_MAX_PAGES = 20
|
|
20
|
+
_MAX_BYTES = 20 * 1024 * 1024 # refuse absurdly large inputs (DoS guard)
|
|
21
|
+
_AMOUNT = r"\d{1,3}(?:\.\d{3})*,\d{2}"
|
|
22
|
+
_LINE_RE = re.compile(
|
|
23
|
+
rf"^(?P<pos>\d+)\s+(?P<name>.+?)\s+(?P<menge>\d+\s+\S+)\s+"
|
|
24
|
+
rf"(?P<qty>\d+(?:,\d+)?)\s+(?P<price>{_AMOUNT})\s+(?P<total>{_AMOUNT})$"
|
|
25
|
+
)
|
|
26
|
+
_SIMPLE_LINE_RE = re.compile(
|
|
27
|
+
rf"^(?P<pos>\d+)\s+(?P<name>.+?)\s+(?P<qty>\d+(?:,\d+)?)\s+(?P<unit>[^\d\s]\S*)\s+"
|
|
28
|
+
rf"(?P<price>{_AMOUNT})\s+(?P<total>{_AMOUNT})$"
|
|
29
|
+
)
|
|
30
|
+
# UN/ECE Rec. 20 codes for the units seen on German invoices.
|
|
31
|
+
_UNIT_CODES = {
|
|
32
|
+
"monat": "MON",
|
|
33
|
+
"monate": "MON",
|
|
34
|
+
"tag": "DAY",
|
|
35
|
+
"tage": "DAY",
|
|
36
|
+
"stunde": "HUR",
|
|
37
|
+
"stunden": "HUR",
|
|
38
|
+
"stück": "C62",
|
|
39
|
+
"stk": "C62",
|
|
40
|
+
}
|
|
41
|
+
_STOP_RE = re.compile(r"^(Betrag\b|Summe\b|Gesamt)")
|
|
42
|
+
_POSTCODE_RE = re.compile(r"^(?P<zip>\d{5})\s+(?P<city>.+)$")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _decimal(text: str) -> Decimal:
|
|
46
|
+
try:
|
|
47
|
+
return Decimal(text.replace(".", "").replace(",", "."))
|
|
48
|
+
except InvalidOperation as exc:
|
|
49
|
+
raise ExtractionError(f"cannot parse amount: {text!r}") from exc
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _field(text: str, label: str) -> str:
|
|
53
|
+
match = re.search(rf"{label}:\s*\n?\s*(\S[^\n]*)", text)
|
|
54
|
+
if not match:
|
|
55
|
+
raise ExtractionError(f"field not found in PDF: {label}")
|
|
56
|
+
return match.group(1).strip()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def read_text(path: Path) -> str:
|
|
60
|
+
try:
|
|
61
|
+
size = path.stat().st_size
|
|
62
|
+
except OSError as exc:
|
|
63
|
+
raise ExtractionError(f"cannot read PDF {path}: {exc}") from exc
|
|
64
|
+
if size > _MAX_BYTES:
|
|
65
|
+
raise ExtractionError(f"PDF is larger than {_MAX_BYTES // 2**20} MiB")
|
|
66
|
+
try:
|
|
67
|
+
with pdfplumber.open(path) as pdf:
|
|
68
|
+
pages = pdf.pages[:_MAX_PAGES]
|
|
69
|
+
text = "\n".join(page.extract_text() or "" for page in pages)
|
|
70
|
+
except Exception as exc: # pdfminer raises many unrelated types
|
|
71
|
+
raise ExtractionError(f"cannot read PDF {path}: {exc}") from exc
|
|
72
|
+
if not text.strip():
|
|
73
|
+
raise ExtractionError(
|
|
74
|
+
"PDF has no text layer (scanned?). Run it through OCR first."
|
|
75
|
+
)
|
|
76
|
+
return text
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _parse_buyer(lines: list[str]) -> Party:
|
|
80
|
+
# Layout: sender line, then salutation+name, street, "PLZ City".
|
|
81
|
+
for idx, line in enumerate(lines):
|
|
82
|
+
match = _POSTCODE_RE.match(line)
|
|
83
|
+
if match and idx >= 3:
|
|
84
|
+
name = re.sub(r"^(Herr|Frau|Firma)\s+", "", lines[idx - 2])
|
|
85
|
+
return Party(
|
|
86
|
+
name=name,
|
|
87
|
+
street=lines[idx - 1],
|
|
88
|
+
postcode=match["zip"],
|
|
89
|
+
city=match["city"],
|
|
90
|
+
)
|
|
91
|
+
raise ExtractionError("buyer address block not found")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _unit_code(match: re.Match[str]) -> str:
|
|
95
|
+
if "unit" not in match.groupdict() or match["unit"] is None:
|
|
96
|
+
return "DAY"
|
|
97
|
+
return _UNIT_CODES.get(match["unit"].lower(), "C62")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _parse_lines(lines: list[str]) -> list[Line]:
|
|
101
|
+
matches: list[tuple[re.Match[str], list[str]]] = []
|
|
102
|
+
for line in lines:
|
|
103
|
+
match = _LINE_RE.match(line) or _SIMPLE_LINE_RE.match(line)
|
|
104
|
+
if match:
|
|
105
|
+
matches.append((match, []))
|
|
106
|
+
elif _STOP_RE.match(line):
|
|
107
|
+
break
|
|
108
|
+
elif matches:
|
|
109
|
+
matches[-1][1].append(line)
|
|
110
|
+
return [
|
|
111
|
+
Line(
|
|
112
|
+
position=m["pos"],
|
|
113
|
+
name=m["name"],
|
|
114
|
+
description=" ".join(extra),
|
|
115
|
+
quantity=_decimal(m["qty"]),
|
|
116
|
+
unit_price=_decimal(m["price"]),
|
|
117
|
+
total=_decimal(m["total"]),
|
|
118
|
+
unit_code=_unit_code(m),
|
|
119
|
+
)
|
|
120
|
+
for m, extra in matches
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def parse_invoice(text: str) -> Invoice:
|
|
125
|
+
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
|
|
126
|
+
try:
|
|
127
|
+
issue = datetime.strptime(_field(text, "Rechnungsdatum"), "%d.%m.%Y").date()
|
|
128
|
+
except ValueError as exc:
|
|
129
|
+
raise ExtractionError(f"invalid invoice date: {exc}") from exc
|
|
130
|
+
|
|
131
|
+
items = _parse_lines(lines)
|
|
132
|
+
if not items:
|
|
133
|
+
raise ExtractionError("no invoice line items found")
|
|
134
|
+
|
|
135
|
+
total_match = re.search(rf"^Betrag\s+({_AMOUNT})\s*€", text, re.MULTILINE)
|
|
136
|
+
if not total_match:
|
|
137
|
+
raise ExtractionError("invoice total ('Betrag') not found")
|
|
138
|
+
total = _decimal(total_match.group(1))
|
|
139
|
+
if sum((i.total for i in items), Decimal(0)) != total:
|
|
140
|
+
raise ExtractionError("line totals do not add up to the invoice total")
|
|
141
|
+
for item in items:
|
|
142
|
+
if item.quantity * item.unit_price != item.total:
|
|
143
|
+
raise ExtractionError(f"line {item.position}: quantity x price != total")
|
|
144
|
+
|
|
145
|
+
days = re.search(r"Zahlungsziel beträgt (\d+) Tage", text)
|
|
146
|
+
return Invoice(
|
|
147
|
+
number=_field(text, "Rechnungsnummer"),
|
|
148
|
+
issue_date=issue,
|
|
149
|
+
customer_number=_field(text, "Kundennummer"),
|
|
150
|
+
buyer=_parse_buyer(lines),
|
|
151
|
+
lines=items,
|
|
152
|
+
total=total,
|
|
153
|
+
payment_days=int(days.group(1)) if days else None,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def extract_invoice(path: Path) -> Invoice:
|
|
158
|
+
return parse_invoice(read_text(path))
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Plain data containers shared between extraction and XML generation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from datetime import date
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class Party:
|
|
12
|
+
name: str
|
|
13
|
+
street: str
|
|
14
|
+
postcode: str
|
|
15
|
+
city: str
|
|
16
|
+
country: str = "DE"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Line:
|
|
21
|
+
position: str
|
|
22
|
+
name: str
|
|
23
|
+
description: str
|
|
24
|
+
quantity: Decimal
|
|
25
|
+
unit_price: Decimal
|
|
26
|
+
total: Decimal
|
|
27
|
+
unit_code: str = "DAY"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Invoice:
|
|
32
|
+
number: str
|
|
33
|
+
issue_date: date
|
|
34
|
+
customer_number: str
|
|
35
|
+
buyer: Party
|
|
36
|
+
lines: list[Line] = field(default_factory=list)
|
|
37
|
+
total: Decimal = Decimal(0)
|
|
38
|
+
payment_days: int | None = None
|
|
File without changes
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Build the ZUGFeRD / Factur-X (EN 16931) XML and embed it into the PDF."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from drafthorse.models.accounting import ApplicableTradeTax
|
|
10
|
+
from drafthorse.models.document import Document
|
|
11
|
+
from drafthorse.models.party import TaxRegistration
|
|
12
|
+
from drafthorse.models.payment import PaymentMeans, PaymentTerms
|
|
13
|
+
from drafthorse.models.tradelines import LineItem
|
|
14
|
+
from drafthorse.pdf import attach_xml
|
|
15
|
+
|
|
16
|
+
from .config import SellerConfig
|
|
17
|
+
from .models import Invoice, Party
|
|
18
|
+
|
|
19
|
+
_GUIDELINE = "urn:cen.eu:en16931:2017"
|
|
20
|
+
_ZERO = Decimal("0.00")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _fill_party(target, party: Party) -> None:
|
|
24
|
+
target.name = party.name
|
|
25
|
+
target.address.line_one = party.street
|
|
26
|
+
target.address.postcode = party.postcode
|
|
27
|
+
target.address.city_name = party.city
|
|
28
|
+
target.address.country_id = party.country
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_xml(invoice: Invoice, seller: SellerConfig) -> bytes:
|
|
32
|
+
doc = Document()
|
|
33
|
+
doc.context.guideline_parameter.id = _GUIDELINE
|
|
34
|
+
doc.header.id = invoice.number
|
|
35
|
+
doc.header.type_code = "380"
|
|
36
|
+
doc.header.issue_date_time = invoice.issue_date
|
|
37
|
+
|
|
38
|
+
for item in invoice.lines:
|
|
39
|
+
line = LineItem()
|
|
40
|
+
line.document.line_id = item.position
|
|
41
|
+
line.product.name = item.name
|
|
42
|
+
if item.description:
|
|
43
|
+
line.product.description = item.description
|
|
44
|
+
line.agreement.net.amount = item.unit_price
|
|
45
|
+
line.delivery.billed_quantity = (item.quantity, item.unit_code)
|
|
46
|
+
line.settlement.trade_tax.type_code = "VAT"
|
|
47
|
+
line.settlement.trade_tax.category_code = "E"
|
|
48
|
+
line.settlement.trade_tax.rate_applicable_percent = _ZERO
|
|
49
|
+
line.settlement.monetary_summation.total_amount = item.total
|
|
50
|
+
doc.trade.items.add(line)
|
|
51
|
+
|
|
52
|
+
_fill_party(doc.trade.agreement.seller, seller.party)
|
|
53
|
+
doc.trade.agreement.seller.tax_registrations.add(
|
|
54
|
+
TaxRegistration(id=("FC", seller.tax_number))
|
|
55
|
+
)
|
|
56
|
+
if seller.email:
|
|
57
|
+
doc.trade.agreement.seller.electronic_address.uri_ID = ("EM", seller.email)
|
|
58
|
+
_fill_party(doc.trade.agreement.buyer, invoice.buyer)
|
|
59
|
+
doc.trade.agreement.buyer.id = invoice.customer_number
|
|
60
|
+
|
|
61
|
+
settlement = doc.trade.settlement
|
|
62
|
+
settlement.currency_code = "EUR"
|
|
63
|
+
means = PaymentMeans()
|
|
64
|
+
means.type_code = "58" # SEPA credit transfer
|
|
65
|
+
means.payee_account.iban = seller.iban
|
|
66
|
+
if seller.bic:
|
|
67
|
+
means.payee_institution.bic = seller.bic
|
|
68
|
+
settlement.payment_means.add(means)
|
|
69
|
+
|
|
70
|
+
tax = ApplicableTradeTax()
|
|
71
|
+
tax.calculated_amount = _ZERO
|
|
72
|
+
tax.basis_amount = invoice.total
|
|
73
|
+
tax.type_code = "VAT"
|
|
74
|
+
tax.category_code = "E"
|
|
75
|
+
tax.exemption_reason = seller.exemption_reason
|
|
76
|
+
tax.rate_applicable_percent = _ZERO
|
|
77
|
+
settlement.trade_tax.add(tax)
|
|
78
|
+
|
|
79
|
+
if invoice.payment_days is not None:
|
|
80
|
+
terms = PaymentTerms()
|
|
81
|
+
terms.due = invoice.issue_date + timedelta(days=invoice.payment_days)
|
|
82
|
+
settlement.terms.add(terms)
|
|
83
|
+
|
|
84
|
+
summation = settlement.monetary_summation
|
|
85
|
+
summation.line_total = invoice.total
|
|
86
|
+
summation.charge_total = _ZERO
|
|
87
|
+
summation.allowance_total = _ZERO
|
|
88
|
+
summation.tax_basis_total = invoice.total
|
|
89
|
+
summation.tax_total = (_ZERO, "EUR")
|
|
90
|
+
summation.grand_total = invoice.total
|
|
91
|
+
summation.due_amount = invoice.total
|
|
92
|
+
|
|
93
|
+
return doc.serialize(schema="FACTUR-X_EN16931")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def embed(pdf_path: Path, xml: bytes, output: Path) -> None:
|
|
97
|
+
result = attach_xml(pdf_path.read_bytes(), xml, level="EN 16931")
|
|
98
|
+
output.write_bytes(result)
|