acroformer 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: acroformer
|
|
3
|
+
Version: 1.1.1
|
|
4
|
+
Summary: Turn flat PDF forms into fillable AcroForms, with every field named after its printed label.
|
|
5
|
+
Author: Fury Oktria Putra
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/furyoktria/acroformer
|
|
8
|
+
Keywords: pdf,acroform,pdf-forms,fillable-pdf,pymupdf,form-automation
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Office/Business
|
|
12
|
+
Classifier: Topic :: Text Processing
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: pymupdf>=1.24
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# acroformer
|
|
20
|
+
|
|
21
|
+
Turn flat PDF forms into fillable **AcroForms**. acroformer finds the printed
|
|
22
|
+
boxes, date cells, checkboxes and dotted lines, puts real form fields on top of
|
|
23
|
+
the untouched pages, and names every field after its printed label.
|
|
24
|
+
|
|
25
|
+
<a href="https://furyoktria.github.io/explainers/acroformer/"><img src="docs/explainer-poster.jpg" width="100%" alt="Watch acroformer in three minutes: what it does, a map of the code, the life of a page, the core ideas and a real run"></a>
|
|
26
|
+
|
|
27
|
+
**[Watch the three-minute tour](https://furyoktria.github.io/explainers/acroformer/)**: what it does, a map of the code, the life of a page, the core ideas and a real run on the sample form.
|
|
28
|
+
|
|
29
|
+
Many institutional forms (bank account openings, KYC packets, government
|
|
30
|
+
forms) are shipped as flat PDFs: the boxes are printed, but nothing can be
|
|
31
|
+
filled. The output of acroformer looks identical to the source and works in
|
|
32
|
+
Adobe Acrobat and Reader, macOS Preview, Chrome, or from code (PyMuPDF, pypdf,
|
|
33
|
+
pdftk).
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install git+https://github.com/furyoktria/acroformer
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Python 3.9 or newer. PyMuPDF is installed with it.
|
|
42
|
+
|
|
43
|
+
## Try it on the sample form
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
acroformer examples/sample-form.pdf --debug-overlay check.pdf
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
<img src="docs/demo.gif" width="640" alt="The sample form: detected fields are outlined one by one, then filled with example values">
|
|
50
|
+
|
|
51
|
+
[`examples/sample-form.pdf`](examples/sample-form.pdf) is a fictional
|
|
52
|
+
bilingual form. [`sample-form-fillable.pdf`](examples/sample-form-fillable.pdf)
|
|
53
|
+
is what acroformer makes of it, and
|
|
54
|
+
[`sample-form-fields.json`](examples/sample-form-fields.json) is the field map.
|
|
55
|
+
|
|
56
|
+
## What it detects
|
|
57
|
+
|
|
58
|
+
| Printed geometry | Becomes |
|
|
59
|
+
|---|---|
|
|
60
|
+
| Rows of character boxes (`\|_\|_\|_\|...`) | One text field. Short runs such as dates and postal codes become **comb** fields (one character per box); long runs such as names become one free-flowing text field |
|
|
61
|
+
| Small square boxes with a label to the right | Checkbox |
|
|
62
|
+
| Single boxes separated by a printed `/` or `-` (dd / mm / yyyy) | Separate text boxes named `..._dd`, `..._mm`, `..._yyyy` |
|
|
63
|
+
| Dotted leaders (`.......`) and underscore runs | Text field |
|
|
64
|
+
| Drawn write-on lines (`Lainnya/Others ____`) | Text field |
|
|
65
|
+
| Empty bordered table cells and ruled table rows | Text field |
|
|
66
|
+
|
|
67
|
+
A few rules keep the output clean: checkboxes that contain pre-printed text are
|
|
68
|
+
skipped, fields inside shaded header cells (bank-use areas) are suppressed, and
|
|
69
|
+
overlapping candidates are merged.
|
|
70
|
+
|
|
71
|
+
## Field naming
|
|
72
|
+
|
|
73
|
+
Fields are named after the printed label next to them, so your integration code
|
|
74
|
+
stays readable. From the sample form:
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
p01_nama_lengkap
|
|
78
|
+
p01_tempat_tanggal_lahir_dd
|
|
79
|
+
p01_tempat_tanggal_lahir_mm
|
|
80
|
+
p01_tempat_tanggal_lahir_yyyy
|
|
81
|
+
p01_kode_pos
|
|
82
|
+
p01_alamat
|
|
83
|
+
p01_alamat_2 <- continuation line keeps the label
|
|
84
|
+
p01_reguler <- checkbox, labeled by the text to its right
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Checkboxes take the label to their right, text fields the label to their left
|
|
88
|
+
(falling back to the label line above). Bilingual labels such as
|
|
89
|
+
"Nama Lengkap / Full Name" keep the first part. The `pNN_` page prefix keeps
|
|
90
|
+
names unique across pages, and repeats get `_2`, `_3` and so on.
|
|
91
|
+
|
|
92
|
+
## Usage
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
acroformer input.pdf # writes input_acroform.pdf
|
|
96
|
+
acroformer input.pdf -o fillable.pdf
|
|
97
|
+
acroformer input.pdf --map fields.json # JSON list of all fields
|
|
98
|
+
acroformer input.pdf --debug-overlay check.pdf
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`--map` writes `[{name, page, type, maxlen, rect}, ...]`, which is handy for
|
|
102
|
+
building auto-fill integrations.
|
|
103
|
+
|
|
104
|
+
`--debug-overlay` writes a copy with colored outlines (red = text, blue = comb,
|
|
105
|
+
green = checkbox) so you can check the detection page by page.
|
|
106
|
+
|
|
107
|
+
Without installing, `python acroformer.py input.pdf` works the same way.
|
|
108
|
+
|
|
109
|
+
### Filling a form
|
|
110
|
+
|
|
111
|
+
Put the values in a JSON file, with the field names from `--map`:
|
|
112
|
+
|
|
113
|
+
```json
|
|
114
|
+
{
|
|
115
|
+
"p01_nama_lengkap": "Siti Nur'aini Wulandari",
|
|
116
|
+
"p01_kode_pos": "12730",
|
|
117
|
+
"p01_reguler": true
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
acroformer form.pdf --fill values.json # writes form_filled.pdf
|
|
123
|
+
acroformer form.pdf --fill values.json -o out.pdf
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The input can be the flat form or a file that is already fillable. A flat form
|
|
127
|
+
is converted first, so one command goes from the printed form to the filled
|
|
128
|
+
one. Checkboxes take `true` or `false`, text fields take a string or a number.
|
|
129
|
+
|
|
130
|
+
acroformer checks every value before it writes. A name that does not exist
|
|
131
|
+
(with the nearest real name as a hint), a value too long for its boxes, or the
|
|
132
|
+
wrong type stops the run with exit code 2, and no file is written:
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
error: p01_nama_lengkp: no such field (did you mean p01_nama_lengkap?)
|
|
136
|
+
error: p01_kode_pos: '127301' has 6 characters, the field holds 5
|
|
137
|
+
2 problem(s). No file was written.
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Filling from code
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
import fitz # PyMuPDF
|
|
144
|
+
|
|
145
|
+
values = {"p01_kode_pos": "12730", "p01_pekerjaan": "Product Manager", "p01_reguler": True}
|
|
146
|
+
|
|
147
|
+
doc = fitz.open("examples/sample-form-fillable.pdf")
|
|
148
|
+
for w in doc[0].widgets():
|
|
149
|
+
if w.field_name in values:
|
|
150
|
+
v = values[w.field_name]
|
|
151
|
+
w.field_value = w.on_state() if v is True else v
|
|
152
|
+
w.update()
|
|
153
|
+
doc.save("filled.pdf")
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## How it works
|
|
157
|
+
|
|
158
|
+
The detector reads the page's vector drawings (`page.get_drawings()`) and text
|
|
159
|
+
(`page.get_text("rawdict")`), then classifies the geometry:
|
|
160
|
+
|
|
161
|
+
1. **Vertical tick marks** are clustered into rows and split into runs at
|
|
162
|
+
larger gaps and at printed glyphs, so `dd / mm / yyyy` splits into three.
|
|
163
|
+
2. Runs of 3 or more evenly spaced ticks become comb or text fields. Tick pairs
|
|
164
|
+
are told apart by context: a `/` or `-` next to them means a date cell, and
|
|
165
|
+
a letter or digit right after them means a checkbox. On many forms a
|
|
166
|
+
checkbox and a 2-digit date box are geometrically identical.
|
|
167
|
+
3. Dotted leaders and underscores are found per character, so labels and
|
|
168
|
+
fillers mixed in one text span still work.
|
|
169
|
+
4. Candidates are deduplicated, and widgets are added on top of the original,
|
|
170
|
+
untouched pages.
|
|
171
|
+
|
|
172
|
+
Tested on a 67-page Indonesian account-opening packet with 667 fields. The
|
|
173
|
+
rules are generic, not tuned to one form.
|
|
174
|
+
|
|
175
|
+
## Tests
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
python3 tests/e2e.py
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
One end-to-end run of the command line on the sample form. It reads the result
|
|
182
|
+
back with PyMuPDF and pypdf, and checks that the values are drawn on the page.
|
|
183
|
+
The last run is in [`tests/e2e-report.md`](tests/e2e-report.md).
|
|
184
|
+
|
|
185
|
+
## Limitations
|
|
186
|
+
|
|
187
|
+
- Wet-signature areas are left without fields on purpose.
|
|
188
|
+
- Radio-button groups are not inferred: exclusive choices come out as
|
|
189
|
+
independent checkboxes.
|
|
190
|
+
- Detection is heuristic. Always look at `--debug-overlay` on a new form.
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
acroformer.py,sha256=gvyuPHSSVk9QjhBEg9WRPXvD4o-r4J9wgIsd1x82vn0,25456
|
|
2
|
+
acroformer-1.1.1.dist-info/licenses/LICENSE,sha256=gaWEM2Ne2oWFIQ_tzC5Yk2dhr1uSyqwFSunyzlJedXE,1074
|
|
3
|
+
acroformer-1.1.1.dist-info/METADATA,sha256=5q5KO3yPSJmPmFj0TqreaTuqLkKEBsMO8sc0UEXLGAA,7222
|
|
4
|
+
acroformer-1.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
acroformer-1.1.1.dist-info/entry_points.txt,sha256=fRqb4umsVvLv2lUkfqTeHnrZlnC-VVTZdnlJfP5vWEI,47
|
|
6
|
+
acroformer-1.1.1.dist-info/top_level.txt,sha256=p4QeaN_WhjNPvZr8Hg8YLQA64Ks6O7v9E4sIR7vVCmA,11
|
|
7
|
+
acroformer-1.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fury Oktria Putra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
acroformer
|
acroformer.py
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""acroformer: turn flat (non-fillable) PDF forms into fillable AcroForms.
|
|
3
|
+
|
|
4
|
+
Detects drawn form geometry (character boxes, checkboxes, dotted leaders,
|
|
5
|
+
write-on lines, empty table cells) and overlays real AcroForm widgets on the
|
|
6
|
+
original pages, so the output looks 100% identical to the source PDF.
|
|
7
|
+
|
|
8
|
+
Field naming: each widget is named from the printed label next to it,
|
|
9
|
+
e.g. `p02_nama_depan`, `p03_pekerjaan_2` — page prefix guarantees uniqueness.
|
|
10
|
+
|
|
11
|
+
Usage:
|
|
12
|
+
python acroformer.py input.pdf [-o output.pdf] [--debug-overlay overlay.pdf]
|
|
13
|
+
python acroformer.py input.pdf --fill values.json [-o filled.pdf]
|
|
14
|
+
|
|
15
|
+
Requires: PyMuPDF (pip install pymupdf)
|
|
16
|
+
"""
|
|
17
|
+
import argparse
|
|
18
|
+
import difflib
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import sys
|
|
23
|
+
import unicodedata
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
import pymupdf as fitz # the name PyMuPDF uses from 1.24.3
|
|
27
|
+
except ImportError: # older PyMuPDF
|
|
28
|
+
import fitz
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ---------------------------------------------------------------- helpers
|
|
32
|
+
|
|
33
|
+
def cluster_rows(items, ykey, tol=2.5):
|
|
34
|
+
"""Group items whose y-centers lie within `tol` points."""
|
|
35
|
+
rows = []
|
|
36
|
+
for it in sorted(items, key=ykey):
|
|
37
|
+
for row in rows:
|
|
38
|
+
if abs(ykey(it) - row["y"]) <= tol:
|
|
39
|
+
row["items"].append(it)
|
|
40
|
+
break
|
|
41
|
+
else:
|
|
42
|
+
rows.append({"y": ykey(it), "items": [it]})
|
|
43
|
+
return rows
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def slugify(text, maxlen=40):
|
|
47
|
+
text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
|
|
48
|
+
text = re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")
|
|
49
|
+
text = re.sub(r"_+", "_", text)
|
|
50
|
+
return text[:maxlen].rstrip("_")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def label_for(kind, rect, words):
|
|
54
|
+
"""Derive a human label for a field from nearby printed text.
|
|
55
|
+
|
|
56
|
+
Checkboxes are labeled by the words to their right ("[x] Saham / Stock"),
|
|
57
|
+
text fields by the words to their left ("Nama Depan / First Name : [___]"),
|
|
58
|
+
falling back to the closest label line up-left of the field. Bilingual
|
|
59
|
+
labels are cut at "/" keeping the first (usually Indonesian) part.
|
|
60
|
+
"""
|
|
61
|
+
yc = (rect.y0 + rect.y1) / 2
|
|
62
|
+
|
|
63
|
+
def same_line(w):
|
|
64
|
+
return w[1] - 3 < yc < w[3] + 3
|
|
65
|
+
|
|
66
|
+
def firstpart(label):
|
|
67
|
+
label = label.strip(" :.")
|
|
68
|
+
return label.split("/")[0] if re.search(r"[a-zA-Z]", label) else ""
|
|
69
|
+
|
|
70
|
+
if kind == "checkbox":
|
|
71
|
+
right = sorted([w for w in words if same_line(w) and w[0] >= rect.x1 - 1
|
|
72
|
+
and w[0] - rect.x1 <= 80], key=lambda w: w[0])
|
|
73
|
+
parts, prev = [], rect.x1
|
|
74
|
+
for w in right:
|
|
75
|
+
if w[0] - prev > 12 or w[4].startswith("/"):
|
|
76
|
+
break
|
|
77
|
+
if "/" in w[4]:
|
|
78
|
+
parts.append(w[4].split("/")[0])
|
|
79
|
+
break
|
|
80
|
+
parts.append(w[4])
|
|
81
|
+
prev = w[2]
|
|
82
|
+
return " ".join(parts)
|
|
83
|
+
|
|
84
|
+
# 1) words on the same line, left of the field ("label : [___]").
|
|
85
|
+
# Cluster them by horizontal gaps and take the nearest cluster that
|
|
86
|
+
# actually contains letters (skipping lone ":" or "/" separators).
|
|
87
|
+
left = sorted([w for w in words if same_line(w) and w[2] <= rect.x0 + 2
|
|
88
|
+
and rect.x0 - w[2] <= 320], key=lambda w: w[0])
|
|
89
|
+
clusters, cur = [], []
|
|
90
|
+
for w in left:
|
|
91
|
+
if cur and w[0] - cur[-1][2] > 14:
|
|
92
|
+
clusters.append(cur)
|
|
93
|
+
cur = []
|
|
94
|
+
cur.append(w)
|
|
95
|
+
if cur:
|
|
96
|
+
clusters.append(cur)
|
|
97
|
+
for cl in reversed(clusters):
|
|
98
|
+
label = firstpart(" ".join(w[4] for w in cl))
|
|
99
|
+
if label:
|
|
100
|
+
return label
|
|
101
|
+
|
|
102
|
+
# 2) label block up-left of the field (multi-line labels)
|
|
103
|
+
band = [w for w in words if w[2] <= rect.x0 + 2 and rect.x0 - w[2] <= 320
|
|
104
|
+
and w[3] > rect.y0 - 6 and w[1] < rect.y1 + 2]
|
|
105
|
+
if band:
|
|
106
|
+
top = min(w[1] for w in band)
|
|
107
|
+
line = sorted([w for w in band if w[1] < top + 6], key=lambda w: w[0])
|
|
108
|
+
label = firstpart(" ".join(w[4] for w in line))
|
|
109
|
+
if label:
|
|
110
|
+
return label
|
|
111
|
+
|
|
112
|
+
# 3) label line directly above, starting near the field's left edge
|
|
113
|
+
above = [w for w in words if rect.y0 - 20 < w[3] <= rect.y0 + 2
|
|
114
|
+
and w[0] < rect.x1 and w[2] > rect.x0 - 30]
|
|
115
|
+
if above and min(w[0] for w in above) > rect.x0 - 50:
|
|
116
|
+
line_y = max(w[3] for w in above)
|
|
117
|
+
line = sorted([w for w in above if w[3] > line_y - 6], key=lambda w: w[0])
|
|
118
|
+
return firstpart(" ".join(w[4] for w in line))
|
|
119
|
+
return ""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------------------------------------------------------- detection
|
|
123
|
+
|
|
124
|
+
def detect_fields(page):
|
|
125
|
+
"""Return [(kind, rect)] for one page. kind: 'text' | 'checkbox' | 'combN'."""
|
|
126
|
+
ticks, boxes = [], []
|
|
127
|
+
for d in page.get_drawings():
|
|
128
|
+
for it in d["items"]:
|
|
129
|
+
if it[0] == "re":
|
|
130
|
+
r = it[1]
|
|
131
|
+
w, h = r.width, r.height
|
|
132
|
+
if w <= 2.2 and 5 <= h <= 24:
|
|
133
|
+
ticks.append(fitz.Rect(r))
|
|
134
|
+
elif 5 <= w <= 22 and 5 <= h <= 20:
|
|
135
|
+
boxes.append(fitz.Rect(r))
|
|
136
|
+
elif it[0] == "l":
|
|
137
|
+
p1, p2 = it[1], it[2]
|
|
138
|
+
if abs(p1.x - p2.x) < 1.2 and 5 <= abs(p1.y - p2.y) <= 24:
|
|
139
|
+
ticks.append(fitz.Rect(min(p1.x, p2.x), min(p1.y, p2.y),
|
|
140
|
+
max(p1.x, p2.x) + 0.7, max(p1.y, p2.y)))
|
|
141
|
+
|
|
142
|
+
# dedupe ticks drawn twice (as 're' and as 'l')
|
|
143
|
+
uniq = []
|
|
144
|
+
for t in ticks:
|
|
145
|
+
if not any(abs(t.x0 - u.x0) < 3.0 and abs(t.y0 - u.y0) < 2.5
|
|
146
|
+
and abs(t.y1 - u.y1) < 2.5 for u in uniq):
|
|
147
|
+
uniq.append(t)
|
|
148
|
+
ticks = uniq
|
|
149
|
+
|
|
150
|
+
fields = []
|
|
151
|
+
words = page.get_text("words")
|
|
152
|
+
glyphs = []
|
|
153
|
+
for blk in page.get_text("rawdict")["blocks"]:
|
|
154
|
+
if blk["type"] != 0:
|
|
155
|
+
continue
|
|
156
|
+
for line in blk["lines"]:
|
|
157
|
+
for span in line["spans"]:
|
|
158
|
+
for c in span["chars"]:
|
|
159
|
+
if c["c"].strip():
|
|
160
|
+
glyphs.append((c["c"], c["bbox"]))
|
|
161
|
+
|
|
162
|
+
def classify_small(box, y0, y1):
|
|
163
|
+
"""Checkbox-size box: '/' or '-' neighbor => date cell (text);
|
|
164
|
+
a letter/digit label immediately right => checkbox."""
|
|
165
|
+
sep = lab = False
|
|
166
|
+
for gc, (gx0, gy0, gx1, gy1) in glyphs:
|
|
167
|
+
gcy = (gy0 + gy1) / 2
|
|
168
|
+
if not (y0 - 2 < gcy < y1 + 2):
|
|
169
|
+
continue
|
|
170
|
+
near_l = 0 <= box.x0 - gx1 <= 10
|
|
171
|
+
near_r = 0 <= gx0 - box.x1 <= 10
|
|
172
|
+
if gc in "/-" and (near_l or near_r):
|
|
173
|
+
sep = True
|
|
174
|
+
if gc.isalnum() and near_r:
|
|
175
|
+
lab = True
|
|
176
|
+
return "text" if (sep or not lab) else "checkbox"
|
|
177
|
+
|
|
178
|
+
# --- runs of vertical ticks: comb rows, single cells, checkboxes ---
|
|
179
|
+
for row in cluster_rows(ticks, lambda r: (r.y0 + r.y1) / 2):
|
|
180
|
+
xs = sorted(row["items"], key=lambda r: r.x0)
|
|
181
|
+
yb0 = min(t.y0 for t in xs)
|
|
182
|
+
yb1 = max(t.y1 for t in xs)
|
|
183
|
+
|
|
184
|
+
def glyph_between(a, b):
|
|
185
|
+
for _gc, (gx0, gy0, gx1, gy1) in glyphs:
|
|
186
|
+
cx = (gx0 + gx1) / 2
|
|
187
|
+
cy = (gy0 + gy1) / 2
|
|
188
|
+
if a.x1 + 0.5 < cx < b.x0 - 0.5 and yb0 - 1 < cy < yb1 + 1:
|
|
189
|
+
return True
|
|
190
|
+
return False
|
|
191
|
+
|
|
192
|
+
runs, run = [], [xs[0]]
|
|
193
|
+
for a, b in zip(xs, xs[1:]):
|
|
194
|
+
gap = b.x0 - a.x0
|
|
195
|
+
h = max(a.y1 - a.y0, b.y1 - b.y0)
|
|
196
|
+
limit = max(2.4 * h, 30) if len(run) >= 2 else 1.8 * h + 6
|
|
197
|
+
if gap > limit or glyph_between(a, b):
|
|
198
|
+
runs.append(run)
|
|
199
|
+
run = [b]
|
|
200
|
+
else:
|
|
201
|
+
run.append(b)
|
|
202
|
+
runs.append(run)
|
|
203
|
+
|
|
204
|
+
for rn in runs:
|
|
205
|
+
y0 = min(t.y0 for t in rn)
|
|
206
|
+
y1 = max(t.y1 for t in rn)
|
|
207
|
+
h = y1 - y0
|
|
208
|
+
if len(rn) == 2:
|
|
209
|
+
gap = rn[1].x0 - rn[0].x1
|
|
210
|
+
if gap < 5:
|
|
211
|
+
continue
|
|
212
|
+
box = fitz.Rect(rn[0].x0, y0, rn[1].x1, y1)
|
|
213
|
+
if gap <= 20 and gap <= 1.7 * h and classify_small(box, y0, y1) == "checkbox":
|
|
214
|
+
fields.append(("checkbox", box))
|
|
215
|
+
elif gap <= 260:
|
|
216
|
+
fields.append(("text", fitz.Rect(rn[0].x1 + 0.8, y0 + 0.5,
|
|
217
|
+
rn[1].x0 - 0.8, y1 - 0.5)))
|
|
218
|
+
elif len(rn) >= 3:
|
|
219
|
+
cells = len(rn) - 1
|
|
220
|
+
wtot = rn[-1].x1 - rn[0].x0
|
|
221
|
+
cws = [rn[i + 1].x0 - rn[i].x0 for i in range(len(rn) - 1)]
|
|
222
|
+
uniform = max(cws) / max(min(cws), 0.1) <= 1.9
|
|
223
|
+
if wtot < 24:
|
|
224
|
+
box = fitz.Rect(rn[0].x0, y0, rn[-1].x1, y1)
|
|
225
|
+
if classify_small(box, y0, y1) == "checkbox":
|
|
226
|
+
fields.append(("checkbox", box))
|
|
227
|
+
else:
|
|
228
|
+
fields.append(("text", fitz.Rect(box.x0 + 1, y0 + 0.5,
|
|
229
|
+
box.x1 - 1, y1 - 0.5)))
|
|
230
|
+
elif not uniform:
|
|
231
|
+
# mixed run: close tick pairs = checkboxes, drop strays
|
|
232
|
+
i = 0
|
|
233
|
+
while i < len(rn) - 1:
|
|
234
|
+
gap = rn[i + 1].x0 - rn[i].x1
|
|
235
|
+
if 5 <= gap <= 1.8 * (y1 - y0):
|
|
236
|
+
fields.append(("checkbox", fitz.Rect(rn[i].x0, y0,
|
|
237
|
+
rn[i + 1].x1, y1)))
|
|
238
|
+
i += 2
|
|
239
|
+
else:
|
|
240
|
+
i += 1
|
|
241
|
+
elif cells <= 12:
|
|
242
|
+
fields.append(("comb%d" % cells,
|
|
243
|
+
fitz.Rect(rn[0].x0, y0 + 0.4, rn[-1].x1, y1 - 0.4)))
|
|
244
|
+
else:
|
|
245
|
+
rect = fitz.Rect(rn[0].x0 + 1.2, y0 + 0.6, rn[-1].x1 - 1.2, y1 - 0.6)
|
|
246
|
+
if rect.width >= 15:
|
|
247
|
+
fields.append(("text", rect))
|
|
248
|
+
|
|
249
|
+
# --- standalone small rects: contiguous runs => comb/text, isolated => checkbox ---
|
|
250
|
+
for row in cluster_rows(boxes, lambda r: (r.y0 + r.y1) / 2):
|
|
251
|
+
xs = sorted(row["items"], key=lambda r: r.x0)
|
|
252
|
+
runs, run = [], [xs[0]]
|
|
253
|
+
for a, b in zip(xs, xs[1:]):
|
|
254
|
+
if (b.x0 - a.x1) <= 2.0:
|
|
255
|
+
run.append(b)
|
|
256
|
+
else:
|
|
257
|
+
runs.append(run)
|
|
258
|
+
run = [b]
|
|
259
|
+
runs.append(run)
|
|
260
|
+
for rn in runs:
|
|
261
|
+
y0 = min(t.y0 for t in rn)
|
|
262
|
+
y1 = max(t.y1 for t in rn)
|
|
263
|
+
ws = [t.width for t in rn]
|
|
264
|
+
uniform_r = max(ws) / max(min(ws), 0.1) <= 1.6
|
|
265
|
+
if len(rn) >= 3 and uniform_r and (rn[-1].x1 - rn[0].x0) >= 24:
|
|
266
|
+
if len(rn) <= 12:
|
|
267
|
+
fields.append(("comb%d" % len(rn),
|
|
268
|
+
fitz.Rect(rn[0].x0, y0 + 0.4, rn[-1].x1, y1 - 0.4)))
|
|
269
|
+
else:
|
|
270
|
+
fields.append(("text", fitz.Rect(rn[0].x0 + 1, y0 + 0.5,
|
|
271
|
+
rn[-1].x1 - 1, y1 - 0.5)))
|
|
272
|
+
elif len(rn) >= 3 and (rn[-1].x1 - rn[0].x0) < 24:
|
|
273
|
+
box = fitz.Rect(rn[0].x0, y0, rn[-1].x1, y1)
|
|
274
|
+
if classify_small(box, y0, y1) == "checkbox":
|
|
275
|
+
fields.append(("checkbox", box))
|
|
276
|
+
else:
|
|
277
|
+
fields.append(("text", fitz.Rect(box.x0 + 1, y0 + 0.5,
|
|
278
|
+
box.x1 - 1, y1 - 0.5)))
|
|
279
|
+
else:
|
|
280
|
+
for t in rn:
|
|
281
|
+
if t.width >= 5:
|
|
282
|
+
fields.append(("checkbox", t))
|
|
283
|
+
|
|
284
|
+
# --- dotted-leader / underscore runs (char-level, handles mixed spans) ---
|
|
285
|
+
for blk in page.get_text("rawdict")["blocks"]:
|
|
286
|
+
if blk["type"] != 0:
|
|
287
|
+
continue
|
|
288
|
+
for line in blk["lines"]:
|
|
289
|
+
for span in line["spans"]:
|
|
290
|
+
run = []
|
|
291
|
+
|
|
292
|
+
def flush(run):
|
|
293
|
+
if len(run) >= 4:
|
|
294
|
+
x0 = run[0]["bbox"][0]
|
|
295
|
+
x1 = run[-1]["bbox"][2]
|
|
296
|
+
ry1 = max(c["bbox"][3] for c in run)
|
|
297
|
+
ry0 = min(c["bbox"][1] for c in run)
|
|
298
|
+
hgt = max(ry1 - ry0, 11)
|
|
299
|
+
if x1 - x0 >= 25:
|
|
300
|
+
fields.append(("text", fitz.Rect(x0, ry1 - hgt, x1, ry1)))
|
|
301
|
+
|
|
302
|
+
for c in span["chars"]:
|
|
303
|
+
if c["c"] in "._…":
|
|
304
|
+
run.append(c)
|
|
305
|
+
elif c["c"] != " ":
|
|
306
|
+
flush(run)
|
|
307
|
+
run = []
|
|
308
|
+
flush(run)
|
|
309
|
+
|
|
310
|
+
# --- empty bordered table cells ---
|
|
311
|
+
for d in page.get_drawings():
|
|
312
|
+
if d.get("fill") and sum(d["fill"]) < 2.0:
|
|
313
|
+
continue
|
|
314
|
+
col = d.get("color")
|
|
315
|
+
if col is None or sum(col) > 1.5:
|
|
316
|
+
continue
|
|
317
|
+
for it in d["items"]:
|
|
318
|
+
if it[0] != "re":
|
|
319
|
+
continue
|
|
320
|
+
r = it[1]
|
|
321
|
+
if 60 <= r.width <= 420 and 13 <= r.height <= 32:
|
|
322
|
+
inner = fitz.Rect(r.x0 + 2, r.y0 + 2, r.x1 - 2, r.y1 - 2)
|
|
323
|
+
if any(fitz.Rect(w[:4]).intersects(inner) for w in words):
|
|
324
|
+
continue
|
|
325
|
+
fields.append(("text", fitz.Rect(r.x0 + 2, r.y0 + 1.5, r.x1 - 2, r.y1 - 1.5)))
|
|
326
|
+
|
|
327
|
+
# --- drawn write-on lines (e.g. "Lainnya/Others ____") ---
|
|
328
|
+
for d in page.get_drawings():
|
|
329
|
+
for it in d["items"]:
|
|
330
|
+
r = None
|
|
331
|
+
if it[0] == "re" and it[1].height <= 1.5 and 28 <= it[1].width <= 260:
|
|
332
|
+
r = it[1]
|
|
333
|
+
elif it[0] == "l":
|
|
334
|
+
p1, p2 = it[1], it[2]
|
|
335
|
+
if abs(p1.y - p2.y) < 1 and 28 <= abs(p1.x - p2.x) <= 260:
|
|
336
|
+
r = fitz.Rect(min(p1.x, p2.x), min(p1.y, p2.y),
|
|
337
|
+
max(p1.x, p2.x), max(p1.y, p2.y) + 0.5)
|
|
338
|
+
if r is None:
|
|
339
|
+
continue
|
|
340
|
+
above = fitz.Rect(r.x0 + 6, r.y0 - 9.0, r.x1 - 2, r.y0 - 0.5)
|
|
341
|
+
if any(fitz.Rect(w[:4]).intersects(above) for w in words):
|
|
342
|
+
continue # it's an underline, not a write-on line
|
|
343
|
+
hasl = any(abs(w[3] - r.y1) < 6 and 0 <= r.x0 - w[2] < 45 for w in words)
|
|
344
|
+
hasr = any(abs(w[3] - r.y1) < 6 and 0 <= w[0] - r.x1 < 45 for w in words)
|
|
345
|
+
if not (hasl or hasr):
|
|
346
|
+
continue
|
|
347
|
+
fields.append(("text", fitz.Rect(r.x0, r.y0 - 10.5, r.x1, r.y0 + 0.5)))
|
|
348
|
+
|
|
349
|
+
# --- stacked horizontal rules => table-row text fields ---
|
|
350
|
+
hrules = []
|
|
351
|
+
for d in page.get_drawings():
|
|
352
|
+
for it in d["items"]:
|
|
353
|
+
r = None
|
|
354
|
+
if it[0] == "re" and it[1].height <= 1.2 and it[1].width >= 60:
|
|
355
|
+
r = it[1]
|
|
356
|
+
elif it[0] == "l":
|
|
357
|
+
p1, p2 = it[1], it[2]
|
|
358
|
+
if abs(p1.y - p2.y) < 1 and abs(p1.x - p2.x) >= 60:
|
|
359
|
+
r = fitz.Rect(min(p1.x, p2.x), p1.y, max(p1.x, p2.x), p1.y + 0.5)
|
|
360
|
+
if r is not None:
|
|
361
|
+
hrules.append(r)
|
|
362
|
+
cols = {}
|
|
363
|
+
for r in hrules:
|
|
364
|
+
cols.setdefault((round(r.x0 / 3), round(r.width / 3)), []).append(r)
|
|
365
|
+
for rs in cols.values():
|
|
366
|
+
rs = sorted(rs, key=lambda r: r.y0)
|
|
367
|
+
ys = []
|
|
368
|
+
for r in rs:
|
|
369
|
+
if not ys or r.y0 - ys[-1].y0 > 3:
|
|
370
|
+
ys.append(r)
|
|
371
|
+
if len(ys) < 3:
|
|
372
|
+
continue
|
|
373
|
+
for a, b in zip(ys, ys[1:]):
|
|
374
|
+
gap = b.y0 - a.y1
|
|
375
|
+
if not (9 <= gap <= 26):
|
|
376
|
+
continue
|
|
377
|
+
cell = fitz.Rect(a.x0 + 2, a.y1 + 1, a.x1 - 2, b.y0 - 1)
|
|
378
|
+
inner = fitz.Rect(cell.x0 + 2, cell.y0 + 2, cell.x1 - 2, cell.y1 - 2)
|
|
379
|
+
if any(fitz.Rect(w[:4]).intersects(inner) for w in words):
|
|
380
|
+
continue
|
|
381
|
+
fields.append(("text", cell))
|
|
382
|
+
|
|
383
|
+
# --- suppress fields inside shaded (gray) header cells ---
|
|
384
|
+
shaded = []
|
|
385
|
+
for d in page.get_drawings():
|
|
386
|
+
f = d.get("fill")
|
|
387
|
+
if f and 0.2 < sum(f) < 2.5:
|
|
388
|
+
r = d["rect"]
|
|
389
|
+
if r.width > 30 and r.height > 8:
|
|
390
|
+
shaded.append(r)
|
|
391
|
+
|
|
392
|
+
def in_shade(r):
|
|
393
|
+
c = fitz.Point((r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2)
|
|
394
|
+
return any(s.contains(c) for s in shaded)
|
|
395
|
+
|
|
396
|
+
fields = [(k, r) for k, r in fields if not in_shade(r)]
|
|
397
|
+
|
|
398
|
+
# --- checkboxes must be empty inside (no pre-printed glyphs) ---
|
|
399
|
+
def has_glyph(r):
|
|
400
|
+
inner = fitz.Rect(r.x0 + 1.5, r.y0 + 1.5, r.x1 - 1.5, r.y1 - 1.5)
|
|
401
|
+
return any(fitz.Rect(g[1]).intersects(inner) for g in glyphs)
|
|
402
|
+
|
|
403
|
+
fields = [(k, r) for k, r in fields if not (k == "checkbox" and has_glyph(r))]
|
|
404
|
+
|
|
405
|
+
# --- dedupe overlapping candidates (bigger first) ---
|
|
406
|
+
kept = []
|
|
407
|
+
for kind, r in sorted(fields, key=lambda f: -abs(f[1])):
|
|
408
|
+
if any(abs(r & r2) > 0.4 * min(abs(r), abs(r2)) for _, r2 in kept):
|
|
409
|
+
continue
|
|
410
|
+
kept.append((kind, r))
|
|
411
|
+
# reading order, so duplicate labels number top-down
|
|
412
|
+
kept.sort(key=lambda f: (round(f[1].y0), f[1].x0))
|
|
413
|
+
return kept, words, glyphs
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
# ---------------------------------------------------------------- build
|
|
417
|
+
|
|
418
|
+
def build(src, out, debug_overlay=None, field_map=None):
|
|
419
|
+
doc = fitz.open(src)
|
|
420
|
+
used = set()
|
|
421
|
+
stats = {"text": 0, "comb": 0, "checkbox": 0}
|
|
422
|
+
mapping = []
|
|
423
|
+
|
|
424
|
+
for pno in range(len(doc)):
|
|
425
|
+
page = doc[pno]
|
|
426
|
+
kept, words, glyphs = detect_fields(page)
|
|
427
|
+
|
|
428
|
+
# pass 1: raw labels
|
|
429
|
+
bases = [slugify(label_for(kind, r, words)) for kind, r in kept]
|
|
430
|
+
|
|
431
|
+
# pass 2a: continuation lines (e.g. address line 2) inherit the label
|
|
432
|
+
# of the text field directly above them
|
|
433
|
+
for i, (kind, r) in enumerate(kept):
|
|
434
|
+
if bases[i] or kind == "checkbox":
|
|
435
|
+
continue
|
|
436
|
+
for j, (kj, rj) in enumerate(kept):
|
|
437
|
+
if kj == "checkbox" or not bases[j]:
|
|
438
|
+
continue
|
|
439
|
+
if abs(rj.x0 - r.x0) < 6 and 0 < r.y0 - rj.y0 <= 20:
|
|
440
|
+
bases[i] = bases[j]
|
|
441
|
+
break
|
|
442
|
+
|
|
443
|
+
# pass 2b: date rows — narrow boxes on one line separated by printed
|
|
444
|
+
# "/" or "-" get dd/mm/yyyy suffixes
|
|
445
|
+
by_row = {}
|
|
446
|
+
for i, (kind, r) in enumerate(kept):
|
|
447
|
+
if kind != "checkbox" and r.width < 75:
|
|
448
|
+
by_row.setdefault(round((r.y0 + r.y1) / 2 / 4), []).append(i)
|
|
449
|
+
for idxs in by_row.values():
|
|
450
|
+
if len(idxs) < 2:
|
|
451
|
+
continue
|
|
452
|
+
idxs = sorted(idxs, key=lambda i: kept[i][1].x0)
|
|
453
|
+
seps = 0
|
|
454
|
+
for a, b in zip(idxs, idxs[1:]):
|
|
455
|
+
ra, rb = kept[a][1], kept[b][1]
|
|
456
|
+
if any(gc in "/-" and ra.x1 - 2 < (g[0] + g[2]) / 2 < rb.x0 + 2
|
|
457
|
+
and ra.y0 - 3 < (g[1] + g[3]) / 2 < ra.y1 + 3
|
|
458
|
+
for gc, g in glyphs):
|
|
459
|
+
seps += 1
|
|
460
|
+
if seps == len(idxs) - 1 and len(idxs) == 3:
|
|
461
|
+
root = next((bases[i] for i in idxs if bases[i]), "tanggal")
|
|
462
|
+
for i, suf in zip(idxs, ("dd", "mm", "yyyy")):
|
|
463
|
+
bases[i] = f"{root}_{suf}"
|
|
464
|
+
|
|
465
|
+
for (kind, r), base in zip(kept, bases):
|
|
466
|
+
base = base or "field"
|
|
467
|
+
name = f"p{pno + 1:02d}_{base}"
|
|
468
|
+
n = 1
|
|
469
|
+
while name in used:
|
|
470
|
+
n += 1
|
|
471
|
+
name = f"p{pno + 1:02d}_{base}_{n}"
|
|
472
|
+
used.add(name)
|
|
473
|
+
|
|
474
|
+
w = fitz.Widget()
|
|
475
|
+
w.rect = r
|
|
476
|
+
w.field_name = name
|
|
477
|
+
if kind == "checkbox":
|
|
478
|
+
w.field_type = fitz.PDF_WIDGET_TYPE_CHECKBOX
|
|
479
|
+
stats["checkbox"] += 1
|
|
480
|
+
elif kind.startswith("comb"):
|
|
481
|
+
w.field_type = fitz.PDF_WIDGET_TYPE_TEXT
|
|
482
|
+
w.text_maxlen = int(kind[4:])
|
|
483
|
+
w.field_flags = 1 << 24 # comb: one character per box
|
|
484
|
+
w.text_fontsize = min(9, max(6, r.height * 0.62))
|
|
485
|
+
stats["comb"] += 1
|
|
486
|
+
else:
|
|
487
|
+
w.field_type = fitz.PDF_WIDGET_TYPE_TEXT
|
|
488
|
+
w.text_fontsize = min(9, max(6, r.height * 0.62))
|
|
489
|
+
stats["text"] += 1
|
|
490
|
+
w.border_width = 0
|
|
491
|
+
w.fill_color = None
|
|
492
|
+
w.text_color = (0, 0, 0.6)
|
|
493
|
+
page.add_widget(w)
|
|
494
|
+
mapping.append({"name": name, "page": pno + 1,
|
|
495
|
+
"type": "checkbox" if kind == "checkbox" else "text",
|
|
496
|
+
"maxlen": int(kind[4:]) if kind.startswith("comb") else None,
|
|
497
|
+
"rect": [round(v, 1) for v in r]})
|
|
498
|
+
|
|
499
|
+
doc.save(out)
|
|
500
|
+
print(f"{out}: {stats['text']} text + {stats['comb']} comb + "
|
|
501
|
+
f"{stats['checkbox']} checkbox = {sum(stats.values())} fields")
|
|
502
|
+
|
|
503
|
+
if field_map:
|
|
504
|
+
with open(field_map, "w") as fh:
|
|
505
|
+
json.dump(mapping, fh, indent=2, ensure_ascii=False)
|
|
506
|
+
print(f"{field_map}: field map written ({len(mapping)} fields)")
|
|
507
|
+
|
|
508
|
+
if debug_overlay:
|
|
509
|
+
dbg = fitz.open(out)
|
|
510
|
+
for page in dbg:
|
|
511
|
+
shape = page.new_shape()
|
|
512
|
+
for w in page.widgets():
|
|
513
|
+
if w.field_type == fitz.PDF_WIDGET_TYPE_CHECKBOX:
|
|
514
|
+
col = (0, 0.7, 0)
|
|
515
|
+
elif w.text_maxlen:
|
|
516
|
+
col = (0, 0, 1)
|
|
517
|
+
else:
|
|
518
|
+
col = (1, 0, 0)
|
|
519
|
+
shape.draw_rect(w.rect)
|
|
520
|
+
shape.finish(color=col, width=1.2)
|
|
521
|
+
shape.commit()
|
|
522
|
+
dbg.save(debug_overlay)
|
|
523
|
+
print(f"{debug_overlay}: overlay written (red=text, blue=comb, green=checkbox)")
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
# ---------------------------------------------------------------- fill
|
|
527
|
+
|
|
528
|
+
def has_fields(path):
|
|
529
|
+
doc = fitz.open(path)
|
|
530
|
+
try:
|
|
531
|
+
return any(True for page in doc for _ in page.widgets())
|
|
532
|
+
finally:
|
|
533
|
+
doc.close()
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def check_values(fields, values):
|
|
537
|
+
"""Compare values with the fields of a PDF. Return a list of problems.
|
|
538
|
+
|
|
539
|
+
`fields` maps a field name to (type, maxlen). Nothing is written when the
|
|
540
|
+
list is not empty, so a typo in one name cannot give a half-filled form.
|
|
541
|
+
"""
|
|
542
|
+
problems = []
|
|
543
|
+
for name, value in values.items():
|
|
544
|
+
if name not in fields:
|
|
545
|
+
near = difflib.get_close_matches(name, fields, n=1)
|
|
546
|
+
hint = f" (did you mean {near[0]}?)" if near else ""
|
|
547
|
+
problems.append(f"{name}: no such field{hint}")
|
|
548
|
+
continue
|
|
549
|
+
ftype, maxlen = fields[name]
|
|
550
|
+
if ftype == fitz.PDF_WIDGET_TYPE_CHECKBOX:
|
|
551
|
+
if not isinstance(value, bool):
|
|
552
|
+
problems.append(f"{name}: checkbox needs true or false, got {value!r}")
|
|
553
|
+
elif isinstance(value, bool) or not isinstance(value, (str, int, float)):
|
|
554
|
+
problems.append(f"{name}: text field needs a string or number, got {value!r}")
|
|
555
|
+
elif maxlen and len(str(value)) > maxlen:
|
|
556
|
+
problems.append(f"{name}: {str(value)!r} has {len(str(value))} "
|
|
557
|
+
f"characters, the field holds {maxlen}")
|
|
558
|
+
return problems
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def fill(src, out, values):
|
|
562
|
+
"""Write `values` ({field name: value}) into the fields of `src`.
|
|
563
|
+
|
|
564
|
+
Returns the list of problems. An empty list means `out` was written.
|
|
565
|
+
"""
|
|
566
|
+
doc = fitz.open(src)
|
|
567
|
+
fields = {w.field_name: (w.field_type, w.text_maxlen)
|
|
568
|
+
for page in doc for w in page.widgets()}
|
|
569
|
+
problems = check_values(fields, values)
|
|
570
|
+
if problems:
|
|
571
|
+
doc.close()
|
|
572
|
+
return problems
|
|
573
|
+
|
|
574
|
+
done = 0
|
|
575
|
+
for page in doc:
|
|
576
|
+
for w in page.widgets():
|
|
577
|
+
if w.field_name not in values:
|
|
578
|
+
continue
|
|
579
|
+
v = values[w.field_name]
|
|
580
|
+
if w.field_type == fitz.PDF_WIDGET_TYPE_CHECKBOX:
|
|
581
|
+
w.field_value = w.on_state() if v else "Off"
|
|
582
|
+
else:
|
|
583
|
+
w.field_value = str(v)
|
|
584
|
+
w.update()
|
|
585
|
+
done += 1
|
|
586
|
+
|
|
587
|
+
# a PDF cannot be saved on top of the file it was opened from
|
|
588
|
+
tmp = out + ".tmp"
|
|
589
|
+
doc.save(tmp)
|
|
590
|
+
doc.close()
|
|
591
|
+
os.replace(tmp, out)
|
|
592
|
+
print(f"{out}: {done} of {len(fields)} fields filled")
|
|
593
|
+
return []
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def main():
|
|
597
|
+
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
598
|
+
ap.add_argument("input", help="flat PDF form, or a fillable one with --fill")
|
|
599
|
+
ap.add_argument("-o", "--output", help="output path (default: <input>_acroform.pdf, "
|
|
600
|
+
"or <input>_filled.pdf with --fill)")
|
|
601
|
+
ap.add_argument("--debug-overlay", help="also write a copy with color-coded field outlines")
|
|
602
|
+
ap.add_argument("--map", help="also write a JSON field map (name, page, type, rect)")
|
|
603
|
+
ap.add_argument("--fill", metavar="VALUES.json",
|
|
604
|
+
help="fill the fields from a JSON object {field name: value}. "
|
|
605
|
+
"A flat input is converted first")
|
|
606
|
+
args = ap.parse_args()
|
|
607
|
+
stem = re.sub(r"\.pdf$", "", args.input, flags=re.I)
|
|
608
|
+
|
|
609
|
+
if not args.fill:
|
|
610
|
+
build(args.input, args.output or stem + "_acroform.pdf",
|
|
611
|
+
args.debug_overlay, args.map)
|
|
612
|
+
return 0
|
|
613
|
+
|
|
614
|
+
try:
|
|
615
|
+
with open(args.fill, encoding="utf-8") as fh:
|
|
616
|
+
values = json.load(fh)
|
|
617
|
+
except (OSError, ValueError) as exc:
|
|
618
|
+
print(f"{args.fill}: cannot read values: {exc}", file=sys.stderr)
|
|
619
|
+
return 2
|
|
620
|
+
if not isinstance(values, dict):
|
|
621
|
+
print(f"{args.fill}: expected a JSON object {{field name: value}}", file=sys.stderr)
|
|
622
|
+
return 2
|
|
623
|
+
|
|
624
|
+
out = args.output or stem + "_filled.pdf"
|
|
625
|
+
src = args.input
|
|
626
|
+
converted = not has_fields(src)
|
|
627
|
+
if converted:
|
|
628
|
+
build(src, out, args.debug_overlay, args.map)
|
|
629
|
+
src = out
|
|
630
|
+
problems = fill(src, out, values)
|
|
631
|
+
if problems:
|
|
632
|
+
if converted:
|
|
633
|
+
os.remove(out) # do not leave an empty form under the "filled" name
|
|
634
|
+
for p in problems:
|
|
635
|
+
print(f"error: {p}", file=sys.stderr)
|
|
636
|
+
print(f"{len(problems)} problem(s). No file was written.", file=sys.stderr)
|
|
637
|
+
return 2
|
|
638
|
+
return 0
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
if __name__ == "__main__":
|
|
642
|
+
sys.exit(main())
|