From a2677735f3b24b9fee93efc0922fc65a637294a8 Mon Sep 17 00:00:00 2001 From: Rahix Date: Mon, 19 Aug 2024 10:47:12 +0200 Subject: [PATCH] Actual link addition --- src/main.py | 44 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/src/main.py b/src/main.py index 5979426..a128c5b 100644 --- a/src/main.py +++ b/src/main.py @@ -10,20 +10,43 @@ RECT_START = None class AddLinkDialog: - def __init__(self, root, rect, toc) -> None: + def __init__(self, root, page, rect, toc) -> None: self.top = tkinter.Toplevel(root) frm = ttk.Frame(self.top, padding=10) frm.grid() + self.rect = rect + self.page = page + self.toc = toc toc_values = list(t for _, t, _ in toc) ttk.Label(frm, text=f"Rectangle: {rect!r}").grid(column=0, row=0, columnspan=3) ttk.Label(frm, text="Target:").grid(column=0, row=1) - entry = ttk.Entry(frm) - entry.grid(column=1, row=1, columnspan=2, sticky="EW") - ttk.Button(frm, text="Add", command=self.top.destroy).grid(column=2, row=2) + self.entry = ttk.Combobox(frm, values=toc_values) + self.entry.grid(column=1, row=1, columnspan=2, sticky="EW") + ttk.Button(frm, text="Add", command=self.do_add_link).grid(column=2, row=2) ttk.Button(frm, text="Cancel", command=self.top.destroy).grid(column=3, row=2) + def do_add_link(self): + toc_title = self.entry.get() + page = 0 + for _, t, p in self.toc: + if toc_title == t: + page = p - 1 + break + else: + raise Exception("TOC page not found") + + self.page.insert_link( + { + "kind": pymupdf.LINK_GOTO, + "from": pymupdf.Rect(self.rect), + "page": page, + } + ) + + self.top.destroy() + def main() -> None: parser = argparse.ArgumentParser() @@ -72,7 +95,7 @@ def main() -> None: def load_page(page_num: int, rect_overlay=None): page = doc[page_num] - pix = page.get_pixmap(dpi=120) + pix = page.get_pixmap(dpi=72) mode = "RGBA" if pix.alpha else "RGB" img = Image.frombytes(mode, [pix.width, pix.height], pix.samples) @@ -101,13 +124,12 @@ def main() -> None: if RECT_START is not None: print(f"UP @ {event.x}/{event.y}") load_page(CURRENT_PAGE, [*RECT_START, event.x, event.y]) - AddLinkDialog(root, [*RECT_START, event.x, event.y], toc) + AddLinkDialog(root, doc[CURRENT_PAGE], [*RECT_START, event.x, event.y], toc) RECT_START = None page_view.bind("", start_rect) page_view.bind("", end_rect) - def next_page(): global CURRENT_PAGE CURRENT_PAGE += 1 @@ -125,6 +147,14 @@ def main() -> None: column=3, row=1, sticky="NS", padx=5, pady=5 ) + def save_and_close(): + doc.save("/tmp/outfile.pdf") + root.destroy() + + ttk.Button(frm, text="Save & Close", command=save_and_close).grid( + column=1, row=2, columnspan=3, sticky="EW" + ) + root.bind("", lambda _: previous_page()) root.bind("", lambda _: previous_page()) root.bind("", lambda _: previous_page())