ctkpdfium 1.0.0__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.
- ctkpdfium/__init__.py +4 -0
- ctkpdfium/ctkpdfium.py +598 -0
- ctkpdfium/geometry.py +73 -0
- ctkpdfium/py.typed +0 -0
- ctkpdfium/renderer.py +149 -0
- ctkpdfium-1.0.0.dist-info/METADATA +238 -0
- ctkpdfium-1.0.0.dist-info/RECORD +9 -0
- ctkpdfium-1.0.0.dist-info/WHEEL +4 -0
- ctkpdfium-1.0.0.dist-info/licenses/LICENSE +21 -0
ctkpdfium/__init__.py
ADDED
ctkpdfium/ctkpdfium.py
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
import queue
|
|
6
|
+
import sys
|
|
7
|
+
import tkinter as tk
|
|
8
|
+
from bisect import bisect_left, bisect_right
|
|
9
|
+
from collections import OrderedDict
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
|
|
13
|
+
import customtkinter as ctk
|
|
14
|
+
from PIL import Image, ImageTk
|
|
15
|
+
|
|
16
|
+
from .geometry import Box, PageGeometry, PageSelection
|
|
17
|
+
from .renderer import DocumentResult, Renderer, RenderRequest
|
|
18
|
+
|
|
19
|
+
PageChangeCallback = Callable[[int, int], None]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CTkPdfiumNavigation(ctk.CTkFrame):
|
|
23
|
+
def __init__(self, viewer: CTkPdfium, *, overlay: bool = True, **kwargs: Any) -> None:
|
|
24
|
+
defaults = dict(corner_radius=18, border_width=1,
|
|
25
|
+
fg_color=('gray92', 'gray16'), border_color=('gray78', 'gray28'))
|
|
26
|
+
defaults.update(kwargs)
|
|
27
|
+
super().__init__(viewer.get_container_frame(), **defaults)
|
|
28
|
+
self._viewer = viewer
|
|
29
|
+
self._page_var = tk.StringVar(self, value=str(viewer.current_page))
|
|
30
|
+
self._previous_button = ctk.CTkButton(self, text='←', width=36, command=viewer.previous_page)
|
|
31
|
+
self._previous_button.grid(row=0, column=0, padx=(8, 4), pady=8)
|
|
32
|
+
self._page_entry = ctk.CTkEntry(self, width=56, textvariable=self._page_var, justify='center')
|
|
33
|
+
self._page_entry.grid(row=0, column=1, padx=4, pady=8)
|
|
34
|
+
self._page_entry.bind('<Return>', self._submit)
|
|
35
|
+
self._page_entry.bind('<FocusOut>', lambda e: self._page_var.set(str(viewer.current_page)))
|
|
36
|
+
self._count = ctk.CTkLabel(self, width=52, text='')
|
|
37
|
+
self._count.grid(row=0, column=2, padx=4, pady=8)
|
|
38
|
+
self._next_button = ctk.CTkButton(self, text='→', width=36, command=viewer.next_page)
|
|
39
|
+
self._next_button.grid(row=0, column=3, padx=(4, 8), pady=8)
|
|
40
|
+
viewer.add_page_change_callback(self._changed)
|
|
41
|
+
self._changed(viewer.current_page, viewer.page_count)
|
|
42
|
+
if overlay:
|
|
43
|
+
self.place(relx=.5, rely=1, anchor='s', y=-12)
|
|
44
|
+
|
|
45
|
+
def _submit(self, _: Any) -> None:
|
|
46
|
+
try:
|
|
47
|
+
self._viewer.go_to_page(int(self._page_var.get()))
|
|
48
|
+
except ValueError:
|
|
49
|
+
pass
|
|
50
|
+
self._page_var.set(str(self._viewer.current_page))
|
|
51
|
+
|
|
52
|
+
def _changed(self, current: int, count: int) -> None:
|
|
53
|
+
self._page_var.set(str(current))
|
|
54
|
+
self._count.configure(text=f'/ {count}')
|
|
55
|
+
self._page_entry.configure(state='normal' if count else 'disabled')
|
|
56
|
+
self._previous_button.configure(state='normal' if current > 1 else 'disabled')
|
|
57
|
+
self._next_button.configure(state='normal' if current < count else 'disabled')
|
|
58
|
+
|
|
59
|
+
def destroy(self) -> None:
|
|
60
|
+
self._viewer.remove_page_change_callback(self._changed)
|
|
61
|
+
super().destroy()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class CTkPdfium(ctk.CTkFrame):
|
|
65
|
+
"""Virtualized, fit-width PDF viewer. All public methods run on the Tk thread."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, master: Any, file: str | os.PathLike[str], *,
|
|
68
|
+
page_cache_size: int = 8, cache_memory_limit: int = 128 * 1024 * 1024,
|
|
69
|
+
width: int | None = None, height: int | None = None,
|
|
70
|
+
navigation_overlay: bool = False,
|
|
71
|
+
on_load: Callable[[CTkPdfium], None] | None = None,
|
|
72
|
+
on_error: Callable[[int | None, str], None] | None = None,
|
|
73
|
+
translate: Callable[[str], str] = lambda s: s,
|
|
74
|
+
**kwargs: Any) -> None:
|
|
75
|
+
path = Path(file).expanduser()
|
|
76
|
+
if not path.is_file():
|
|
77
|
+
raise FileNotFoundError(path)
|
|
78
|
+
self._destroyed = False
|
|
79
|
+
self._ready = False
|
|
80
|
+
super().__init__(master, width=width or 800, height=height or 600, **kwargs)
|
|
81
|
+
self._ = translate
|
|
82
|
+
self._on_load = on_load
|
|
83
|
+
self._on_error = on_error
|
|
84
|
+
self.page_count = 0
|
|
85
|
+
self.pages: tuple[PageGeometry, ...] = ()
|
|
86
|
+
self._current_page_index = -1
|
|
87
|
+
self._early_page = 1
|
|
88
|
+
self._page_change_callbacks: list[PageChangeCallback] = []
|
|
89
|
+
self._selection_callbacks: list[Callable[[PageSelection | None], None]] = []
|
|
90
|
+
self.navigation_overlay: CTkPdfiumNavigation | None = None
|
|
91
|
+
self._page_cache_size = max(1, page_cache_size)
|
|
92
|
+
self._memory_limit = max(1024 * 1024, cache_memory_limit)
|
|
93
|
+
self._cache: OrderedDict[int, tuple[Image.Image, int]] = OrderedDict()
|
|
94
|
+
self._photos: dict[int, tuple[ImageTk.PhotoImage, tuple[int, int, int]]] = {}
|
|
95
|
+
self._cache_bytes = 0
|
|
96
|
+
self._errors: dict[int, str] = {}
|
|
97
|
+
self._items: dict[int, tuple[int, int, int]] = {}
|
|
98
|
+
self._requests: dict[int, RenderRequest] = {}
|
|
99
|
+
self._generation = 0
|
|
100
|
+
self._page_width = 0
|
|
101
|
+
self._tops: list[float] = []
|
|
102
|
+
self._bottoms: list[float] = []
|
|
103
|
+
self._total_height = 1.0
|
|
104
|
+
self._layout_job: str | None = None
|
|
105
|
+
self._refresh_job: str | None = None
|
|
106
|
+
self._poll_job: str | None = None
|
|
107
|
+
self._selection: PageSelection | None = None
|
|
108
|
+
self._selection_image: Image.Image | None = None
|
|
109
|
+
self._overlay_photo: ImageTk.PhotoImage | None = None
|
|
110
|
+
self._overlay_size: tuple[int, int, int, int] | None = None
|
|
111
|
+
self._drag: tuple[str, float, float, Box] | None = None
|
|
112
|
+
self._wheel_remainder = 0.0
|
|
113
|
+
self.grid_rowconfigure(0, weight=1)
|
|
114
|
+
self.grid_columnconfigure(0, weight=1)
|
|
115
|
+
self.canvas = tk.Canvas(self, highlightthickness=0, borderwidth=0, takefocus=True)
|
|
116
|
+
self.canvas.grid(row=0, column=0, sticky='nsew', padx=2, pady=2)
|
|
117
|
+
self._scrollbar = ctk.CTkScrollbar(self, command=self._scroll)
|
|
118
|
+
self._scrollbar.grid(row=0, column=1, sticky='ns', pady=2)
|
|
119
|
+
self.canvas.configure(yscrollcommand=self._scrollbar.set)
|
|
120
|
+
self.canvas.bind('<Configure>', self._configure_view)
|
|
121
|
+
self.canvas.bind('<MouseWheel>', self._wheel)
|
|
122
|
+
self.canvas.bind('<Button-4>', lambda e: self._wheel(e, -1))
|
|
123
|
+
self.canvas.bind('<Button-5>', lambda e: self._wheel(e, 1))
|
|
124
|
+
self.canvas.bind('<Prior>', lambda e: self._key_page(-1))
|
|
125
|
+
self.canvas.bind('<Next>', lambda e: self._key_page(1))
|
|
126
|
+
self.canvas.bind('<Home>', lambda e: self._key_page(-self.page_count))
|
|
127
|
+
self.canvas.bind('<End>', lambda e: self._key_page(self.page_count))
|
|
128
|
+
self.canvas.bind('<ButtonPress-1>', self._press)
|
|
129
|
+
self.canvas.bind('<B1-Motion>', self._motion)
|
|
130
|
+
self.canvas.bind('<ButtonRelease-1>', self._release)
|
|
131
|
+
self._ready = True
|
|
132
|
+
self._apply_colors()
|
|
133
|
+
self._status = self.canvas.create_text(20, 20, anchor='nw',
|
|
134
|
+
text=self._('Loading PDF…'), fill='gray60')
|
|
135
|
+
self._renderer = Renderer(path)
|
|
136
|
+
self._poll_job = self.after(20, self._poll)
|
|
137
|
+
if navigation_overlay:
|
|
138
|
+
self.attach_navigation_overlay()
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def current_page(self) -> int:
|
|
142
|
+
return self._current_page_index + 1
|
|
143
|
+
|
|
144
|
+
def get_current_page(self) -> int:
|
|
145
|
+
return self.current_page
|
|
146
|
+
|
|
147
|
+
def is_page_rendered(self, page_index: int) -> bool:
|
|
148
|
+
return page_index in self._cache
|
|
149
|
+
|
|
150
|
+
def get_container_frame(self) -> CTkPdfium:
|
|
151
|
+
return self
|
|
152
|
+
|
|
153
|
+
def add_page_change_callback(self, callback: PageChangeCallback) -> None:
|
|
154
|
+
if callback not in self._page_change_callbacks:
|
|
155
|
+
self._page_change_callbacks.append(callback)
|
|
156
|
+
|
|
157
|
+
def remove_page_change_callback(self, callback: PageChangeCallback) -> None:
|
|
158
|
+
if callback in self._page_change_callbacks:
|
|
159
|
+
self._page_change_callbacks.remove(callback)
|
|
160
|
+
|
|
161
|
+
def attach_navigation_overlay(self, **kwargs: Any) -> CTkPdfiumNavigation:
|
|
162
|
+
if self.navigation_overlay is None or not self.navigation_overlay.winfo_exists():
|
|
163
|
+
self.navigation_overlay = CTkPdfiumNavigation(self, **kwargs)
|
|
164
|
+
return self.navigation_overlay
|
|
165
|
+
|
|
166
|
+
def go_to_page(self, page_number: int) -> int:
|
|
167
|
+
if not self.pages:
|
|
168
|
+
self._early_page = max(1, int(page_number))
|
|
169
|
+
return 0
|
|
170
|
+
index = min(self.page_count - 1, max(0, int(page_number) - 1))
|
|
171
|
+
if not self._tops:
|
|
172
|
+
self._early_page = index + 1
|
|
173
|
+
self._layout()
|
|
174
|
+
if not self._tops:
|
|
175
|
+
return 0
|
|
176
|
+
self.canvas.yview_moveto(max(0, self._tops[index] - self._padding()) / self._total_height)
|
|
177
|
+
self._refresh()
|
|
178
|
+
self._set_current_page(index)
|
|
179
|
+
return self.current_page
|
|
180
|
+
|
|
181
|
+
def next_page(self) -> int:
|
|
182
|
+
return self.go_to_page(self.current_page + 1)
|
|
183
|
+
|
|
184
|
+
def previous_page(self) -> int:
|
|
185
|
+
return self.go_to_page(self.current_page - 1)
|
|
186
|
+
|
|
187
|
+
def _key_page(self, delta: int) -> str:
|
|
188
|
+
self.go_to_page(self.current_page + delta)
|
|
189
|
+
return 'break'
|
|
190
|
+
|
|
191
|
+
def _set_current_page(self, index: int) -> None:
|
|
192
|
+
if self._current_page_index != index:
|
|
193
|
+
self._current_page_index = index
|
|
194
|
+
for callback in tuple(self._page_change_callbacks):
|
|
195
|
+
self._call(callback, self.current_page, self.page_count)
|
|
196
|
+
|
|
197
|
+
def _call(self, callback: Callable[..., Any], *args: Any) -> None:
|
|
198
|
+
try:
|
|
199
|
+
callback(*args)
|
|
200
|
+
except Exception:
|
|
201
|
+
self._root().report_callback_exception(*sys.exc_info())
|
|
202
|
+
|
|
203
|
+
def _padding(self) -> float:
|
|
204
|
+
return round(18 * self._get_widget_scaling())
|
|
205
|
+
|
|
206
|
+
def _apply_colors(self) -> None:
|
|
207
|
+
background = self.cget('fg_color')
|
|
208
|
+
if background == 'transparent':
|
|
209
|
+
background = self.cget('bg_color')
|
|
210
|
+
color = self._apply_appearance_mode(background)
|
|
211
|
+
self.canvas.configure(bg=color)
|
|
212
|
+
|
|
213
|
+
def _set_appearance_mode(self, mode_string: str) -> None:
|
|
214
|
+
super()._set_appearance_mode(mode_string)
|
|
215
|
+
if self._ready:
|
|
216
|
+
self._apply_colors()
|
|
217
|
+
|
|
218
|
+
def _set_scaling(self, new_widget_scaling: float, new_window_scaling: float) -> None:
|
|
219
|
+
super()._set_scaling(new_widget_scaling, new_window_scaling)
|
|
220
|
+
if self._ready:
|
|
221
|
+
self._configure_view()
|
|
222
|
+
|
|
223
|
+
def _configure_view(self, _: Any = None) -> None:
|
|
224
|
+
if self._destroyed:
|
|
225
|
+
return
|
|
226
|
+
if self._layout_job is not None:
|
|
227
|
+
self.after_cancel(self._layout_job)
|
|
228
|
+
self._layout_job = self.after(80, self._layout)
|
|
229
|
+
|
|
230
|
+
def _layout(self) -> None:
|
|
231
|
+
if self._layout_job is not None:
|
|
232
|
+
self.after_cancel(self._layout_job)
|
|
233
|
+
self._layout_job = None
|
|
234
|
+
if self._destroyed or not self.pages:
|
|
235
|
+
return
|
|
236
|
+
if self.canvas.winfo_width() <= 1:
|
|
237
|
+
self._configure_view()
|
|
238
|
+
return
|
|
239
|
+
width = max(1, int(self.canvas.winfo_width() - self._padding() * 2))
|
|
240
|
+
if width == self._page_width and self._tops:
|
|
241
|
+
self._total_height = max(self._bottoms[-1] + self._padding(),
|
|
242
|
+
self._tops[-1] + self.canvas.winfo_height() - self._padding())
|
|
243
|
+
self.canvas.configure(scrollregion=(0, 0, self.canvas.winfo_width(), self._total_height))
|
|
244
|
+
self._refresh()
|
|
245
|
+
return
|
|
246
|
+
anchor_page = max(0, self._current_page_index) if self._tops else min(self.page_count - 1, self._early_page - 1)
|
|
247
|
+
offset = 0.0
|
|
248
|
+
if self._tops:
|
|
249
|
+
offset = (self.canvas.canvasy(0) - self._tops[anchor_page]) / max(1, self._bottoms[anchor_page] - self._tops[anchor_page])
|
|
250
|
+
self._page_width = width
|
|
251
|
+
self._generation += 1
|
|
252
|
+
self._requests.clear()
|
|
253
|
+
for image, _ in self._cache.values():
|
|
254
|
+
image.close()
|
|
255
|
+
self._cache.clear()
|
|
256
|
+
self._photos.clear()
|
|
257
|
+
self._cache_bytes = 0
|
|
258
|
+
self.canvas.delete('page')
|
|
259
|
+
self._items.clear()
|
|
260
|
+
self._tops.clear()
|
|
261
|
+
self._bottoms.clear()
|
|
262
|
+
top = self._padding()
|
|
263
|
+
for page in self.pages:
|
|
264
|
+
self._tops.append(top)
|
|
265
|
+
self._bottoms.append(top + width * page.height / page.width)
|
|
266
|
+
top = self._bottoms[-1] + self._padding()
|
|
267
|
+
# Allow even a short last page to align above the floating navigation.
|
|
268
|
+
self._total_height = max(top, self._tops[-1] + self.canvas.winfo_height() - self._padding())
|
|
269
|
+
self.canvas.configure(scrollregion=(0, 0, self.canvas.winfo_width(), self._total_height))
|
|
270
|
+
y = self._tops[anchor_page] + offset * (self._bottoms[anchor_page] - self._tops[anchor_page])
|
|
271
|
+
self.canvas.yview_moveto(max(0, y) / self._total_height)
|
|
272
|
+
self._refresh()
|
|
273
|
+
|
|
274
|
+
def _visible_pages(self) -> list[int]:
|
|
275
|
+
if not self._tops:
|
|
276
|
+
return []
|
|
277
|
+
top = self.canvas.canvasy(0)
|
|
278
|
+
bottom = top + self.canvas.winfo_height()
|
|
279
|
+
first = min(self.page_count - 1, bisect_left(self._bottoms, top))
|
|
280
|
+
last = min(self.page_count, bisect_right(self._tops, bottom))
|
|
281
|
+
return list(range(first, max(first + 1, last)))
|
|
282
|
+
|
|
283
|
+
def _refresh(self) -> None:
|
|
284
|
+
if self._refresh_job is not None:
|
|
285
|
+
self.after_cancel(self._refresh_job)
|
|
286
|
+
self._refresh_job = None
|
|
287
|
+
if self._destroyed or not self._tops:
|
|
288
|
+
return
|
|
289
|
+
visible = self._visible_pages()
|
|
290
|
+
mid = self.canvas.canvasy(0) + self.canvas.winfo_height() / 2
|
|
291
|
+
current = min(visible, key=lambda i: abs((self._tops[i] + self._bottoms[i]) / 2 - mid))
|
|
292
|
+
self._set_current_page(current)
|
|
293
|
+
if self._destroyed:
|
|
294
|
+
return
|
|
295
|
+
active = set(visible)
|
|
296
|
+
if visible[0] > 0:
|
|
297
|
+
active.add(visible[0] - 1)
|
|
298
|
+
if visible[-1] + 1 < self.page_count:
|
|
299
|
+
active.add(visible[-1] + 1)
|
|
300
|
+
for index in set(self._items) - active:
|
|
301
|
+
for item in self._items.pop(index):
|
|
302
|
+
self.canvas.delete(item)
|
|
303
|
+
self._photos.pop(index, None)
|
|
304
|
+
x = self._padding()
|
|
305
|
+
for index in sorted(active):
|
|
306
|
+
if index not in self._items:
|
|
307
|
+
top, bottom = self._tops[index], self._bottoms[index]
|
|
308
|
+
rect = self.canvas.create_rectangle(x, top, x + self._page_width, bottom, fill='white', outline='', tags='page')
|
|
309
|
+
img = self.canvas.create_image(x, top, anchor='nw', tags='page')
|
|
310
|
+
text = self.canvas.create_text(x + self._page_width / 2, (top + bottom) / 2, tags='page', fill='gray40')
|
|
311
|
+
self._items[index] = rect, img, text
|
|
312
|
+
_, img, label = self._items[index]
|
|
313
|
+
cached = self._cache.get(index)
|
|
314
|
+
if cached is not None:
|
|
315
|
+
self._cache.move_to_end(index)
|
|
316
|
+
self._show_image(index, img, cached[0])
|
|
317
|
+
self.canvas.itemconfigure(label, text='')
|
|
318
|
+
else:
|
|
319
|
+
label_text = self._('Could not render page {page}').format(page=index + 1) if index in self._errors else self._('Page {page}').format(page=index + 1)
|
|
320
|
+
self.canvas.itemconfigure(img, image='')
|
|
321
|
+
self.canvas.itemconfigure(label, text=label_text)
|
|
322
|
+
priority = sorted(active, key=lambda i: (i not in visible, abs(i - current)))
|
|
323
|
+
self._requests = {}
|
|
324
|
+
# Bound native bitmap memory too, before rendering exceptionally large pages.
|
|
325
|
+
per_page_pixels = max(1, min(16_000_000, self._memory_limit // (8 * max(1, len(active)))))
|
|
326
|
+
for index in priority:
|
|
327
|
+
if index in self._cache or index in self._errors:
|
|
328
|
+
continue
|
|
329
|
+
height = self._bottoms[index] - self._tops[index]
|
|
330
|
+
factor = min(1.0, math.sqrt(per_page_pixels / max(1, self._page_width * height)))
|
|
331
|
+
self._requests[index] = RenderRequest(index, self._generation,
|
|
332
|
+
max(1, round(self._page_width * factor)), max(1, round(height * factor)))
|
|
333
|
+
self._renderer.request(list(self._requests.values()))
|
|
334
|
+
self._trim_cache(active)
|
|
335
|
+
self._draw_selection()
|
|
336
|
+
|
|
337
|
+
def _show_image(self, index: int, item: int, image: Image.Image) -> None:
|
|
338
|
+
height = max(1, round(self._bottoms[index] - self._tops[index]))
|
|
339
|
+
# Tall engineering drawings must not allocate a page-sized Tk image.
|
|
340
|
+
# Keep a moving strip, quantized to viewport heights to avoid uploads on every wheel tick.
|
|
341
|
+
viewport = max(1, self.canvas.winfo_height())
|
|
342
|
+
offset = max(0, self.canvas.canvasy(0) - self._tops[index])
|
|
343
|
+
start = max(0, min(height - 1, (int(offset) // viewport - 1) * viewport))
|
|
344
|
+
end = min(height, start + 3 * viewport)
|
|
345
|
+
key = (id(image), start, end)
|
|
346
|
+
existing = self._photos.get(index)
|
|
347
|
+
if existing is None or existing[1] != key:
|
|
348
|
+
crop = image.crop((0, start * image.height / height, image.width, end * image.height / height))
|
|
349
|
+
resized = crop.resize((self._page_width, end-start), Image.Resampling.BILINEAR)
|
|
350
|
+
crop.close()
|
|
351
|
+
photo = ImageTk.PhotoImage(resized, master=self.canvas)
|
|
352
|
+
resized.close()
|
|
353
|
+
self._photos[index] = (photo, key)
|
|
354
|
+
self.canvas.coords(item, self._padding(), self._tops[index] + start)
|
|
355
|
+
self.canvas.itemconfigure(item, image=self._photos[index][0])
|
|
356
|
+
|
|
357
|
+
def _trim_cache(self, active: set[int]) -> None:
|
|
358
|
+
for index in list(self._cache):
|
|
359
|
+
if len(self._cache) <= self._page_cache_size and self._cache_bytes <= self._memory_limit:
|
|
360
|
+
break
|
|
361
|
+
if index in active:
|
|
362
|
+
continue
|
|
363
|
+
image, cost = self._cache.pop(index)
|
|
364
|
+
image.close()
|
|
365
|
+
self._cache_bytes -= cost
|
|
366
|
+
|
|
367
|
+
def _scroll(self, *args: Any) -> None:
|
|
368
|
+
self.canvas.yview(*args)
|
|
369
|
+
self._schedule_refresh()
|
|
370
|
+
|
|
371
|
+
def _schedule_refresh(self) -> None:
|
|
372
|
+
# Throttle, rather than debounce: continuous scrolling still renders.
|
|
373
|
+
if self._refresh_job is None and not self._destroyed:
|
|
374
|
+
self._refresh_job = self.after(16, self._refresh)
|
|
375
|
+
|
|
376
|
+
def _wheel(self, event: Any, direction: int | None = None) -> str:
|
|
377
|
+
if direction is None:
|
|
378
|
+
amount = -event.delta if sys.platform == 'darwin' else -event.delta / 120
|
|
379
|
+
else:
|
|
380
|
+
amount = direction
|
|
381
|
+
self._wheel_remainder += amount * (8 if sys.platform == 'darwin' else 48) * self._get_widget_scaling()
|
|
382
|
+
pixels = int(self._wheel_remainder)
|
|
383
|
+
self._wheel_remainder -= pixels
|
|
384
|
+
self.canvas.yview_moveto((self.canvas.canvasy(0) + pixels) / self._total_height)
|
|
385
|
+
self._schedule_refresh()
|
|
386
|
+
return 'break'
|
|
387
|
+
|
|
388
|
+
def _poll(self) -> None:
|
|
389
|
+
self._poll_job = None
|
|
390
|
+
if self._destroyed:
|
|
391
|
+
return
|
|
392
|
+
# At most two PhotoImage uploads per tick; never monopolize Tk's event loop.
|
|
393
|
+
changed = False
|
|
394
|
+
for _ in range(2):
|
|
395
|
+
try:
|
|
396
|
+
result = self._renderer.results.get_nowait()
|
|
397
|
+
except queue.Empty:
|
|
398
|
+
break
|
|
399
|
+
if isinstance(result, DocumentResult):
|
|
400
|
+
if result.error is not None:
|
|
401
|
+
self.canvas.itemconfigure(self._status, text=self._('Could not open PDF'))
|
|
402
|
+
if self._on_error:
|
|
403
|
+
self._call(self._on_error, None, result.error)
|
|
404
|
+
return
|
|
405
|
+
self.pages = result.pages
|
|
406
|
+
self.page_count = len(result.pages)
|
|
407
|
+
self.canvas.delete(self._status)
|
|
408
|
+
self._layout()
|
|
409
|
+
self.go_to_page(self._early_page)
|
|
410
|
+
if self._on_load:
|
|
411
|
+
self._call(self._on_load, self)
|
|
412
|
+
if self._destroyed:
|
|
413
|
+
return
|
|
414
|
+
continue
|
|
415
|
+
request = result.request
|
|
416
|
+
if self._requests.get(request.page_index) != request:
|
|
417
|
+
if result.image is not None:
|
|
418
|
+
result.image.close()
|
|
419
|
+
continue
|
|
420
|
+
if result.error is not None:
|
|
421
|
+
self._errors[request.page_index] = result.error
|
|
422
|
+
if self._on_error:
|
|
423
|
+
self._call(self._on_error, request.page_index, result.error)
|
|
424
|
+
if self._destroyed:
|
|
425
|
+
return
|
|
426
|
+
elif result.image is not None:
|
|
427
|
+
cost = result.image.width * result.image.height * 4
|
|
428
|
+
old = self._cache.pop(request.page_index, None)
|
|
429
|
+
if old:
|
|
430
|
+
self._cache_bytes -= old[1]
|
|
431
|
+
old[0].close()
|
|
432
|
+
self._cache[request.page_index] = (result.image, cost)
|
|
433
|
+
self._cache_bytes += cost
|
|
434
|
+
changed = True
|
|
435
|
+
if changed and not self._destroyed:
|
|
436
|
+
self._refresh()
|
|
437
|
+
if not self._destroyed:
|
|
438
|
+
self._poll_job = self.after(20, self._poll)
|
|
439
|
+
|
|
440
|
+
def add_selection_change_callback(self, callback: Callable[[PageSelection | None], None]) -> None:
|
|
441
|
+
if callback not in self._selection_callbacks:
|
|
442
|
+
self._selection_callbacks.append(callback)
|
|
443
|
+
|
|
444
|
+
def remove_selection_change_callback(self, callback: Callable[[PageSelection | None], None]) -> None:
|
|
445
|
+
if callback in self._selection_callbacks:
|
|
446
|
+
self._selection_callbacks.remove(callback)
|
|
447
|
+
|
|
448
|
+
def get_selection(self) -> PageSelection | None:
|
|
449
|
+
return self._selection
|
|
450
|
+
|
|
451
|
+
def see_selection(self) -> None:
|
|
452
|
+
"""Bring the selected image into the viewport without changing placement."""
|
|
453
|
+
box = self._selection_canvas_box()
|
|
454
|
+
if box is not None:
|
|
455
|
+
y = (box[1] + box[3] - self.canvas.winfo_height()) / 2
|
|
456
|
+
self.canvas.yview_moveto(max(0, y) / self._total_height)
|
|
457
|
+
self._refresh()
|
|
458
|
+
|
|
459
|
+
def set_selection(self, selection: PageSelection, image: Image.Image | None = None) -> None:
|
|
460
|
+
if not 0 <= selection.page_index < self.page_count:
|
|
461
|
+
raise ValueError('Page index out of range')
|
|
462
|
+
page = self.pages[selection.page_index]
|
|
463
|
+
if not all(math.isfinite(v) for v in selection.box):
|
|
464
|
+
raise ValueError('Invalid selection bounds')
|
|
465
|
+
box = page.visual_box(selection.box)
|
|
466
|
+
if box[2] <= box[0] or box[3] <= box[1]:
|
|
467
|
+
raise ValueError('Selection must have positive area')
|
|
468
|
+
if image is not None:
|
|
469
|
+
if self._selection_image:
|
|
470
|
+
self._selection_image.close()
|
|
471
|
+
self._selection_image = image.copy()
|
|
472
|
+
self._overlay_size = None
|
|
473
|
+
self._set_visual_box(selection.page_index, box)
|
|
474
|
+
|
|
475
|
+
def clear_selection(self) -> None:
|
|
476
|
+
self._selection = None
|
|
477
|
+
if self._selection_image:
|
|
478
|
+
self._selection_image.close()
|
|
479
|
+
self._selection_image = None
|
|
480
|
+
self._overlay_photo = None
|
|
481
|
+
self._overlay_size = None
|
|
482
|
+
self.canvas.delete('selection')
|
|
483
|
+
self._notify_selection()
|
|
484
|
+
|
|
485
|
+
def _set_visual_box(self, index: int, box: Box) -> None:
|
|
486
|
+
x, y, right, bottom = box
|
|
487
|
+
width, height = right - x, bottom - y
|
|
488
|
+
page = self.pages[index]
|
|
489
|
+
if self._selection_image:
|
|
490
|
+
height = width * page.width / page.height * self._selection_image.height / self._selection_image.width
|
|
491
|
+
factor = min(1, 1 / width, 1 / height)
|
|
492
|
+
width, height = width * factor, height * factor
|
|
493
|
+
x, y = min(1 - width, max(0, x)), min(1 - height, max(0, y))
|
|
494
|
+
self._selection = PageSelection(index, page.pdf_box((x, y, x + width, y + height)))
|
|
495
|
+
self._draw_selection()
|
|
496
|
+
self._notify_selection()
|
|
497
|
+
|
|
498
|
+
def _notify_selection(self) -> None:
|
|
499
|
+
for callback in tuple(self._selection_callbacks):
|
|
500
|
+
self._call(callback, self._selection)
|
|
501
|
+
|
|
502
|
+
def _selection_canvas_box(self) -> Box | None:
|
|
503
|
+
if self._selection is None or not self._tops:
|
|
504
|
+
return None
|
|
505
|
+
index = self._selection.page_index
|
|
506
|
+
x, y, right, bottom = self.pages[index].visual_box(self._selection.box)
|
|
507
|
+
height = self._bottoms[index] - self._tops[index]
|
|
508
|
+
return (self._padding() + x * self._page_width, self._tops[index] + y * height,
|
|
509
|
+
self._padding() + right * self._page_width, self._tops[index] + bottom * height)
|
|
510
|
+
|
|
511
|
+
def _draw_selection(self) -> None:
|
|
512
|
+
self.canvas.delete('selection')
|
|
513
|
+
box = self._selection_canvas_box()
|
|
514
|
+
if box is None or self._selection is None or self._selection.page_index not in self._items:
|
|
515
|
+
return
|
|
516
|
+
x, y, right, bottom = box
|
|
517
|
+
if self._selection_image:
|
|
518
|
+
width, height = max(1, round(right - x)), max(1, round(bottom - y))
|
|
519
|
+
viewport = max(1, self.canvas.winfo_height())
|
|
520
|
+
offset = max(0, self.canvas.canvasy(0) - y)
|
|
521
|
+
start = max(0, min(height - 1, (int(offset) // viewport - 1) * viewport))
|
|
522
|
+
end = min(height, start + 3 * viewport)
|
|
523
|
+
size = width, height, start, end
|
|
524
|
+
if size != self._overlay_size:
|
|
525
|
+
source = self._selection_image
|
|
526
|
+
crop = source.crop((0, start * source.height / height, source.width, end * source.height / height))
|
|
527
|
+
resized = crop.resize((width, end-start), Image.Resampling.LANCZOS)
|
|
528
|
+
crop.close()
|
|
529
|
+
self._overlay_photo = ImageTk.PhotoImage(resized, master=self.canvas)
|
|
530
|
+
resized.close()
|
|
531
|
+
self._overlay_size = size
|
|
532
|
+
self.canvas.create_image(x, y + start, image=self._overlay_photo, anchor='nw', tags='selection')
|
|
533
|
+
self.canvas.create_rectangle(*box, outline='#1689cc', width=2, dash=(4, 2), tags='selection')
|
|
534
|
+
radius = max(4, round(4 * self._get_widget_scaling()))
|
|
535
|
+
for cx, cy in ((x, y), (right, y), (right, bottom), (x, bottom)):
|
|
536
|
+
self.canvas.create_rectangle(cx-radius, cy-radius, cx+radius, cy+radius,
|
|
537
|
+
fill='white', outline='#1689cc', tags='selection')
|
|
538
|
+
|
|
539
|
+
def _press(self, event: Any) -> str:
|
|
540
|
+
self.canvas.focus_set()
|
|
541
|
+
box = self._selection_canvas_box()
|
|
542
|
+
if box is None or self._selection is None:
|
|
543
|
+
return 'break'
|
|
544
|
+
x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
|
|
545
|
+
left, top, right, bottom = box
|
|
546
|
+
radius = 10 * self._get_widget_scaling()
|
|
547
|
+
for name, cx, cy in (('nw', left, top), ('ne', right, top), ('se', right, bottom), ('sw', left, bottom)):
|
|
548
|
+
if abs(x-cx) <= radius and abs(y-cy) <= radius:
|
|
549
|
+
self._drag = name, x, y, box
|
|
550
|
+
return 'break'
|
|
551
|
+
if left <= x <= right and top <= y <= bottom:
|
|
552
|
+
self._drag = 'move', x, y, box
|
|
553
|
+
return 'break'
|
|
554
|
+
|
|
555
|
+
def _motion(self, event: Any) -> str:
|
|
556
|
+
if self._drag is None or self._selection is None:
|
|
557
|
+
return 'break'
|
|
558
|
+
mode, start_x, start_y, original = self._drag
|
|
559
|
+
x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
|
|
560
|
+
left, top, right, bottom = original
|
|
561
|
+
if mode == 'move':
|
|
562
|
+
left, right = left+x-start_x, right+x-start_x
|
|
563
|
+
top, bottom = top+y-start_y, bottom+y-start_y
|
|
564
|
+
else:
|
|
565
|
+
anchor_x = right if 'w' in mode else left
|
|
566
|
+
anchor_y = bottom if 'n' in mode else top
|
|
567
|
+
width = max(16, (anchor_x-x) if 'w' in mode else (x-anchor_x))
|
|
568
|
+
height = width * (original[3]-original[1]) / (original[2]-original[0])
|
|
569
|
+
left, right = (anchor_x-width, anchor_x) if 'w' in mode else (anchor_x, anchor_x+width)
|
|
570
|
+
top, bottom = (anchor_y-height, anchor_y) if 'n' in mode else (anchor_y, anchor_y+height)
|
|
571
|
+
index = self._selection.page_index
|
|
572
|
+
height = self._bottoms[index] - self._tops[index]
|
|
573
|
+
self._set_visual_box(index, ((left-self._padding()) / self._page_width,
|
|
574
|
+
(top-self._tops[index]) / height,
|
|
575
|
+
(right-self._padding()) / self._page_width,
|
|
576
|
+
(bottom-self._tops[index]) / height))
|
|
577
|
+
return 'break'
|
|
578
|
+
|
|
579
|
+
def _release(self, _: Any) -> str:
|
|
580
|
+
self._drag = None
|
|
581
|
+
return 'break'
|
|
582
|
+
|
|
583
|
+
def destroy(self) -> None:
|
|
584
|
+
if self._destroyed:
|
|
585
|
+
return
|
|
586
|
+
self._destroyed = True
|
|
587
|
+
for job in (self._layout_job, self._refresh_job, self._poll_job):
|
|
588
|
+
if job is not None:
|
|
589
|
+
self.after_cancel(job)
|
|
590
|
+
self._renderer.close()
|
|
591
|
+
for image, _ in self._cache.values():
|
|
592
|
+
image.close()
|
|
593
|
+
self._cache.clear()
|
|
594
|
+
self._photos.clear()
|
|
595
|
+
if self._selection_image:
|
|
596
|
+
self._selection_image.close()
|
|
597
|
+
self._overlay_photo = None
|
|
598
|
+
super().destroy()
|
ctkpdfium/geometry.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Page geometry independent of Tk and of live PDFium handles."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from math import isfinite
|
|
6
|
+
|
|
7
|
+
Box = tuple[float, float, float, float]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class PageSelection:
|
|
12
|
+
"""A zero-based page index and rectangle in unrotated PDF user space."""
|
|
13
|
+
|
|
14
|
+
page_index: int
|
|
15
|
+
box: Box
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class PageGeometry:
|
|
20
|
+
box: Box
|
|
21
|
+
rotation: int = 0
|
|
22
|
+
|
|
23
|
+
def __post_init__(self) -> None:
|
|
24
|
+
left, bottom, right, top = self.box
|
|
25
|
+
if not all(isfinite(v) for v in self.box) or right <= left or top <= bottom:
|
|
26
|
+
raise ValueError('Invalid PDF page bounds')
|
|
27
|
+
if self.rotation not in (0, 90, 180, 270):
|
|
28
|
+
raise ValueError('Unsupported PDF page rotation')
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def width(self) -> float:
|
|
32
|
+
x0, y0, x1, y1 = self.box
|
|
33
|
+
return y1 - y0 if self.rotation % 180 else x1 - x0
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def height(self) -> float:
|
|
37
|
+
x0, y0, x1, y1 = self.box
|
|
38
|
+
return x1 - x0 if self.rotation % 180 else y1 - y0
|
|
39
|
+
|
|
40
|
+
def to_pdf(self, x: float, y: float) -> tuple[float, float]:
|
|
41
|
+
"""Convert normalized visual coordinates (top left origin) to PDF."""
|
|
42
|
+
if self.rotation == 90:
|
|
43
|
+
x, y = y, 1 - x
|
|
44
|
+
elif self.rotation == 180:
|
|
45
|
+
x, y = 1 - x, 1 - y
|
|
46
|
+
elif self.rotation == 270:
|
|
47
|
+
x, y = 1 - y, x
|
|
48
|
+
x0, y0, x1, y1 = self.box
|
|
49
|
+
return x0 + x * (x1 - x0), y1 - y * (y1 - y0)
|
|
50
|
+
|
|
51
|
+
def from_pdf(self, x: float, y: float) -> tuple[float, float]:
|
|
52
|
+
x0, y0, x1, y1 = self.box
|
|
53
|
+
x, y = (x - x0) / (x1 - x0), (y1 - y) / (y1 - y0)
|
|
54
|
+
if self.rotation == 90:
|
|
55
|
+
return 1 - y, x
|
|
56
|
+
if self.rotation == 180:
|
|
57
|
+
return 1 - x, 1 - y
|
|
58
|
+
if self.rotation == 270:
|
|
59
|
+
return y, 1 - x
|
|
60
|
+
return x, y
|
|
61
|
+
|
|
62
|
+
def visual_box(self, box: Box) -> Box:
|
|
63
|
+
points = [self.from_pdf(x, y) for x in (box[0], box[2]) for y in (box[1], box[3])]
|
|
64
|
+
return self._bounds(points)
|
|
65
|
+
|
|
66
|
+
def pdf_box(self, box: Box) -> Box:
|
|
67
|
+
points = [self.to_pdf(x, y) for x in (box[0], box[2]) for y in (box[1], box[3])]
|
|
68
|
+
return self._bounds(points)
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def _bounds(points: list[tuple[float, float]]) -> Box:
|
|
72
|
+
xs, ys = zip(*points)
|
|
73
|
+
return min(xs), min(ys), max(xs), max(ys)
|
ctkpdfium/py.typed
ADDED
|
File without changes
|
ctkpdfium/renderer.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Serialized PDFium access. No Tk objects may enter this module."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import queue
|
|
5
|
+
import threading
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import pypdfium2 as pdfium
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
from .geometry import PageGeometry
|
|
13
|
+
|
|
14
|
+
# PDFium is process-global and cannot be called concurrently, even for different PDFs.
|
|
15
|
+
PDFIUM_LOCK = threading.RLock()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class RenderRequest:
|
|
20
|
+
page_index: int
|
|
21
|
+
generation: int
|
|
22
|
+
width: int
|
|
23
|
+
height: int
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class RenderResult:
|
|
28
|
+
request: RenderRequest
|
|
29
|
+
image: Image.Image | None = None
|
|
30
|
+
error: str | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class DocumentResult:
|
|
35
|
+
pages: tuple[PageGeometry, ...] = ()
|
|
36
|
+
error: str | None = None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Renderer:
|
|
40
|
+
def __init__(self, path: Path) -> None:
|
|
41
|
+
self.path = path
|
|
42
|
+
self.results: queue.Queue[DocumentResult | RenderResult] = queue.Queue(maxsize=2)
|
|
43
|
+
self.stop = threading.Event()
|
|
44
|
+
self.condition = threading.Condition()
|
|
45
|
+
self.requests: list[RenderRequest] = []
|
|
46
|
+
self.wanted: set[RenderRequest] = set()
|
|
47
|
+
self.completed: set[RenderRequest] = set()
|
|
48
|
+
self.in_flight: RenderRequest | None = None
|
|
49
|
+
self.thread = threading.Thread(target=self._run, name='CTkPdfiumRenderer', daemon=True)
|
|
50
|
+
self.thread.start()
|
|
51
|
+
|
|
52
|
+
def request(self, requests: list[RenderRequest]) -> None:
|
|
53
|
+
with self.condition:
|
|
54
|
+
self.wanted = set(requests)
|
|
55
|
+
self.completed.intersection_update(self.wanted)
|
|
56
|
+
self.requests = [r for r in requests if r not in self.completed and r != self.in_flight]
|
|
57
|
+
self.condition.notify()
|
|
58
|
+
|
|
59
|
+
def close(self) -> None:
|
|
60
|
+
self.stop.set()
|
|
61
|
+
with self.condition:
|
|
62
|
+
self.requests.clear()
|
|
63
|
+
self.wanted.clear()
|
|
64
|
+
self.condition.notify()
|
|
65
|
+
self.discard_results()
|
|
66
|
+
|
|
67
|
+
def discard_results(self) -> None:
|
|
68
|
+
while True:
|
|
69
|
+
try:
|
|
70
|
+
result = self.results.get_nowait()
|
|
71
|
+
except queue.Empty:
|
|
72
|
+
return
|
|
73
|
+
if isinstance(result, RenderResult) and result.image is not None:
|
|
74
|
+
result.image.close()
|
|
75
|
+
|
|
76
|
+
def _publish(self, result: DocumentResult | RenderResult) -> None:
|
|
77
|
+
while not self.stop.is_set():
|
|
78
|
+
if isinstance(result, RenderResult):
|
|
79
|
+
with self.condition:
|
|
80
|
+
if result.request not in self.wanted:
|
|
81
|
+
break
|
|
82
|
+
try:
|
|
83
|
+
self.results.put(result, timeout=0.05)
|
|
84
|
+
return
|
|
85
|
+
except queue.Full:
|
|
86
|
+
continue
|
|
87
|
+
if isinstance(result, RenderResult) and result.image is not None:
|
|
88
|
+
result.image.close()
|
|
89
|
+
|
|
90
|
+
def _run(self) -> None:
|
|
91
|
+
document = None
|
|
92
|
+
try:
|
|
93
|
+
with PDFIUM_LOCK:
|
|
94
|
+
document = pdfium.PdfDocument(str(self.path))
|
|
95
|
+
document.init_forms()
|
|
96
|
+
count = len(document)
|
|
97
|
+
if count == 0:
|
|
98
|
+
raise ValueError('The PDF does not contain any pages')
|
|
99
|
+
pages = []
|
|
100
|
+
for index in range(count):
|
|
101
|
+
if self.stop.is_set():
|
|
102
|
+
return
|
|
103
|
+
with PDFIUM_LOCK:
|
|
104
|
+
page = document[index]
|
|
105
|
+
try:
|
|
106
|
+
pages.append(PageGeometry(tuple(page.get_bbox()), page.get_rotation()))
|
|
107
|
+
finally:
|
|
108
|
+
page.close()
|
|
109
|
+
self._publish(DocumentResult(tuple(pages)))
|
|
110
|
+
while not self.stop.is_set():
|
|
111
|
+
with self.condition:
|
|
112
|
+
self.condition.wait_for(lambda: self.requests or self.stop.is_set())
|
|
113
|
+
if self.stop.is_set():
|
|
114
|
+
return
|
|
115
|
+
request = self.requests.pop(0)
|
|
116
|
+
self.in_flight = request
|
|
117
|
+
# Mark in-flight work too, so a viewport refresh cannot duplicate it.
|
|
118
|
+
self.completed.add(request)
|
|
119
|
+
try:
|
|
120
|
+
with PDFIUM_LOCK:
|
|
121
|
+
page = document[request.page_index]
|
|
122
|
+
try:
|
|
123
|
+
bitmap = page.render(
|
|
124
|
+
scale=request.width / pages[request.page_index].width,
|
|
125
|
+
fill_color=(255, 255, 255, 255),
|
|
126
|
+
prefer_bgrx=True, rev_byteorder=True,
|
|
127
|
+
)
|
|
128
|
+
try:
|
|
129
|
+
image = bitmap.to_pil().convert('RGB')
|
|
130
|
+
finally:
|
|
131
|
+
bitmap.close()
|
|
132
|
+
finally:
|
|
133
|
+
page.close()
|
|
134
|
+
self._publish(RenderResult(request, image=image))
|
|
135
|
+
except Exception as exc:
|
|
136
|
+
self._publish(RenderResult(request, error=str(exc)))
|
|
137
|
+
finally:
|
|
138
|
+
with self.condition:
|
|
139
|
+
if request in self.wanted:
|
|
140
|
+
self.completed.add(request)
|
|
141
|
+
self.in_flight = None
|
|
142
|
+
except Exception as exc:
|
|
143
|
+
self._publish(DocumentResult(error=str(exc)))
|
|
144
|
+
finally:
|
|
145
|
+
if document is not None:
|
|
146
|
+
with PDFIUM_LOCK:
|
|
147
|
+
document.close()
|
|
148
|
+
if self.stop.is_set():
|
|
149
|
+
self.discard_results()
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ctkpdfium
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: An asynchronous, virtualized PDF viewer and image placement widget for CustomTkinter
|
|
5
|
+
Project-URL: Homepage, https://github.com/sherpya/ctkpdfium
|
|
6
|
+
Project-URL: Repository, https://github.com/sherpya/ctkpdfium
|
|
7
|
+
Project-URL: Issues, https://github.com/sherpya/ctkpdfium/issues
|
|
8
|
+
Author-email: Gianluigi Tiesi <sherpya@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: customtkinter,pdf,pdfium,pypdfium2,tkinter
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Multimedia :: Graphics :: Viewers
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Requires-Dist: customtkinter>=6.0.0
|
|
24
|
+
Requires-Dist: pillow>=12.3.0
|
|
25
|
+
Requires-Dist: pypdfium2>=5.13.0
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# CTkPdfium
|
|
29
|
+
|
|
30
|
+

|
|
31
|
+

|
|
32
|
+

|
|
33
|
+
|
|
34
|
+
An asynchronous PDF viewer for CustomTkinter, powered by PDFium. Pages fit the
|
|
35
|
+
available width and scroll continuously. Only visible pages and their immediate
|
|
36
|
+
neighbours have canvas items; opening a large document does not create thousands
|
|
37
|
+
of Tk widgets.
|
|
38
|
+
|
|
39
|
+
Requires Python 3.11+, Tk, CustomTkinter, Pillow and pypdfium2. PDFium binaries are
|
|
40
|
+
provided by the pypdfium2 wheel on supported platforms. This package is pure
|
|
41
|
+
Python; installing it on Linux, macOS or Windows pulls the matching pypdfium2
|
|
42
|
+
wheel.
|
|
43
|
+
|
|
44
|
+
## Install and run
|
|
45
|
+
|
|
46
|
+
From PyPI:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
pip install ctkpdfium
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
From this directory:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
uv sync
|
|
56
|
+
uv run main.py /path/to/document.pdf
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
To install the local library in another project:
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
uv add --editable /path/to/ctkpdfium
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
There is no requirement to change CustomTkinter's scaling. The viewer follows the
|
|
66
|
+
application's widget scaling and theme, and also works at 2× scaling.
|
|
67
|
+
|
|
68
|
+
## Minimal example
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import customtkinter as ctk
|
|
72
|
+
from ctkpdfium import CTkPdfium
|
|
73
|
+
|
|
74
|
+
root = ctk.CTk()
|
|
75
|
+
root.geometry('900x700')
|
|
76
|
+
viewer = CTkPdfium(
|
|
77
|
+
root,
|
|
78
|
+
file='document.pdf',
|
|
79
|
+
navigation_overlay=True,
|
|
80
|
+
on_load=lambda viewer: print(viewer.page_count, 'pages'),
|
|
81
|
+
on_error=lambda page_index, message: print(page_index, message),
|
|
82
|
+
)
|
|
83
|
+
viewer.pack(fill='both', expand=True)
|
|
84
|
+
root.mainloop()
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Opening the document, discovering page geometry and rendering happen in a worker.
|
|
88
|
+
`page_count` and `current_page` are zero until the document is loaded. A missing
|
|
89
|
+
file raises `FileNotFoundError` immediately. Invalid, empty or password-protected
|
|
90
|
+
PDFs report a document error asynchronously. `on_load(viewer)` and
|
|
91
|
+
`on_error(page_index, message)` run on the Tk thread; the error page is `None` for
|
|
92
|
+
an opening error, otherwise a zero-based index. Errors are shown in the viewer
|
|
93
|
+
and are not retried indefinitely.
|
|
94
|
+
|
|
95
|
+
## Navigation and configuration
|
|
96
|
+
|
|
97
|
+
- `current_page`, `get_current_page()`: current **one-based** page number.
|
|
98
|
+
- `go_to_page(number)`, `next_page()`, `previous_page()`: return the resulting page
|
|
99
|
+
number. Requests are clamped to the document range; an early `go_to_page()` is
|
|
100
|
+
applied when the layout is ready.
|
|
101
|
+
- `add_page_change_callback(callback)` / `remove_page_change_callback(callback)`:
|
|
102
|
+
callbacks receive `(current_page, page_count)` on the Tk thread.
|
|
103
|
+
- `attach_navigation_overlay(**kwargs)`: create or return the floating navigation.
|
|
104
|
+
- `CTkPdfiumNavigation(viewer, overlay=False)`: create navigation for the caller
|
|
105
|
+
to position inside the viewer. `get_container_frame()` returns the viewer frame.
|
|
106
|
+
- `page_cache_size=8`: maximum cached pages, except pages active in the viewport
|
|
107
|
+
and their neighbours, which remain pinned to avoid repeated rendering.
|
|
108
|
+
- `cache_memory_limit=128 * 1024 * 1024`: decoded bitmap cache budget in bytes.
|
|
109
|
+
Native render resolution is limited by this budget and a 16-million-pixel cap.
|
|
110
|
+
Active images take priority; Tk display strips, in-flight bitmaps and PDFium's
|
|
111
|
+
document memory are additional memory, not part of this cache budget.
|
|
112
|
+
- `translate=callable`: translate the English UI messages (for example gettext).
|
|
113
|
+
- Standard CTkFrame styling, `width` and `height` are accepted.
|
|
114
|
+
|
|
115
|
+
Mouse wheel events are local to each viewer. Page Up/Down and Home/End work when
|
|
116
|
+
the canvas has keyboard focus. Resizing preserves the reading position. Tall
|
|
117
|
+
pages are displayed using bounded-height image strips, not enormous Tk images.
|
|
118
|
+
|
|
119
|
+
## Image placement
|
|
120
|
+
|
|
121
|
+
The viewer does not sign or modify PDFs. Its optional selection API is intended
|
|
122
|
+
for applications that need to place an image accurately on a PDF page.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from PIL import Image
|
|
126
|
+
from ctkpdfium import PageSelection
|
|
127
|
+
|
|
128
|
+
# Run after on_load. Coordinates are normalized to the displayed page:
|
|
129
|
+
# (0, 0) is its top left, (1, 1) its bottom right.
|
|
130
|
+
page = viewer.pages[0]
|
|
131
|
+
with Image.open('signature.png') as image:
|
|
132
|
+
viewer.set_selection(
|
|
133
|
+
PageSelection(0, page.pdf_box((0.15, 0.70, 0.45, 0.80))),
|
|
134
|
+
image=image,
|
|
135
|
+
)
|
|
136
|
+
viewer.add_selection_change_callback(lambda selection: print(selection))
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`PageSelection(page_index, box)` uses a **zero-based** page index. `box` is
|
|
140
|
+
`(left, bottom, right, top)` in the PDF's **unrotated user space**, including the
|
|
141
|
+
page origin; user units normally correspond to 1/72 inch. It is not a rectangle
|
|
142
|
+
in screen pixels. `PageGeometry` handles page rotation and the intersection of
|
|
143
|
+
MediaBox and CropBox. Its `to_pdf` / `from_pdf` methods convert points, and
|
|
144
|
+
`pdf_box` / `visual_box` convert rectangles.
|
|
145
|
+
|
|
146
|
+
The image is copied and displayed upright as viewed on screen. Drag it to move,
|
|
147
|
+
or drag a corner to resize with fixed aspect ratio. Placement is clamped to the
|
|
148
|
+
page. To move it to another page, call `set_selection` with that page's geometry.
|
|
149
|
+
An application that writes a PDF appearance must also compensate for the page's
|
|
150
|
+
rotation when embedding the image; coordinate conversion alone does not rotate
|
|
151
|
+
its content.
|
|
152
|
+
|
|
153
|
+
`get_selection()` returns the selection or `None`; `clear_selection()` clears it.
|
|
154
|
+
`see_selection()` scrolls it into view; `is_page_rendered(page_index)` reports
|
|
155
|
+
whether a page is currently available in the render cache.
|
|
156
|
+
Selection callbacks receive this same value. Use
|
|
157
|
+
`remove_selection_change_callback()` to detach a callback. Without an image,
|
|
158
|
+
the same API displays a rectangle. Only one selection is supported.
|
|
159
|
+
|
|
160
|
+
## Lifecycle and limitations
|
|
161
|
+
|
|
162
|
+
Call all viewer methods on the Tk thread. PDFium handles belong to the renderer
|
|
163
|
+
and are closed there, including when the viewer is destroyed during a render.
|
|
164
|
+
`destroy()` cancels callbacks and pending work without waiting for native work.
|
|
165
|
+
Do not use private PDFium handles from the UI. Viewer workers share a lock since
|
|
166
|
+
PDFium cannot be called concurrently, even for different documents. Other code
|
|
167
|
+
using PDFium in the same process must coordinate with
|
|
168
|
+
`ctkpdfium.renderer.PDFIUM_LOCK` as well.
|
|
169
|
+
|
|
170
|
+
The viewer is fit-width only: no text selection, search, password entry, document
|
|
171
|
+
editing or arbitrary zoom. Very large pages may have reduced preview resolution.
|
|
172
|
+
The public navigation methods from the earlier implementation remain available;
|
|
173
|
+
the widget now derives from CTkFrame, not CTkScrollableFrame, and private
|
|
174
|
+
scrollable-frame attributes are no longer available.
|
|
175
|
+
|
|
176
|
+
## PyPI publishing configuration
|
|
177
|
+
|
|
178
|
+
The release workflow builds one sdist and one `py3-none-any` wheel, then
|
|
179
|
+
installs that wheel on Linux, Windows and macOS (CPython 3.11–3.14). Those
|
|
180
|
+
jobs pull pypdfium2's platform-specific PDFium binary, check that it loads, and
|
|
181
|
+
run the test suite (with `xvfb-run` on Linux).
|
|
182
|
+
|
|
183
|
+
Configure a Trusted Publisher for the `ctkpdfium` project using owner
|
|
184
|
+
`sherpya`, repository `ctkpdfium`, workflow `release.yml` and GitHub
|
|
185
|
+
environment `ctkpdfium`. For a project that does not exist yet, register a
|
|
186
|
+
[pending publisher](https://pypi.org/manage/account/publishing/).
|
|
187
|
+
|
|
188
|
+
The workflow checks metadata with `twine check --strict` before upload and
|
|
189
|
+
skips already uploaded files when retrying a partial release. PyPI files are
|
|
190
|
+
immutable: increment `VERSION` for changed code or metadata. Release metadata
|
|
191
|
+
(description, summary) is taken from the first file uploaded for that version.
|
|
192
|
+
|
|
193
|
+
```sh
|
|
194
|
+
python -m pip install --upgrade build twine
|
|
195
|
+
python -m build
|
|
196
|
+
python -m twine check --strict dist/*
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Checks
|
|
200
|
+
|
|
201
|
+
```sh
|
|
202
|
+
uv run python -m unittest discover -s tests -v
|
|
203
|
+
uv run mypy src/ctkpdfium
|
|
204
|
+
# Linux without a graphical session:
|
|
205
|
+
xvfb-run -a uv run python -m unittest discover -s tests -v
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Tests create synthetic PDFs; no private documents or signing token are needed.
|
|
209
|
+
They cover 1/100/1,000-page documents, PDFium coordinate agreement on rotated and
|
|
210
|
+
cropped pages, HiDPI, rapid resize, independent viewers, loading errors, and
|
|
211
|
+
closing during rendering. On the development Linux machine, constructor times
|
|
212
|
+
were approximately 83 ms for 100 pages and 127 ms for 1,000 pages (versus roughly
|
|
213
|
+
one second for 100 pages in the earlier implementation). These are constructor
|
|
214
|
+
measurements, not total render times, and vary by system.
|
|
215
|
+
|
|
216
|
+
### Standalone Linux smoke test
|
|
217
|
+
|
|
218
|
+
The probe creates a temporary PDF, opens a window, verifies that PDFium renders
|
|
219
|
+
the page, and exits. It requires development headers matching the Python
|
|
220
|
+
interpreter used to compile it. The Linux check was also run successfully with
|
|
221
|
+
Nuitka 4.2 and Python 3.14; normal development tests use Python 3.13.
|
|
222
|
+
|
|
223
|
+
From this directory:
|
|
224
|
+
|
|
225
|
+
```sh
|
|
226
|
+
uv run --with nuitka --with zstandard python -m nuitka \
|
|
227
|
+
--standalone --static-libpython=no --enable-plugin=tk-inter \
|
|
228
|
+
--include-package=ctkpdfium --include-package=pypdfium2 \
|
|
229
|
+
--include-package=pypdfium2_raw --output-dir=build/smoke \
|
|
230
|
+
tests/packaging_probe.py
|
|
231
|
+
xvfb-run -a build/smoke/packaging_probe.dist/packaging_probe.bin
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
The successful run prints `Standalone PDFium render OK: 1 page(s)`. Check that
|
|
235
|
+
`packaging_probe.dist/pypdfium2_raw/libpdfium.so` is present. This tests the
|
|
236
|
+
packaged viewer and its native library; it does not sign with a smart card.
|
|
237
|
+
|
|
238
|
+
License: MIT. Copyright (c) Gianluigi Tiesi <sherpya@gmail.com>.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
ctkpdfium/__init__.py,sha256=gz1pPn1Wf-pT063TW-C-TmWWOK4sut_o0TisH0upbdY,185
|
|
2
|
+
ctkpdfium/ctkpdfium.py,sha256=8-F3foJ-BtjkXLQPtT48QeiverPwTbfmBfOnz6FFfmo,27927
|
|
3
|
+
ctkpdfium/geometry.py,sha256=phH4gyudxMY2zVzdNmCaqdWplxft6zZmf-e1ezBzOxU,2338
|
|
4
|
+
ctkpdfium/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
ctkpdfium/renderer.py,sha256=2tF0w-IvpkCTL3vEkj5Yev2XqpL92C3bVXmKkzi8XnM,5380
|
|
6
|
+
ctkpdfium-1.0.0.dist-info/METADATA,sha256=aWvNVUMYkdIsQW2ytqG-3_SP3SVwSliMWZiQiO3lZ9U,10325
|
|
7
|
+
ctkpdfium-1.0.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
8
|
+
ctkpdfium-1.0.0.dist-info/licenses/LICENSE,sha256=aZ1-Ebd1ufKflmvERyqPt1bw7bEnvwhgsjMjP11d0mU,1087
|
|
9
|
+
ctkpdfium-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Gianluigi Tiesi <sherpya@gmail.com>
|
|
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.
|