@floless/app 0.174.0 → 0.175.0
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.
- package/autostart.mjs +117 -10
- package/dist/floless-server.cjs +2 -2
- package/dist/pdf-engine/floless_pdf/__init__.py +53 -0
- package/dist/pdf-engine/floless_pdf/backend_pdfium.py +823 -0
- package/dist/pdf-engine/floless_pdf/backend_pymupdf.py +245 -0
- package/dist/pdf-engine/floless_pdf/geometry.py +115 -0
- package/dist/pdf-engine/floless_pdf/images.py +75 -0
- package/dist/pdf-engine/floless_pdf/pages.py +136 -0
- package/dist/pdf-engine/floless_pdf/textrules.py +200 -0
- package/dist/schemas/steel.model.v2.schema.json +45 -1
- package/dist/skills/floless-app-approval/SKILL.md +28 -3
- package/dist/skills/floless-app-knowledge/SKILL.md +3 -2
- package/dist/skills/floless-app-sketches/SKILL.md +71 -0
- package/dist/skills/floless-app-sketches/references/steel-plate.md +15 -0
- package/dist/skills/floless-app-steel-model/SKILL.md +14 -1
- package/dist/skills/floless-app-steel-model/references/elements.md +90 -23
- package/dist/skills/floless-app-steel-takeoff/SKILL.md +18 -7
- package/dist/skills/floless-app-tweak-contract/SKILL.md +3 -2
- package/dist/web/agents.js +1 -1
- package/dist/web/app.css +120 -15
- package/dist/web/app.js +89 -38
- package/dist/web/aware-hold.js +10 -0
- package/dist/web/aware.js +405 -51
- package/dist/web/boot-watchdog.js +249 -0
- package/dist/web/card-details.js +88 -0
- package/dist/web/chat.css +29 -0
- package/dist/web/chat.js +430 -128
- package/dist/web/commands-connection-design.js +23 -0
- package/dist/web/commands-revit.js +3 -0
- package/dist/web/commands-shell.js +226 -10
- package/dist/web/commands-steel.js +95 -5
- package/dist/web/commands-tekla-parser.js +21 -1
- package/dist/web/connection-design-editor.html +71 -0
- package/dist/web/connection-design-editor.js +794 -61
- package/dist/web/connection-design-handles.js +9 -3
- package/dist/web/element-approval.js +74 -0
- package/dist/web/element-context.js +76 -6
- package/dist/web/element-geometry.js +8 -2
- package/dist/web/element-holds.js +68 -5
- package/dist/web/element-type-actions.js +22 -3
- package/dist/web/element-types.js +12 -5
- package/dist/web/element-words.js +15 -11
- package/dist/web/grid-place.js +51 -0
- package/dist/web/guide.js +2 -0
- package/dist/web/index.html +13 -16
- package/dist/web/instructor.js +5 -2
- package/dist/web/missed-routines.js +6 -1
- package/dist/web/model-change-findings.js +147 -32
- package/dist/web/model-change-review.js +435 -32
- package/dist/web/model-clash-check.css +100 -0
- package/dist/web/model-clash-check.js +681 -0
- package/dist/web/model-clip-box.js +204 -0
- package/dist/web/model-clip-list.js +153 -3
- package/dist/web/model-clip-session.js +3 -3
- package/dist/web/model-clip-three-overlay.js +135 -25
- package/dist/web/model-editor.css +2 -0
- package/dist/web/model-elements.js +273 -18
- package/dist/web/model-fit-checks.js +354 -0
- package/dist/web/model-spatial-panel.js +9 -3
- package/dist/web/model-spatial-tools.js +12 -3
- package/dist/web/model-tekla-selection.js +74 -0
- package/dist/web/model-view-query.js +70 -14
- package/dist/web/model-viewport-revit-adapter.js +8 -7
- package/dist/web/model-viewport-toolbar.js +8 -4
- package/dist/web/pages.js +78 -1
- package/dist/web/project-history.js +31 -1
- package/dist/web/revit-editor.css +34 -1
- package/dist/web/revit-editor.js +176 -55
- package/dist/web/run-history.js +8 -0
- package/dist/web/sketch-editor.js +141 -2
- package/dist/web/sketches.js +192 -6
- package/dist/web/start-place.js +46 -0
- package/dist/web/steel-3d-core.js +70 -0
- package/dist/web/steel-3d-view.js +288 -47
- package/dist/web/steel-change-review.css +29 -0
- package/dist/web/steel-custom-connection.js +6 -0
- package/dist/web/steel-editor.html +532 -33
- package/dist/web/steel-filter.html +8 -3
- package/dist/web/steel-model-checks.css +76 -0
- package/dist/web/steel-model-commands.js +1 -1
- package/dist/web/steel-model-v2-commands.js +17 -0
- package/dist/web/steel-view-generation.js +6 -2
- package/dist/web/teams.js +259 -19
- package/dist/web/tekla-editor.html +1 -0
- package/dist/web/terminal-requests.js +6 -0
- package/dist/web/vendor/connection-engine.js +890 -89
- package/dist/web/workspaces.js +630 -48
- package/package.json +4 -1
- package/preferences-file.mjs +27 -0
|
@@ -0,0 +1,823 @@
|
|
|
1
|
+
"""The pdfium backend: pypdfium2 (PDFium), written fresh for FloLess (plan section 3.1).
|
|
2
|
+
|
|
3
|
+
What it reads, and where it deliberately differs from MuPDF (the D numbers are the plan's, section 1):
|
|
4
|
+
|
|
5
|
+
- Coordinates: unrotated page space, origin at the crop box's top-left, y down, as the pymupdf backend gives them.
|
|
6
|
+
- Text: PDFium's characters with their boxes; lines, spaces and words come from FloLess's own rules (textrules.py),
|
|
7
|
+
never from PDFium's segmentation (D2, D3). Text printed several times on itself is read once (D12).
|
|
8
|
+
- Linework: every path object, Form XObjects included, with its matrix, colours, width, dash and layer. A fill and
|
|
9
|
+
a stroke of the same outline, one after the other on one layer, are one "fs" drawing as MuPDF reads them (D4). A
|
|
10
|
+
path's extent is trimmed to its clip (D8). Mid-grey is PDFium's #808080 (D5).
|
|
11
|
+
- Markups: annotation appearances are not read (D1, owner ruling 2026-11-20); every drawing and char says
|
|
12
|
+
`markup: False`, and the rendered picture still shows them.
|
|
13
|
+
- Layers: the optional content an object sits in, by its layer name; content under a membership dictionary (OCMD)
|
|
14
|
+
is in the first layer the dictionary names. The document's layer list comes from pypdf.
|
|
15
|
+
"""
|
|
16
|
+
import ctypes
|
|
17
|
+
import math
|
|
18
|
+
|
|
19
|
+
import pypdfium2 as pdfium
|
|
20
|
+
import pypdfium2.raw as R
|
|
21
|
+
|
|
22
|
+
from . import images, textrules
|
|
23
|
+
from .geometry import Matrix, Point, Rect, rotation_matrix
|
|
24
|
+
|
|
25
|
+
NAME = "pdfium"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class StructureError(Exception):
|
|
29
|
+
"""pypdf could not read the document's structure; the message is its error class name."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def versions():
|
|
33
|
+
return {"pypdfium2": str(pdfium.PYPDFIUM_INFO.version), "pdfium": str(pdfium.PDFIUM_INFO.build)}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_BUF = (ctypes.c_ushort * 1024)()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _wide(fn, *args):
|
|
40
|
+
n = ctypes.c_ulong()
|
|
41
|
+
if not fn(*args, _BUF, ctypes.sizeof(_BUF), ctypes.byref(n)):
|
|
42
|
+
return None
|
|
43
|
+
return bytes(_BUF)[:max(0, n.value - 2)].decode("utf-16-le", "replace")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _obj_matrix(obj):
|
|
47
|
+
m = R.FS_MATRIX()
|
|
48
|
+
R.FPDFPageObj_GetMatrix(obj, m)
|
|
49
|
+
return Matrix(m.a, m.b, m.c, m.d, m.e, m.f)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _rgb(fn, obj):
|
|
53
|
+
r, g, b, a = ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint()
|
|
54
|
+
if not fn(obj, r, g, b, a):
|
|
55
|
+
return None
|
|
56
|
+
return (r.value / 255.0, g.value / 255.0, b.value / 255.0)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _same_items(a, b):
|
|
60
|
+
def key(items):
|
|
61
|
+
out = []
|
|
62
|
+
for it in items:
|
|
63
|
+
out.append((it[0],) + tuple(v for p in it[1:] for v in ((round(p.x, 3), round(p.y, 3)) if isinstance(p, Point)
|
|
64
|
+
else (tuple(round(x, 3) for x in p.as_tuple()) if isinstance(p, Rect) else (p,)))))
|
|
65
|
+
return out
|
|
66
|
+
return key(a) == key(b)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Page:
|
|
70
|
+
# The whole-page picture's JPEG quality (pages.page_picture/page_pictures); tiles keep images.JPEG_QUALITY. At 88
|
|
71
|
+
# pdfium's optimised JPEG is within the 1.25x size bar of MuPDF's quality-95 picture on every corpus page, with no
|
|
72
|
+
# ink measure moving against quality 95 (slice 2b, docs/superpowers/specs/2026-11-23-pdf-engine-slice2-PLAN.md).
|
|
73
|
+
PAGE_JPEG_QUALITY = 88
|
|
74
|
+
|
|
75
|
+
def __init__(self, doc, number):
|
|
76
|
+
self._doc = doc
|
|
77
|
+
self._p = doc._pdf[number]
|
|
78
|
+
self.number = number
|
|
79
|
+
# PDFium's own page box: the crop box clipped to the media box, which is MuPDF's `page.rect` (a crop box larger
|
|
80
|
+
# than the media box shows only the media box; the raw crop box would stretch the picture and shift every
|
|
81
|
+
# coordinate by the overhang).
|
|
82
|
+
cx0, cy0, cx1, cy1 = self._p.get_bbox()
|
|
83
|
+
w, h = cx1 - cx0, cy1 - cy0
|
|
84
|
+
self._ctm = Matrix(1, 0, 0, -1, -cx0, cy1) # PDF user space -> unrotated page space (y down)
|
|
85
|
+
self.rotation = self._p.get_rotation() % 360
|
|
86
|
+
self.unrotated_size = (w, h)
|
|
87
|
+
self.size = (h, w) if self.rotation in (90, 270) else (w, h)
|
|
88
|
+
self.rotation_matrix = rotation_matrix(self.rotation, w, h)
|
|
89
|
+
self._tp = None
|
|
90
|
+
self._layer_cache = {}
|
|
91
|
+
self._tree_cache = None
|
|
92
|
+
self._hairlines_beveled = False
|
|
93
|
+
|
|
94
|
+
# ---- layers -------------------------------------------------------------------------------------------------
|
|
95
|
+
def _layer(self, obj):
|
|
96
|
+
"""The layer an object is in: the innermost optional-content mark around it ('' outside any layer)."""
|
|
97
|
+
return self._oc(obj)[0]
|
|
98
|
+
|
|
99
|
+
def _hidden(self, obj):
|
|
100
|
+
"""True when the object sits in a layer the default configuration turns off; MuPDF does not read those."""
|
|
101
|
+
return self._oc(obj)[1]
|
|
102
|
+
|
|
103
|
+
def _oc(self, obj):
|
|
104
|
+
"""(layer, hidden) of an object: its own optional-content marks, inside whatever the Forms around it give
|
|
105
|
+
(a Form's own /OC entry, or the marks around the Form), as MuPDF reads them."""
|
|
106
|
+
key = ctypes.addressof(obj.contents) if obj else 0
|
|
107
|
+
if key in self._layer_cache:
|
|
108
|
+
return self._layer_cache[key]
|
|
109
|
+
own_name, own_hidden = self._marks(obj)
|
|
110
|
+
inh_name, inh_hidden = self._tree()[1].get(key, ("", False))
|
|
111
|
+
self._layer_cache[key] = (own_name or inh_name, own_hidden or inh_hidden)
|
|
112
|
+
return self._layer_cache[key]
|
|
113
|
+
|
|
114
|
+
def _marks(self, obj):
|
|
115
|
+
"""(layer, hidden) from an object's own optional-content marks only."""
|
|
116
|
+
name, hidden = "", False
|
|
117
|
+
if not obj:
|
|
118
|
+
return name, hidden
|
|
119
|
+
for i in range(R.FPDFPageObj_CountMarks(obj)):
|
|
120
|
+
mark = R.FPDFPageObj_GetMark(obj, i)
|
|
121
|
+
if _wide(R.FPDFPageObjMark_GetName, mark) != "OC":
|
|
122
|
+
continue
|
|
123
|
+
n = ctypes.c_ulong()
|
|
124
|
+
if R.FPDFPageObjMark_GetParamStringValue(mark, b"Name", _BUF, ctypes.sizeof(_BUF), ctypes.byref(n)):
|
|
125
|
+
name = bytes(_BUF)[:max(0, n.value - 2)].decode("utf-16-le", "replace")
|
|
126
|
+
hidden = hidden or name in self._doc._off_names()
|
|
127
|
+
else:
|
|
128
|
+
ocmd_name, ocmd_hidden = self._doc._ocmd_layer(self.number, mark)
|
|
129
|
+
name = ocmd_name or name
|
|
130
|
+
hidden = hidden or ocmd_hidden
|
|
131
|
+
return name, hidden
|
|
132
|
+
|
|
133
|
+
def _tree(self):
|
|
134
|
+
"""Every path object with its matrices, and the layer each object inside a Form inherits from it.
|
|
135
|
+
|
|
136
|
+
PDFium hands over a Form's children but not the Form's own /OC entry, so the Forms a content stream paints are
|
|
137
|
+
read through pypdf, in order, and paired with PDFium's Form objects at the same level. Where the two counts
|
|
138
|
+
disagree the pairing is not trusted and that level inherits only the marks around its Forms (a stated limit)."""
|
|
139
|
+
if self._tree_cache is not None:
|
|
140
|
+
return self._tree_cache
|
|
141
|
+
paths, inherited = [], {}
|
|
142
|
+
top = None
|
|
143
|
+
reader = self._doc._reader()
|
|
144
|
+
if reader is not None:
|
|
145
|
+
try:
|
|
146
|
+
pg = reader.pages[self.number]
|
|
147
|
+
top = (pg.get_contents(), pg.get("/Resources"))
|
|
148
|
+
except Exception: # noqa: BLE001 - the page still reads, without Form layers
|
|
149
|
+
top = None
|
|
150
|
+
|
|
151
|
+
def walk(parent, in_form, chain, inh, stream):
|
|
152
|
+
n = R.FPDFFormObj_CountObjects(parent) if in_form else R.FPDFPage_CountObjects(parent)
|
|
153
|
+
children = [R.FPDFFormObj_GetObject(parent, i) if in_form else R.FPDFPage_GetObject(parent, i) for i in range(n)]
|
|
154
|
+
form_children = [o for o in children if R.FPDFPageObj_GetType(o) == R.FPDF_PAGEOBJ_FORM]
|
|
155
|
+
xobjects = None
|
|
156
|
+
if stream is not None:
|
|
157
|
+
try:
|
|
158
|
+
xobjects = self._doc._form_xobjects(*stream)
|
|
159
|
+
except Exception: # noqa: BLE001 - unpaired: marks only
|
|
160
|
+
xobjects = None
|
|
161
|
+
if xobjects is not None and len(xobjects) != len(form_children):
|
|
162
|
+
xobjects = None
|
|
163
|
+
k = 0
|
|
164
|
+
for obj in children:
|
|
165
|
+
if inh != ("", False):
|
|
166
|
+
inherited[ctypes.addressof(obj.contents)] = inh
|
|
167
|
+
t = R.FPDFPageObj_GetType(obj)
|
|
168
|
+
if t == R.FPDF_PAGEOBJ_FORM:
|
|
169
|
+
xobj = xobjects[k] if xobjects is not None else None
|
|
170
|
+
k += 1
|
|
171
|
+
mark_name, mark_hidden = self._marks(obj)
|
|
172
|
+
oc_name, oc_hidden = self._doc._form_oc(xobj) if xobj is not None else ("", False)
|
|
173
|
+
child = (oc_name or mark_name or inh[0], inh[1] or mark_hidden or oc_hidden)
|
|
174
|
+
sub = None
|
|
175
|
+
if xobj is not None:
|
|
176
|
+
sub = (xobj, xobj.get("/Resources") if xobj.get("/Resources") is not None else stream[1])
|
|
177
|
+
walk(obj, True, _obj_matrix(obj).then(chain), child, sub)
|
|
178
|
+
elif t == R.FPDF_PAGEOBJ_PATH:
|
|
179
|
+
paths.append((obj, _obj_matrix(obj).then(chain), chain))
|
|
180
|
+
walk(self._p.raw, False, self._ctm, ("", False), top)
|
|
181
|
+
self._tree_cache = (paths, inherited)
|
|
182
|
+
return self._tree_cache
|
|
183
|
+
|
|
184
|
+
# ---- text ---------------------------------------------------------------------------------------------------
|
|
185
|
+
def _textpage(self):
|
|
186
|
+
if self._tp is None:
|
|
187
|
+
self._tp = self._p.get_textpage()
|
|
188
|
+
return self._tp
|
|
189
|
+
|
|
190
|
+
def _raw_chars(self):
|
|
191
|
+
raw = self._textpage().raw
|
|
192
|
+
rect = R.FS_RECTF()
|
|
193
|
+
fr, fg, fb, fa = ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint()
|
|
194
|
+
ox, oy = ctypes.c_double(), ctypes.c_double()
|
|
195
|
+
tm = R.FS_MATRIX()
|
|
196
|
+
fonts = {}
|
|
197
|
+
out = []
|
|
198
|
+
for i in range(R.FPDFText_CountChars(raw)):
|
|
199
|
+
u = R.FPDFText_GetUnicode(raw, i)
|
|
200
|
+
generated = R.FPDFText_IsGenerated(raw, i) == 1
|
|
201
|
+
c = chr(u) if u else ""
|
|
202
|
+
if c in ("\r", "\n") or u == 0xFFFE:
|
|
203
|
+
out.append({"c": "\n", "generated": True})
|
|
204
|
+
continue
|
|
205
|
+
R.FPDFText_GetLooseCharBox(raw, i, rect)
|
|
206
|
+
box = Rect(rect.left, rect.top, rect.right, rect.bottom).transform(self._ctm)
|
|
207
|
+
obj = R.FPDFText_GetTextObject(raw, i)
|
|
208
|
+
key = ctypes.addressof(obj.contents) if obj else 0
|
|
209
|
+
if key not in fonts:
|
|
210
|
+
fonts[key] = self._font_of(obj)
|
|
211
|
+
font, flags, layer = fonts[key]
|
|
212
|
+
if obj and self._hidden(obj):
|
|
213
|
+
continue
|
|
214
|
+
R.FPDFText_GetFillColor(raw, i, fr, fg, fb, fa)
|
|
215
|
+
R.FPDFText_GetCharOrigin(raw, i, ox, oy)
|
|
216
|
+
R.FPDFText_GetMatrix(raw, i, tm)
|
|
217
|
+
out.append({"c": c, "generated": generated, "box": box,
|
|
218
|
+
"origin": Point(*self._ctm.apply(ox.value, oy.value)),
|
|
219
|
+
"size": R.FPDFText_GetFontSize(raw, i),
|
|
220
|
+
"angle": round(math.atan2(-tm.b, tm.a), 4),
|
|
221
|
+
"font": font, "flags": flags, "layer": layer, "markup": False,
|
|
222
|
+
"color": (fr.value << 16) | (fg.value << 8) | fb.value})
|
|
223
|
+
return out
|
|
224
|
+
|
|
225
|
+
def _font_of(self, obj):
|
|
226
|
+
if not obj:
|
|
227
|
+
return ("", 0, "")
|
|
228
|
+
font = R.FPDFTextObj_GetFont(obj)
|
|
229
|
+
name, flags = "", 0
|
|
230
|
+
if font:
|
|
231
|
+
buf = ctypes.create_string_buffer(256)
|
|
232
|
+
R.FPDFFont_GetBaseFontName(font, buf, 256)
|
|
233
|
+
name = buf.value.decode("latin-1", "replace")
|
|
234
|
+
pdf_flags = R.FPDFFont_GetFlags(font)
|
|
235
|
+
# MuPDF's span flags: 2 italic, 4 serif, 8 monospaced, 16 bold (from the font descriptor and its weight).
|
|
236
|
+
flags = (2 if pdf_flags & (1 << 6) else 0) | (4 if pdf_flags & (1 << 1) else 0) \
|
|
237
|
+
| (8 if pdf_flags & 1 else 0) | (16 if R.FPDFFont_GetWeight(font) >= 600 or pdf_flags & (1 << 18) else 0)
|
|
238
|
+
return (name, flags, self._layer(obj))
|
|
239
|
+
|
|
240
|
+
def chars(self):
|
|
241
|
+
return [c for c in self._raw_chars() if c["c"] != "\n"]
|
|
242
|
+
|
|
243
|
+
def lines(self):
|
|
244
|
+
out = []
|
|
245
|
+
for ln in textrules.lines(self._raw_chars()):
|
|
246
|
+
out.append({"bbox": ln["bbox"], "dir": ln["dir"], "spans": [
|
|
247
|
+
{"text": s["text"], "bbox": s["bbox"], "size": s["size"], "font": s["font"], "color": s["color"],
|
|
248
|
+
"flags": s["flags"], "origin": s["origin"]} for s in ln["spans"]]})
|
|
249
|
+
return out
|
|
250
|
+
|
|
251
|
+
def words(self):
|
|
252
|
+
return [(w[0], w[1], w[2], w[3], w[4], 0, w[5], w[6]) for w in textrules.words(self._raw_chars())]
|
|
253
|
+
|
|
254
|
+
def text(self):
|
|
255
|
+
return "\n".join(" ".join(s["text"] for s in ln["spans"]).strip() for ln in self.lines()) + ("\n" if self.lines() else "")
|
|
256
|
+
|
|
257
|
+
# ---- linework -----------------------------------------------------------------------------------------------
|
|
258
|
+
def _paths(self):
|
|
259
|
+
return self._tree()[0]
|
|
260
|
+
|
|
261
|
+
def _clip_rect(self, obj, chain):
|
|
262
|
+
"""The bounding box of an object's clip, in page space; None when it has none (D8)."""
|
|
263
|
+
clip = R.FPDFPageObj_GetClipPath(obj)
|
|
264
|
+
if not clip:
|
|
265
|
+
return None
|
|
266
|
+
x, y = ctypes.c_float(), ctypes.c_float()
|
|
267
|
+
box = None
|
|
268
|
+
for i in range(R.FPDFClipPath_CountPaths(clip)):
|
|
269
|
+
pts = []
|
|
270
|
+
for s in range(R.FPDFClipPath_CountPathSegments(clip, i)):
|
|
271
|
+
seg = R.FPDFClipPath_GetPathSegment(clip, i, s)
|
|
272
|
+
if seg and R.FPDFPathSegment_GetPoint(seg, x, y):
|
|
273
|
+
pts.append(Point(*chain.apply(x.value, y.value)))
|
|
274
|
+
if pts:
|
|
275
|
+
r = Rect.around(pts)
|
|
276
|
+
box = r if box is None else box.intersect(r)
|
|
277
|
+
return box
|
|
278
|
+
|
|
279
|
+
def drawings(self):
|
|
280
|
+
out = []
|
|
281
|
+
x, y = ctypes.c_float(), ctypes.c_float()
|
|
282
|
+
mode, stroke = ctypes.c_int(), ctypes.c_int()
|
|
283
|
+
for obj, m, chain in self._paths():
|
|
284
|
+
R.FPDFPath_GetDrawMode(obj, mode, stroke)
|
|
285
|
+
fill, strk = mode.value != 0, bool(stroke.value)
|
|
286
|
+
if not fill and not strk:
|
|
287
|
+
continue
|
|
288
|
+
if self._hidden(obj):
|
|
289
|
+
continue
|
|
290
|
+
items = _path_items(obj, m, x, y)
|
|
291
|
+
if not items:
|
|
292
|
+
continue
|
|
293
|
+
pts = []
|
|
294
|
+
for it in items:
|
|
295
|
+
if it[0] == "re":
|
|
296
|
+
pts += [Point(it[1].x0, it[1].y0), Point(it[1].x1, it[1].y1)]
|
|
297
|
+
else:
|
|
298
|
+
pts += list(it[1:])
|
|
299
|
+
rect = Rect.around(pts)
|
|
300
|
+
clip = self._clip_rect(obj, chain)
|
|
301
|
+
layer = self._layer(obj)
|
|
302
|
+
width = color = dashes = None
|
|
303
|
+
if strk:
|
|
304
|
+
w = ctypes.c_float()
|
|
305
|
+
R.FPDFPageObj_GetStrokeWidth(obj, w)
|
|
306
|
+
width = w.value * m.expansion
|
|
307
|
+
color = _rgb(R.FPDFPageObj_GetStrokeColor, obj)
|
|
308
|
+
dashes = _dashes(obj, m.expansion)
|
|
309
|
+
prev = out[-1] if out else None
|
|
310
|
+
if strk and not fill and prev is not None and prev["type"] == "f" and prev["layer"] == layer \
|
|
311
|
+
and _same_items(prev["items"], items):
|
|
312
|
+
prev.update({"type": "fs", "width": width, "color": color, "dashes": dashes}) # D4
|
|
313
|
+
continue
|
|
314
|
+
out.append({"type": "fs" if fill and strk else ("f" if fill else "s"), "items": items, "rect": rect,
|
|
315
|
+
"clip": clip, "visible": rect.intersect(clip) if clip is not None else rect,
|
|
316
|
+
"width": width, "color": color, "fill": _rgb(R.FPDFPageObj_GetFillColor, obj) if fill else None,
|
|
317
|
+
"dashes": dashes, "even_odd": (mode.value == R.FPDF_FILLMODE_ALTERNATE) if fill else None,
|
|
318
|
+
"closePath": False, "layer": layer, "markup": False})
|
|
319
|
+
return out
|
|
320
|
+
|
|
321
|
+
# ---- pictures -----------------------------------------------------------------------------------------------
|
|
322
|
+
def render(self, scale=None, dpi=None, clip=None):
|
|
323
|
+
"""The displayed page (or the `clip` of it, in displayed page space: `size`, origin top-left) as RGB on white,
|
|
324
|
+
with MuPDF's pixel box: at scale s the left/top pixel edge is floor(v*s + 0.001), the right/bottom one
|
|
325
|
+
ceil(v*s - 0.001), so a picture or a tile has exactly the size PyMuPDF gives it (slice 2, S2-6)."""
|
|
326
|
+
k = (float(dpi) / 72.0) if dpi is not None else float(scale or 1.0)
|
|
327
|
+
w, h = self.size
|
|
328
|
+
full = (0, 0, _ceil(w * k), _ceil(h * k))
|
|
329
|
+
if clip is None:
|
|
330
|
+
box = full
|
|
331
|
+
else:
|
|
332
|
+
x0, y0, x1, y1 = clip
|
|
333
|
+
box = (max(full[0], _floor(x0 * k)), max(full[1], _floor(y0 * k)),
|
|
334
|
+
min(full[2], _ceil(x1 * k)), min(full[3], _ceil(y1 * k)))
|
|
335
|
+
bw, bh = box[2] - box[0], box[3] - box[1]
|
|
336
|
+
if bw < 1 or bh < 1:
|
|
337
|
+
raise ValueError("the clip lies outside the page")
|
|
338
|
+
self._bevel_hairline_joins()
|
|
339
|
+
bitmap = pdfium.PdfBitmap.new_native(bw, bh, R.FPDFBitmap_BGR)
|
|
340
|
+
bitmap.fill_rect((255, 255, 255, 255), 0, 0, bw, bh)
|
|
341
|
+
# The whole displayed page is mapped onto MuPDF's full-page pixel size and shifted by the box's corner; PDFium
|
|
342
|
+
# applies the page's own /Rotate (rotate=0), and draws annotation appearances as MuPDF does.
|
|
343
|
+
R.FPDF_RenderPageBitmap(bitmap.raw, self._p.raw, -box[0], -box[1], full[2], full[3], 0, R.FPDF_ANNOT)
|
|
344
|
+
return images.to_rgb(bitmap.to_pil())
|
|
345
|
+
|
|
346
|
+
def _bevel_hairline_joins(self):
|
|
347
|
+
"""Draw every width-0 (hairline) stroke with bevel joins instead of miters, once per page, before the first
|
|
348
|
+
picture. A hairline is the thinnest line the device draws, 1 px; MuPDF and the reference viewer (pdf.js) draw
|
|
349
|
+
it as plain segments, but PDFium widens it to 1 px and then applies the miter join, so the sharp triangles CAD
|
|
350
|
+
exports fill small dots with grew spikes up to 4 px long at picture dpi: new ink nobody else paints (slice 2b,
|
|
351
|
+
the new-ink investigation). A bevel adds at most half a pixel at a 1 px width. Only the loaded page objects in
|
|
352
|
+
memory change, never the file; no reader here reports a join, so text and linework are untouched."""
|
|
353
|
+
if self._hairlines_beveled:
|
|
354
|
+
return
|
|
355
|
+
self._hairlines_beveled = True
|
|
356
|
+
width, mode, stroke = ctypes.c_float(), ctypes.c_int(), ctypes.c_int()
|
|
357
|
+
|
|
358
|
+
def walk(parent, in_form):
|
|
359
|
+
n = R.FPDFFormObj_CountObjects(parent) if in_form else R.FPDFPage_CountObjects(parent)
|
|
360
|
+
for i in range(n):
|
|
361
|
+
obj = R.FPDFFormObj_GetObject(parent, i) if in_form else R.FPDFPage_GetObject(parent, i)
|
|
362
|
+
t = R.FPDFPageObj_GetType(obj)
|
|
363
|
+
if t == R.FPDF_PAGEOBJ_FORM:
|
|
364
|
+
walk(obj, True)
|
|
365
|
+
elif (t == R.FPDF_PAGEOBJ_PATH and R.FPDFPageObj_GetLineJoin(obj) == R.FPDF_LINEJOIN_MITER
|
|
366
|
+
and R.FPDFPath_GetDrawMode(obj, mode, stroke) and stroke.value
|
|
367
|
+
and R.FPDFPageObj_GetStrokeWidth(obj, width) and width.value == 0):
|
|
368
|
+
R.FPDFPageObj_SetLineJoin(obj, R.FPDF_LINEJOIN_BEVEL)
|
|
369
|
+
walk(self._p.raw, False)
|
|
370
|
+
|
|
371
|
+
def render_jpeg(self, scale=None, dpi=None, clip=None, quality=images.JPEG_QUALITY):
|
|
372
|
+
img = self.render(scale, dpi, clip)
|
|
373
|
+
return images.encode_jpeg(img, quality), img.size
|
|
374
|
+
|
|
375
|
+
def render_png(self, scale=None, dpi=None, clip=None):
|
|
376
|
+
img = self.render(scale, dpi, clip)
|
|
377
|
+
return images.encode_png(img), img.size
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _floor(v):
|
|
381
|
+
return int(math.floor(v + 0.001))
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _ceil(v):
|
|
385
|
+
return int(math.ceil(v - 0.001))
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _dashes(obj, k):
|
|
389
|
+
n = R.FPDFPageObj_GetDashCount(obj)
|
|
390
|
+
phase = ctypes.c_float()
|
|
391
|
+
R.FPDFPageObj_GetDashPhase(obj, phase)
|
|
392
|
+
if n <= 0:
|
|
393
|
+
return "[] 0"
|
|
394
|
+
arr = (ctypes.c_float * n)()
|
|
395
|
+
R.FPDFPageObj_GetDashArray(obj, arr, n)
|
|
396
|
+
return "[ %s ] %g" % (" ".join("%g" % (arr[i] * k) for i in range(n)), phase.value * k)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _path_items(obj, m, x, y):
|
|
400
|
+
"""A path's segments as MuPDF reports them: lines, curves, and a closed four-line subpath as a rectangle when it
|
|
401
|
+
is axis-aligned or a quad when it is not. A line to the current point is dropped unless it follows a move."""
|
|
402
|
+
items, sub, start, cur, bez = [], [], None, None, []
|
|
403
|
+
|
|
404
|
+
def flush(closed):
|
|
405
|
+
lines = [it for it in sub if it[0] == "l"]
|
|
406
|
+
if closed and len(sub) == 4 and len(lines) == 4:
|
|
407
|
+
p = [it[1] for it in sub]
|
|
408
|
+
xs = {round(q.x, 3) for q in p}
|
|
409
|
+
ys = {round(q.y, 3) for q in p}
|
|
410
|
+
if len(xs) == 2 and len(ys) == 2:
|
|
411
|
+
area = sum(p[i].x * p[(i + 1) % 4].y - p[(i + 1) % 4].x * p[i].y for i in range(4))
|
|
412
|
+
items.append(("re", Rect.around(p), 1 if area <= 0 else -1))
|
|
413
|
+
else:
|
|
414
|
+
items.append(("qu", p[0], p[3], p[1], p[2]))
|
|
415
|
+
else:
|
|
416
|
+
items.extend(sub)
|
|
417
|
+
sub.clear()
|
|
418
|
+
|
|
419
|
+
for s in range(R.FPDFPath_CountSegments(obj)):
|
|
420
|
+
seg = R.FPDFPath_GetPathSegment(obj, s)
|
|
421
|
+
R.FPDFPathSegment_GetPoint(seg, x, y)
|
|
422
|
+
p = Point(*m.apply(x.value, y.value))
|
|
423
|
+
kind = R.FPDFPathSegment_GetType(seg)
|
|
424
|
+
closes = bool(R.FPDFPathSegment_GetClose(seg))
|
|
425
|
+
if kind == R.FPDF_SEGMENT_MOVETO:
|
|
426
|
+
if sub:
|
|
427
|
+
flush(False)
|
|
428
|
+
start = cur = p
|
|
429
|
+
elif kind == R.FPDF_SEGMENT_LINETO:
|
|
430
|
+
if not (sub and abs(p.x - cur.x) < 1e-6 and abs(p.y - cur.y) < 1e-6):
|
|
431
|
+
sub.append(("l", cur, p))
|
|
432
|
+
cur = p
|
|
433
|
+
elif kind == R.FPDF_SEGMENT_BEZIERTO:
|
|
434
|
+
bez.append(p)
|
|
435
|
+
if len(bez) == 3:
|
|
436
|
+
sub.append(("c", cur, bez[0], bez[1], bez[2]))
|
|
437
|
+
cur, bez = bez[2], []
|
|
438
|
+
if closes and start is not None:
|
|
439
|
+
if abs(cur.x - start.x) > 1e-6 or abs(cur.y - start.y) > 1e-6:
|
|
440
|
+
sub.append(("l", cur, start))
|
|
441
|
+
cur = start
|
|
442
|
+
flush(True)
|
|
443
|
+
if sub:
|
|
444
|
+
flush(False)
|
|
445
|
+
return items
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _drop_unreachable(writer):
|
|
449
|
+
"""Keep only the objects the piece's trailer reaches. pypdf's unreferenced pass frees one level of orphans per call
|
|
450
|
+
(an object counts as referenced while any other object, itself orphaned or not, points at it), so a removed page's
|
|
451
|
+
resource dictionaries, Forms and images stayed: a 3-page piece of a 40 MB set was written at 40 MB, and MuPDF's
|
|
452
|
+
piece of the same pages is 6.7 MB (slice 2b profile). Reached from the catalog; the piece has no /Info and is
|
|
453
|
+
written unencrypted, and its /ID is a direct value."""
|
|
454
|
+
from pypdf.generic import ArrayObject, DictionaryObject, IndirectObject # noqa: PLC0415
|
|
455
|
+
|
|
456
|
+
reached = set()
|
|
457
|
+
stack = [writer._root_object.indirect_reference] # noqa: SLF001
|
|
458
|
+
while stack:
|
|
459
|
+
item = stack.pop()
|
|
460
|
+
if isinstance(item, IndirectObject):
|
|
461
|
+
if item.idnum in reached:
|
|
462
|
+
continue
|
|
463
|
+
reached.add(item.idnum)
|
|
464
|
+
item = writer.get_object(item.idnum)
|
|
465
|
+
if isinstance(item, DictionaryObject):
|
|
466
|
+
stack.extend(item.values())
|
|
467
|
+
elif isinstance(item, ArrayObject):
|
|
468
|
+
stack.extend(item)
|
|
469
|
+
objects = writer._objects # noqa: SLF001 - pypdf writes every object left in this list
|
|
470
|
+
for i in range(len(objects)):
|
|
471
|
+
if objects[i] is not None and i + 1 not in reached:
|
|
472
|
+
objects[i] = None
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _prune_removed_targets(writer, root):
|
|
476
|
+
"""What still points at a removed page after pypdf's `remove_page(clean=True)`, which only turns the page into
|
|
477
|
+
`null`: a link or an outline item whose destination is that page goes (as MuPDF's select drops them), an outline
|
|
478
|
+
item with children keeps them and loses only its destination, and a form field whose widgets were all on removed
|
|
479
|
+
pages leaves /AcroForm (the kept pages' fields stay). Named destinations are left as they are (a stated limit)."""
|
|
480
|
+
from pypdf.generic import ArrayObject, IndirectObject, NameObject, NullObject, NumberObject # noqa: PLC0415
|
|
481
|
+
|
|
482
|
+
def obj(v):
|
|
483
|
+
return v.get_object() if isinstance(v, IndirectObject) else v
|
|
484
|
+
|
|
485
|
+
def dead(d):
|
|
486
|
+
d = obj(d)
|
|
487
|
+
if hasattr(d, "get") and not isinstance(d, list): # an action, or a destination dictionary
|
|
488
|
+
d = obj(d.get("/D")) if d.get("/S", "/GoTo") == "/GoTo" else None
|
|
489
|
+
return isinstance(d, list) and len(d) > 0 and isinstance(d[0], IndirectObject) \
|
|
490
|
+
and isinstance(d[0].get_object(), NullObject)
|
|
491
|
+
|
|
492
|
+
def goes_nowhere(item):
|
|
493
|
+
return dead(item.get("/Dest")) or ("/A" in item and dead(item["/A"]))
|
|
494
|
+
|
|
495
|
+
kept_annots = set()
|
|
496
|
+
for page in writer.pages:
|
|
497
|
+
annots = obj(page.get("/Annots"))
|
|
498
|
+
if not isinstance(annots, list):
|
|
499
|
+
continue
|
|
500
|
+
alive = ArrayObject(a for a in annots if not goes_nowhere(obj(a)))
|
|
501
|
+
if len(alive) != len(annots):
|
|
502
|
+
page[NameObject("/Annots")] = alive
|
|
503
|
+
kept_annots.update(a.idnum for a in alive if isinstance(a, IndirectObject))
|
|
504
|
+
|
|
505
|
+
outlines = obj(root.get("/Outlines"))
|
|
506
|
+
if outlines is not None and hasattr(outlines, "get"):
|
|
507
|
+
def prune(parent):
|
|
508
|
+
"""Unlink the children that go nowhere; returns the open-descendant count for /Count."""
|
|
509
|
+
items, child = [], parent.get("/First")
|
|
510
|
+
while child is not None:
|
|
511
|
+
items.append(child)
|
|
512
|
+
child = obj(child).get("/Next")
|
|
513
|
+
kept, visible = [], 0
|
|
514
|
+
for ref in items:
|
|
515
|
+
item = obj(ref)
|
|
516
|
+
if goes_nowhere(item):
|
|
517
|
+
if item.get("/First") is None:
|
|
518
|
+
continue
|
|
519
|
+
for key in ("/Dest", "/A"):
|
|
520
|
+
if key in item:
|
|
521
|
+
del item[NameObject(key)]
|
|
522
|
+
sub = prune(item)
|
|
523
|
+
if "/Count" in item:
|
|
524
|
+
item[NameObject("/Count")] = NumberObject(sub if int(item["/Count"]) > 0 else -sub)
|
|
525
|
+
kept.append(ref)
|
|
526
|
+
visible += 1 + (sub if int(item.get("/Count", 0)) > 0 else 0)
|
|
527
|
+
for key in ("/First", "/Last"):
|
|
528
|
+
if key in parent:
|
|
529
|
+
del parent[NameObject(key)]
|
|
530
|
+
for i, ref in enumerate(kept):
|
|
531
|
+
item = obj(ref)
|
|
532
|
+
for key, other in (("/Prev", kept[i - 1] if i else None), ("/Next", kept[i + 1] if i + 1 < len(kept) else None)):
|
|
533
|
+
if other is None:
|
|
534
|
+
if key in item:
|
|
535
|
+
del item[NameObject(key)]
|
|
536
|
+
else:
|
|
537
|
+
item[NameObject(key)] = other
|
|
538
|
+
if kept:
|
|
539
|
+
parent[NameObject("/First")], parent[NameObject("/Last")] = kept[0], kept[-1]
|
|
540
|
+
return visible
|
|
541
|
+
visible = prune(outlines)
|
|
542
|
+
if visible or outlines.get("/First") is not None:
|
|
543
|
+
if "/Count" in outlines:
|
|
544
|
+
outlines[NameObject("/Count")] = NumberObject(visible)
|
|
545
|
+
else:
|
|
546
|
+
del root[NameObject("/Outlines")]
|
|
547
|
+
|
|
548
|
+
form = obj(root.get("/AcroForm"))
|
|
549
|
+
if form is not None and isinstance(obj(form.get("/Fields")), list):
|
|
550
|
+
def keep_field(ref):
|
|
551
|
+
field = obj(ref)
|
|
552
|
+
if isinstance(field, NullObject) or field is None:
|
|
553
|
+
return False
|
|
554
|
+
kids = obj(field.get("/Kids"))
|
|
555
|
+
if isinstance(kids, list) and len(kids):
|
|
556
|
+
alive = [k for k in kids if keep_field(k)]
|
|
557
|
+
if len(alive) != len(kids):
|
|
558
|
+
field[NameObject("/Kids")] = ArrayObject(alive)
|
|
559
|
+
return bool(alive)
|
|
560
|
+
if field.get("/Subtype") == "/Widget": # a widget belongs to the page whose /Annots lists it
|
|
561
|
+
if isinstance(ref, IndirectObject):
|
|
562
|
+
return ref.idnum in kept_annots
|
|
563
|
+
return not isinstance(obj(field.get("/P")), NullObject)
|
|
564
|
+
return True # a field with no widget is on no page: it stays
|
|
565
|
+
fields = obj(form["/Fields"])
|
|
566
|
+
alive = ArrayObject(f for f in fields if keep_field(f))
|
|
567
|
+
if len(alive) != len(fields):
|
|
568
|
+
form[NameObject("/Fields")] = alive
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def _locked_page_count(source):
|
|
572
|
+
"""A password-locked PDF's page count from its page tree's /Count, or None when it cannot be read without the
|
|
573
|
+
password (the tree sits in an encrypted object stream, or pypdf is not installed)."""
|
|
574
|
+
try:
|
|
575
|
+
import io # noqa: PLC0415
|
|
576
|
+
import pypdf # noqa: PLC0415
|
|
577
|
+
reader = pypdf.PdfReader(io.BytesIO(bytes(source)) if isinstance(source, (bytes, bytearray)) else source, strict=False)
|
|
578
|
+
if not reader.is_encrypted:
|
|
579
|
+
return None
|
|
580
|
+
reader._encryption = None # noqa: SLF001 - pypdf refuses every object until decrypted; /Count is not encrypted
|
|
581
|
+
count = reader.trailer["/Root"]["/Pages"]["/Count"]
|
|
582
|
+
return int(count) if isinstance(count, int) and count >= 0 else None
|
|
583
|
+
except Exception: # noqa: BLE001 - nothing readable: the file stays locked and the count is labelled unavailable
|
|
584
|
+
return None
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
class Document:
|
|
588
|
+
def __init__(self, source, count_only_if_locked=False):
|
|
589
|
+
self._source = source
|
|
590
|
+
self.locked = False
|
|
591
|
+
self._struct = None
|
|
592
|
+
self.engine = {"name": NAME, **versions()}
|
|
593
|
+
try:
|
|
594
|
+
self._pdf = pdfium.PdfDocument(bytes(source) if isinstance(source, (bytes, bytearray)) else source)
|
|
595
|
+
except pdfium.PdfiumError as error:
|
|
596
|
+
if "password" not in str(error).lower():
|
|
597
|
+
raise
|
|
598
|
+
# PDFium will not open a locked file at all. For the page count only, the page tree's /Count (a plain
|
|
599
|
+
# number, never encrypted) is read through pypdf; when that cannot be read the file stays locked.
|
|
600
|
+
counted = _locked_page_count(source) if count_only_if_locked else None
|
|
601
|
+
if counted is None:
|
|
602
|
+
raise PermissionError("the PDF needs a password") from error
|
|
603
|
+
self._pdf, self.locked, self.page_count = None, True, counted
|
|
604
|
+
return
|
|
605
|
+
self.page_count = len(self._pdf)
|
|
606
|
+
|
|
607
|
+
def page(self, number):
|
|
608
|
+
if self.locked:
|
|
609
|
+
raise PermissionError("the PDF needs a password")
|
|
610
|
+
if not 0 <= number < self.page_count:
|
|
611
|
+
raise IndexError("page %d of %d" % (number + 1, self.page_count))
|
|
612
|
+
return Page(self, number)
|
|
613
|
+
|
|
614
|
+
def page_size(self, number):
|
|
615
|
+
"""A page's displayed size, `Page.size`, from the page tree alone: the crop box clipped to the media box, turned
|
|
616
|
+
by /Rotate. PDFium's page load parses every content object, which the page count's bounds never need."""
|
|
617
|
+
if self.locked:
|
|
618
|
+
raise PermissionError("the PDF needs a password")
|
|
619
|
+
if not 0 <= number < self.page_count:
|
|
620
|
+
raise IndexError("page %d of %d" % (number + 1, self.page_count))
|
|
621
|
+
size = R.FS_SIZEF()
|
|
622
|
+
if not R.FPDF_GetPageSizeByIndexF(self._pdf.raw, number, size):
|
|
623
|
+
return Page(self, number).size # PDFium could not read the box without the page: load it once
|
|
624
|
+
return (size.width, size.height)
|
|
625
|
+
|
|
626
|
+
def _structure(self):
|
|
627
|
+
"""The document's structure through pypdf (layers and their membership dictionaries); PDFium has no call."""
|
|
628
|
+
if self._struct is None:
|
|
629
|
+
import io
|
|
630
|
+
src = io.BytesIO(bytes(self._source)) if isinstance(self._source, (bytes, bytearray)) else self._source
|
|
631
|
+
try:
|
|
632
|
+
import pypdf # noqa: PLC0415 - the layer structure needs it; without it the pages read with no layers
|
|
633
|
+
reader = pypdf.PdfReader(src, strict=False)
|
|
634
|
+
if reader.is_encrypted:
|
|
635
|
+
reader.decrypt("")
|
|
636
|
+
props = reader.trailer["/Root"].get("/OCProperties")
|
|
637
|
+
props = props.get_object() if props is not None else None
|
|
638
|
+
except Exception as error: # noqa: BLE001 - nothing refuses: the page still reads, labelled
|
|
639
|
+
# PDFium opened (and repaired) a file pypdf cannot parse. Its text and linework still read; it reads as
|
|
640
|
+
# having no layers, and `structure_error` says so for the reader to label.
|
|
641
|
+
self._pypdf = None
|
|
642
|
+
self._struct = {"layers": [], "error": type(error).__name__}
|
|
643
|
+
return self._struct
|
|
644
|
+
self._pypdf = reader
|
|
645
|
+
def ref(o):
|
|
646
|
+
return getattr(o, "idnum", None) or id(o.get_object())
|
|
647
|
+
ocgs, off = [], set()
|
|
648
|
+
if props is not None:
|
|
649
|
+
ocgs = list(props.get("/OCGs", []))
|
|
650
|
+
d = props.get("/D")
|
|
651
|
+
if d is not None:
|
|
652
|
+
d = d.get_object()
|
|
653
|
+
if str(d.get("/BaseState", "/ON")) == "/OFF":
|
|
654
|
+
# Every layer starts off; /ON turns some back on (/OFF is then redundant).
|
|
655
|
+
on = {ref(o) for o in d.get("/ON", [])}
|
|
656
|
+
off = {ref(o) for o in ocgs} - on
|
|
657
|
+
else:
|
|
658
|
+
off = {ref(o) for o in d.get("/OFF", [])}
|
|
659
|
+
self._struct = {"layers": [{"name": str(o.get_object().get("/Name", "")), "on": ref(o) not in off}
|
|
660
|
+
for o in ocgs]}
|
|
661
|
+
return self._struct
|
|
662
|
+
|
|
663
|
+
def _ocmd_layer(self, number, mark):
|
|
664
|
+
"""The layer of content under a membership dictionary (OCMD). PDFium names the mark's keys but does not hand
|
|
665
|
+
over its /OCGs array, so the page's OCMDs are read through pypdf and matched by their /P policy. The name is
|
|
666
|
+
the LAST layer the OCMD lists, as MuPDF reads it. Two OCMDs on one page with the same policy and different
|
|
667
|
+
layers cannot be told apart this way; such content reads as outside any layer (a stated limit)."""
|
|
668
|
+
n = ctypes.c_ulong()
|
|
669
|
+
policy = "AnyOn"
|
|
670
|
+
if R.FPDFPageObjMark_GetParamStringValue(mark, b"P", _BUF, ctypes.sizeof(_BUF), ctypes.byref(n)):
|
|
671
|
+
policy = bytes(_BUF)[:max(0, n.value - 2)].decode("utf-16-le", "replace").lstrip("/")
|
|
672
|
+
found = {(name, hidden) for p, name, hidden in self._ocmds(number) if p == policy}
|
|
673
|
+
return found.pop() if len(found) == 1 else ("", False)
|
|
674
|
+
|
|
675
|
+
def _ocmds(self, number):
|
|
676
|
+
cache = self._structure().setdefault("ocmds", {})
|
|
677
|
+
if number not in cache:
|
|
678
|
+
found = []
|
|
679
|
+
reader = self._reader()
|
|
680
|
+
if reader is None: # pypdf could not parse the file: no membership dictionaries to read
|
|
681
|
+
cache[number] = found
|
|
682
|
+
return found
|
|
683
|
+
page = reader.pages[number]
|
|
684
|
+
|
|
685
|
+
def visit(resources, depth):
|
|
686
|
+
if resources is None or depth > 8:
|
|
687
|
+
return
|
|
688
|
+
resources = resources.get_object()
|
|
689
|
+
for value in (resources.get("/Properties") or {}).values():
|
|
690
|
+
d = value.get_object()
|
|
691
|
+
if d.get("/Type") == "/OCMD":
|
|
692
|
+
state = self._ocmd_state(d)
|
|
693
|
+
if state is not None:
|
|
694
|
+
found.append(state)
|
|
695
|
+
for x in (resources.get("/XObject") or {}).values():
|
|
696
|
+
x = x.get_object()
|
|
697
|
+
if x.get("/Subtype") == "/Form":
|
|
698
|
+
visit(x.get("/Resources"), depth + 1)
|
|
699
|
+
visit(page.get("/Resources"), 0)
|
|
700
|
+
cache[number] = found
|
|
701
|
+
return cache[number]
|
|
702
|
+
|
|
703
|
+
def _ocmd_state(self, d):
|
|
704
|
+
"""(policy, layer name, hidden) of a membership dictionary; None when it lists no layer."""
|
|
705
|
+
ocgs = d.get("/OCGs")
|
|
706
|
+
ocgs = ocgs.get_object() if ocgs is not None else []
|
|
707
|
+
ocgs = list(ocgs) if isinstance(ocgs, list) else [ocgs]
|
|
708
|
+
if not ocgs:
|
|
709
|
+
return None
|
|
710
|
+
policy = str(d.get("/P", "/AnyOn")).lstrip("/")
|
|
711
|
+
off = self._off_names()
|
|
712
|
+
state = [str(o.get_object().get("/Name", "")) not in off for o in ocgs]
|
|
713
|
+
visible = {"AnyOn": any(state), "AllOn": all(state), "AnyOff": not all(state),
|
|
714
|
+
"AllOff": not any(state)}.get(policy, any(state))
|
|
715
|
+
return policy, str(ocgs[-1].get_object().get("/Name", "")), not visible
|
|
716
|
+
|
|
717
|
+
def _form_oc(self, xobj):
|
|
718
|
+
"""(layer, hidden) a Form XObject's own /OC entry gives its content ('' and False when it has none)."""
|
|
719
|
+
oc = xobj.get("/OC")
|
|
720
|
+
if oc is None:
|
|
721
|
+
return "", False
|
|
722
|
+
d = oc.get_object()
|
|
723
|
+
if d.get("/Type") == "/OCMD":
|
|
724
|
+
state = self._ocmd_state(d)
|
|
725
|
+
return ("", False) if state is None else (state[1], state[2])
|
|
726
|
+
name = str(d.get("/Name", ""))
|
|
727
|
+
return name, name in self._off_names()
|
|
728
|
+
|
|
729
|
+
def _form_xobjects(self, contents, resources):
|
|
730
|
+
"""The Form XObjects one content stream paints, in the order it paints them (pypdf objects)."""
|
|
731
|
+
from pypdf.generic import ContentStream # noqa: PLC0415
|
|
732
|
+
if contents is None:
|
|
733
|
+
return []
|
|
734
|
+
res = resources.get_object() if resources is not None else {}
|
|
735
|
+
xobjs = res.get("/XObject") if res is not None else None
|
|
736
|
+
xobjs = xobjs.get_object() if xobjs is not None else {}
|
|
737
|
+
cs = contents if isinstance(contents, ContentStream) else ContentStream(contents.get_object(), self._pypdf)
|
|
738
|
+
out = []
|
|
739
|
+
for operands, op in cs.operations:
|
|
740
|
+
if op == b"Do" and operands:
|
|
741
|
+
x = xobjs.get(operands[0])
|
|
742
|
+
x = x.get_object() if x is not None else None
|
|
743
|
+
if x is not None and x.get("/Subtype") == "/Form":
|
|
744
|
+
out.append(x)
|
|
745
|
+
return out
|
|
746
|
+
|
|
747
|
+
def _off_names(self):
|
|
748
|
+
return {l["name"] for l in self._structure()["layers"] if not l["on"]}
|
|
749
|
+
|
|
750
|
+
def _reader(self):
|
|
751
|
+
self._structure()
|
|
752
|
+
return self._pypdf
|
|
753
|
+
|
|
754
|
+
@property
|
|
755
|
+
def is_pdf(self):
|
|
756
|
+
return True # PDFium opens nothing else
|
|
757
|
+
|
|
758
|
+
def write_pages(self, numbers, out_path, source_sha256=None):
|
|
759
|
+
"""The document narrowed to the 0-based `numbers`, in that order (plan 5.5, slice 2 S2-7): pypdf removes the
|
|
760
|
+
other pages from the ORIGINAL document, so its layers, their defaults, forms and names stay; `/Info` and the
|
|
761
|
+
XMP metadata go; the source's /ID is kept, and a source without one gets an id derived from its sha256 and the
|
|
762
|
+
choice (never random), so the same choice gives the same bytes. Written unencrypted. Raises StructureError
|
|
763
|
+
when pypdf cannot read the document (the caller decides how to go on, S2-5)."""
|
|
764
|
+
import hashlib # noqa: PLC0415
|
|
765
|
+
import io # noqa: PLC0415
|
|
766
|
+
try:
|
|
767
|
+
import pypdf # noqa: PLC0415
|
|
768
|
+
from pypdf.generic import ArrayObject, ByteStringObject, NameObject # noqa: PLC0415
|
|
769
|
+
src = io.BytesIO(bytes(self._source)) if isinstance(self._source, (bytes, bytearray)) else self._source
|
|
770
|
+
reader = pypdf.PdfReader(src, strict=False)
|
|
771
|
+
if reader.is_encrypted and not reader.decrypt(""):
|
|
772
|
+
raise PermissionError("the PDF needs a password")
|
|
773
|
+
writer = pypdf.PdfWriter(clone_from=reader)
|
|
774
|
+
except PermissionError:
|
|
775
|
+
raise
|
|
776
|
+
except Exception as error: # noqa: BLE001 - named for the caller's label
|
|
777
|
+
raise StructureError(type(error).__name__) from error
|
|
778
|
+
keep = list(numbers)
|
|
779
|
+
pages = list(writer.pages)
|
|
780
|
+
chosen = [pages[n].indirect_reference for n in keep]
|
|
781
|
+
for n in sorted(set(range(len(pages))) - set(keep), reverse=True):
|
|
782
|
+
writer.remove_page(n, clean=True)
|
|
783
|
+
if keep != sorted(keep): # the choice's own order, as MuPDF's select keeps it
|
|
784
|
+
kids = writer._pages.get_object()["/Kids"] # noqa: SLF001 - pypdf has no public reorder
|
|
785
|
+
kids.clear()
|
|
786
|
+
kids.extend(chosen)
|
|
787
|
+
root = writer._root_object # noqa: SLF001
|
|
788
|
+
_prune_removed_targets(writer, root)
|
|
789
|
+
if NameObject("/Metadata") in root:
|
|
790
|
+
del root[NameObject("/Metadata")]
|
|
791
|
+
writer._info = None # noqa: SLF001 - no /Info, no dates
|
|
792
|
+
if not getattr(writer, "_ID", None):
|
|
793
|
+
seed = hashlib.md5(("floless-piece\0%s\0%s" % (source_sha256 or "", ",".join(map(str, keep)))).encode()).digest()
|
|
794
|
+
writer._ID = ArrayObject([ByteStringObject(seed), ByteStringObject(seed)]) # noqa: SLF001
|
|
795
|
+
writer.compress_identical_objects(remove_duplicates=False, remove_unreferenced=True)
|
|
796
|
+
_drop_unreachable(writer)
|
|
797
|
+
with open(out_path, "wb") as f:
|
|
798
|
+
writer.write(f)
|
|
799
|
+
return {"pages": len(keep), "structureError": None, "labels": []}
|
|
800
|
+
|
|
801
|
+
def copy_pages(self, numbers, out_path):
|
|
802
|
+
"""The last resort when pypdf cannot read the document and PyMuPDF is not installed: PDFium copies the pages
|
|
803
|
+
into a NEW document. The document's layer settings, forms and names do not come along, so a hidden layer can
|
|
804
|
+
show; the caller labels the piece with exactly that (S2-5)."""
|
|
805
|
+
new = pdfium.PdfDocument.new()
|
|
806
|
+
try:
|
|
807
|
+
new.import_pages(self._pdf, list(numbers))
|
|
808
|
+
new.save(out_path)
|
|
809
|
+
return {"pages": len(new)}
|
|
810
|
+
finally:
|
|
811
|
+
new.close()
|
|
812
|
+
|
|
813
|
+
def layers(self):
|
|
814
|
+
return list(self._structure()["layers"])
|
|
815
|
+
|
|
816
|
+
def structure_error(self):
|
|
817
|
+
"""Why the layer structure could not be read (pypdf's error class), or None. The pages still read, without
|
|
818
|
+
layers; a reader labels its result with this instead of refusing."""
|
|
819
|
+
return self._structure().get("error")
|
|
820
|
+
|
|
821
|
+
def close(self):
|
|
822
|
+
if self._pdf is not None: # None for a locked file opened for its page count only
|
|
823
|
+
self._pdf.close()
|