2026-06-29 14:42:42 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-06-29 15:26:55 +08:00
|
|
|
from collections import OrderedDict
|
2026-06-29 14:42:42 +08:00
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
from tempfile import NamedTemporaryFile
|
|
|
|
|
|
|
|
|
|
import fitz
|
|
|
|
|
from PySide6.QtGui import QImage
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
class SearchMatch:
|
|
|
|
|
page_index: int
|
|
|
|
|
text: str
|
|
|
|
|
|
|
|
|
|
|
2026-06-29 15:12:05 +08:00
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
class FormField:
|
|
|
|
|
page_index: int
|
|
|
|
|
name: str
|
|
|
|
|
field_type: str
|
|
|
|
|
value: str
|
|
|
|
|
|
|
|
|
|
|
2026-06-29 15:26:55 +08:00
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
class AnnotationInfo:
|
|
|
|
|
page_index: int
|
|
|
|
|
xref: int
|
|
|
|
|
annotation_type: str
|
|
|
|
|
content: str
|
2026-06-29 17:48:48 +08:00
|
|
|
rect: tuple[float, float, float, float] | None = None
|
2026-06-29 15:26:55 +08:00
|
|
|
|
|
|
|
|
|
2026-06-29 15:12:05 +08:00
|
|
|
class EncryptedPdfError(RuntimeError):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2026-06-29 14:42:42 +08:00
|
|
|
class PdfDocument:
|
|
|
|
|
def __init__(self) -> None:
|
|
|
|
|
self.path: Path | None = None
|
|
|
|
|
self._doc: fitz.Document | None = None
|
2026-06-29 15:26:55 +08:00
|
|
|
self._revision = 0
|
2026-06-29 18:24:59 +08:00
|
|
|
self._dirty = False
|
2026-06-29 15:38:36 +08:00
|
|
|
self._undo_stack: list[bytes] = []
|
|
|
|
|
self._redo_stack: list[bytes] = []
|
2026-06-29 15:26:55 +08:00
|
|
|
self._render_cache: OrderedDict[tuple[int, int, float], QImage] = OrderedDict()
|
|
|
|
|
self._thumbnail_cache: OrderedDict[tuple[int, int, int], QImage] = OrderedDict()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def is_open(self) -> bool:
|
|
|
|
|
return self._doc is not None
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def page_count(self) -> int:
|
|
|
|
|
return len(self._doc) if self._doc else 0
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def title(self) -> str:
|
|
|
|
|
if not self.path:
|
|
|
|
|
return "未打开文档"
|
|
|
|
|
return self.path.name
|
|
|
|
|
|
2026-06-29 18:24:59 +08:00
|
|
|
@property
|
|
|
|
|
def is_dirty(self) -> bool:
|
|
|
|
|
return self._dirty
|
|
|
|
|
|
2026-06-29 18:35:48 +08:00
|
|
|
@property
|
|
|
|
|
def revision(self) -> int:
|
|
|
|
|
return self._revision
|
|
|
|
|
|
2026-06-29 15:12:05 +08:00
|
|
|
def open(self, path: str | Path, password: str | None = None) -> None:
|
2026-06-29 14:42:42 +08:00
|
|
|
self.close()
|
|
|
|
|
self.path = Path(path)
|
|
|
|
|
self._doc = fitz.open(self.path)
|
2026-06-29 15:05:19 +08:00
|
|
|
if self._doc.needs_pass:
|
2026-06-29 15:12:05 +08:00
|
|
|
if not password or not self._doc.authenticate(password):
|
|
|
|
|
self.close()
|
|
|
|
|
raise EncryptedPdfError("该 PDF 需要密码。")
|
2026-06-29 18:24:59 +08:00
|
|
|
self._dirty = False
|
2026-06-29 15:38:36 +08:00
|
|
|
self.clear_history()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
|
|
|
|
def close(self) -> None:
|
|
|
|
|
if self._doc:
|
|
|
|
|
self._doc.close()
|
|
|
|
|
self._doc = None
|
|
|
|
|
self.path = None
|
2026-06-29 18:24:59 +08:00
|
|
|
self._dirty = False
|
2026-06-29 15:38:36 +08:00
|
|
|
self.clear_history()
|
2026-06-29 15:26:55 +08:00
|
|
|
self.clear_cache()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
|
|
|
|
def render_page(self, page_index: int, zoom: float) -> QImage:
|
2026-06-29 15:26:55 +08:00
|
|
|
cache_key = (self._revision, page_index, round(zoom, 3))
|
|
|
|
|
if cache_key in self._render_cache:
|
|
|
|
|
self._render_cache.move_to_end(cache_key)
|
|
|
|
|
return self._render_cache[cache_key].copy()
|
|
|
|
|
|
2026-06-29 14:42:42 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
matrix = fitz.Matrix(zoom, zoom)
|
|
|
|
|
pixmap = page.get_pixmap(matrix=matrix, alpha=False)
|
|
|
|
|
image = QImage(
|
|
|
|
|
pixmap.samples,
|
|
|
|
|
pixmap.width,
|
|
|
|
|
pixmap.height,
|
|
|
|
|
pixmap.stride,
|
|
|
|
|
QImage.Format.Format_RGB888,
|
|
|
|
|
)
|
2026-06-29 15:26:55 +08:00
|
|
|
cached = image.copy()
|
|
|
|
|
self._remember_cache_item(self._render_cache, cache_key, cached, max_items=16)
|
|
|
|
|
return cached.copy()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
|
|
|
|
def render_thumbnail(self, page_index: int, width: int = 150) -> QImage:
|
2026-06-29 15:26:55 +08:00
|
|
|
cache_key = (self._revision, page_index, width)
|
|
|
|
|
if cache_key in self._thumbnail_cache:
|
|
|
|
|
self._thumbnail_cache.move_to_end(cache_key)
|
|
|
|
|
return self._thumbnail_cache[cache_key].copy()
|
|
|
|
|
|
2026-06-29 14:42:42 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
rect = page.rect
|
|
|
|
|
zoom = width / rect.width
|
2026-06-29 18:35:48 +08:00
|
|
|
pixmap = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), alpha=False)
|
|
|
|
|
image = QImage(
|
|
|
|
|
pixmap.samples,
|
|
|
|
|
pixmap.width,
|
|
|
|
|
pixmap.height,
|
|
|
|
|
pixmap.stride,
|
|
|
|
|
QImage.Format.Format_RGB888,
|
|
|
|
|
)
|
|
|
|
|
thumbnail = image.copy()
|
2026-06-29 15:26:55 +08:00
|
|
|
self._remember_cache_item(self._thumbnail_cache, cache_key, thumbnail, max_items=80)
|
|
|
|
|
return thumbnail.copy()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
|
|
|
|
def search(self, text: str, limit: int = 200) -> list[SearchMatch]:
|
|
|
|
|
if not self._doc or not text.strip():
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
matches: list[SearchMatch] = []
|
|
|
|
|
query = text.strip()
|
|
|
|
|
for page_index, page in enumerate(self._doc):
|
|
|
|
|
if page.search_for(query):
|
|
|
|
|
page_text = page.get_text("text").replace("\n", " ")
|
|
|
|
|
snippet_index = page_text.lower().find(query.lower())
|
|
|
|
|
if snippet_index >= 0:
|
|
|
|
|
start = max(0, snippet_index - 24)
|
|
|
|
|
end = min(len(page_text), snippet_index + len(query) + 48)
|
|
|
|
|
snippet = page_text[start:end].strip()
|
|
|
|
|
else:
|
|
|
|
|
snippet = f"第 {page_index + 1} 页匹配"
|
|
|
|
|
matches.append(SearchMatch(page_index=page_index, text=snippet))
|
|
|
|
|
if len(matches) >= limit:
|
|
|
|
|
break
|
|
|
|
|
return matches
|
|
|
|
|
|
|
|
|
|
def rotate_page(self, page_index: int, degrees: int = 90) -> None:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:42:42 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
page.set_rotation((page.rotation + degrees) % 360)
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
|
|
|
|
def highlight_text(self, page_index: int, text: str) -> int:
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
rects = page.search_for(text.strip())
|
2026-06-29 15:38:36 +08:00
|
|
|
if rects:
|
|
|
|
|
self.snapshot()
|
2026-06-29 14:42:42 +08:00
|
|
|
for rect in rects:
|
|
|
|
|
annot = page.add_highlight_annot(rect)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
if rects:
|
|
|
|
|
self.mark_changed()
|
2026-06-29 14:42:42 +08:00
|
|
|
return len(rects)
|
|
|
|
|
|
2026-06-29 14:50:47 +08:00
|
|
|
def underline_text(self, page_index: int, text: str) -> int:
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
rects = page.search_for(text.strip())
|
2026-06-29 15:38:36 +08:00
|
|
|
if rects:
|
|
|
|
|
self.snapshot()
|
2026-06-29 14:50:47 +08:00
|
|
|
for rect in rects:
|
|
|
|
|
annot = page.add_underline_annot(rect)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
if rects:
|
|
|
|
|
self.mark_changed()
|
2026-06-29 14:50:47 +08:00
|
|
|
return len(rects)
|
|
|
|
|
|
|
|
|
|
def strikeout_text(self, page_index: int, text: str) -> int:
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
rects = page.search_for(text.strip())
|
2026-06-29 15:38:36 +08:00
|
|
|
if rects:
|
|
|
|
|
self.snapshot()
|
2026-06-29 14:50:47 +08:00
|
|
|
for rect in rects:
|
|
|
|
|
annot = page.add_strikeout_annot(rect)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
if rects:
|
|
|
|
|
self.mark_changed()
|
2026-06-29 14:50:47 +08:00
|
|
|
return len(rects)
|
|
|
|
|
|
2026-06-29 14:42:42 +08:00
|
|
|
def add_note(self, page_index: int, text: str) -> None:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:42:42 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
point = fitz.Point(72, 72)
|
|
|
|
|
annot = page.add_text_annot(point, text)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
2026-06-29 16:44:45 +08:00
|
|
|
def add_text(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
text: str,
|
|
|
|
|
point: tuple[float, float] | None = None,
|
|
|
|
|
) -> None:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:42:42 +08:00
|
|
|
page = self._page(page_index)
|
2026-06-29 17:48:48 +08:00
|
|
|
x0, y0 = point or (72, 96)
|
|
|
|
|
line_count = max(1, len(text.splitlines()))
|
|
|
|
|
max_line = max((len(line) for line in text.splitlines()), default=len(text))
|
|
|
|
|
width = max(160, min(page.rect.width - x0 - 24, max_line * 10 + 32))
|
|
|
|
|
height = max(42, line_count * 22 + 20)
|
|
|
|
|
rect = fitz.Rect(x0, y0, x0 + width, y0 + height)
|
|
|
|
|
annot = page.add_freetext_annot(
|
|
|
|
|
rect,
|
|
|
|
|
text,
|
|
|
|
|
fontsize=14,
|
|
|
|
|
fontname="china-s",
|
|
|
|
|
text_color=(0, 0, 0),
|
|
|
|
|
border_width=0,
|
|
|
|
|
)
|
|
|
|
|
annot.set_info(content=text)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
2026-06-29 16:44:45 +08:00
|
|
|
def insert_image(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
image_path: str | Path,
|
|
|
|
|
point: tuple[float, float] | None = None,
|
|
|
|
|
) -> None:
|
2026-06-29 18:12:05 +08:00
|
|
|
self.insert_image_rect(page_index, image_path, self.image_rect(page_index, point))
|
|
|
|
|
|
|
|
|
|
def image_rect(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
point: tuple[float, float] | None = None,
|
|
|
|
|
) -> tuple[float, float, float, float]:
|
2026-06-29 14:42:42 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
page_rect = page.rect
|
|
|
|
|
width = page_rect.width * 0.35
|
|
|
|
|
height = width * 0.75
|
2026-06-29 16:44:45 +08:00
|
|
|
x0, y0 = point or (72, 120)
|
2026-06-29 18:12:05 +08:00
|
|
|
return (x0, y0, x0 + width, y0 + height)
|
|
|
|
|
|
|
|
|
|
def insert_image_rect(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
image_path: str | Path,
|
|
|
|
|
rect: tuple[float, float, float, float],
|
|
|
|
|
) -> None:
|
|
|
|
|
self.snapshot()
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
page.insert_image(fitz.Rect(*rect), filename=str(image_path), keep_proportion=True)
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
2026-06-29 16:44:45 +08:00
|
|
|
def add_signature(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
image_path: str | Path,
|
|
|
|
|
point: tuple[float, float] | None = None,
|
|
|
|
|
) -> None:
|
2026-06-29 18:12:05 +08:00
|
|
|
self.insert_image_rect(page_index, image_path, self.signature_rect(page_index, point))
|
|
|
|
|
|
|
|
|
|
def signature_rect(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
point: tuple[float, float] | None = None,
|
|
|
|
|
) -> tuple[float, float, float, float]:
|
2026-06-29 15:05:19 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
page_rect = page.rect
|
|
|
|
|
width = page_rect.width * 0.28
|
|
|
|
|
height = width * 0.42
|
|
|
|
|
margin = 54
|
2026-06-29 16:44:45 +08:00
|
|
|
if point:
|
|
|
|
|
x0, y0 = point
|
2026-06-29 18:12:05 +08:00
|
|
|
return (x0, y0, x0 + width, y0 + height)
|
|
|
|
|
return (
|
|
|
|
|
page_rect.width - width - margin,
|
|
|
|
|
page_rect.height - height - margin,
|
|
|
|
|
page_rect.width - margin,
|
|
|
|
|
page_rect.height - margin,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def add_signature_rect(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
image_path: str | Path,
|
|
|
|
|
rect: tuple[float, float, float, float],
|
|
|
|
|
) -> None:
|
|
|
|
|
self.snapshot()
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
page.insert_image(fitz.Rect(*rect), filename=str(image_path), keep_proportion=True)
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 15:05:19 +08:00
|
|
|
|
2026-06-29 14:50:47 +08:00
|
|
|
def add_rectangle(self, page_index: int) -> None:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:50:47 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
rect = self._default_rect(page)
|
|
|
|
|
annot = page.add_rect_annot(rect)
|
|
|
|
|
annot.set_colors(stroke=(0.9, 0.1, 0.1))
|
|
|
|
|
annot.set_border(width=2)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:50:47 +08:00
|
|
|
|
|
|
|
|
def add_circle(self, page_index: int) -> None:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:50:47 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
rect = self._default_rect(page)
|
|
|
|
|
annot = page.add_circle_annot(rect)
|
|
|
|
|
annot.set_colors(stroke=(0.1, 0.3, 0.9))
|
|
|
|
|
annot.set_border(width=2)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:50:47 +08:00
|
|
|
|
|
|
|
|
def add_line(self, page_index: int, arrow: bool = False) -> None:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:50:47 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
rect = self._default_rect(page)
|
|
|
|
|
start = fitz.Point(rect.x0, rect.y0)
|
|
|
|
|
end = fitz.Point(rect.x1, rect.y1)
|
|
|
|
|
annot = page.add_line_annot(start, end)
|
|
|
|
|
annot.set_colors(stroke=(0.1, 0.1, 0.1))
|
|
|
|
|
annot.set_border(width=2)
|
|
|
|
|
if arrow:
|
|
|
|
|
annot.set_line_ends(fitz.PDF_ANNOT_LE_NONE, fitz.PDF_ANNOT_LE_CLOSED_ARROW)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:50:47 +08:00
|
|
|
|
2026-06-29 16:37:26 +08:00
|
|
|
def add_ink(self, page_index: int, points: list[tuple[float, float]]) -> None:
|
|
|
|
|
if len(points) < 2:
|
|
|
|
|
return
|
|
|
|
|
self.snapshot()
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
stroke = [(float(x), float(y)) for x, y in points]
|
|
|
|
|
annot = page.add_ink_annot([stroke])
|
|
|
|
|
annot.set_colors(stroke=(0.05, 0.05, 0.05))
|
|
|
|
|
annot.set_border(width=2)
|
|
|
|
|
annot.update()
|
|
|
|
|
self.mark_changed()
|
|
|
|
|
|
2026-06-29 14:50:47 +08:00
|
|
|
def add_cover_area(self, page_index: int) -> None:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:50:47 +08:00
|
|
|
page = self._page(page_index)
|
|
|
|
|
rect = self._default_rect(page)
|
|
|
|
|
annot = page.add_rect_annot(rect)
|
|
|
|
|
annot.set_colors(stroke=(1, 1, 1), fill=(1, 1, 1))
|
|
|
|
|
annot.set_border(width=0)
|
|
|
|
|
annot.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:50:47 +08:00
|
|
|
|
|
|
|
|
def insert_blank_page(self, after_page_index: int | None = None) -> int:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:50:47 +08:00
|
|
|
if self.page_count:
|
|
|
|
|
source = self._page(after_page_index if after_page_index is not None else self.page_count - 1)
|
|
|
|
|
width = source.rect.width
|
|
|
|
|
height = source.rect.height
|
|
|
|
|
else:
|
|
|
|
|
width = 595
|
|
|
|
|
height = 842
|
|
|
|
|
insert_at = self.page_count if after_page_index is None else after_page_index + 1
|
|
|
|
|
self._doc.new_page(pno=insert_at, width=width, height=height)
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:50:47 +08:00
|
|
|
return insert_at
|
|
|
|
|
|
|
|
|
|
def insert_pdf(self, source_path: str | Path, after_page_index: int | None = None) -> int:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:50:47 +08:00
|
|
|
insert_at = self.page_count if after_page_index is None else after_page_index + 1
|
|
|
|
|
with fitz.open(source_path) as source:
|
|
|
|
|
count = source.page_count
|
|
|
|
|
self._doc.insert_pdf(source, start_at=insert_at)
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:50:47 +08:00
|
|
|
return count
|
|
|
|
|
|
|
|
|
|
def extract_pages(self, page_numbers: list[int], target_path: str | Path) -> None:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
new_doc = fitz.open()
|
|
|
|
|
try:
|
|
|
|
|
for page_number in page_numbers:
|
|
|
|
|
page_index = page_number - 1
|
|
|
|
|
if page_index < 0 or page_index >= self.page_count:
|
|
|
|
|
raise ValueError(f"页码超出范围:{page_number}")
|
|
|
|
|
new_doc.insert_pdf(self._doc, from_page=page_index, to_page=page_index)
|
|
|
|
|
new_doc.save(target_path, garbage=4, deflate=True)
|
|
|
|
|
finally:
|
|
|
|
|
new_doc.close()
|
|
|
|
|
|
|
|
|
|
def split_to_folder(self, target_folder: str | Path) -> None:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
folder = Path(target_folder)
|
|
|
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
base_name = self.path.stem if self.path else "PDFReaderLite"
|
|
|
|
|
for page_index in range(self.page_count):
|
|
|
|
|
new_doc = fitz.open()
|
|
|
|
|
try:
|
|
|
|
|
new_doc.insert_pdf(self._doc, from_page=page_index, to_page=page_index)
|
|
|
|
|
new_doc.save(folder / f"{base_name}_第{page_index + 1}页.pdf", garbage=4, deflate=True)
|
|
|
|
|
finally:
|
|
|
|
|
new_doc.close()
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def merge_pdfs(source_paths: list[str | Path], target_path: str | Path) -> None:
|
|
|
|
|
if not source_paths:
|
|
|
|
|
raise ValueError("没有选择 PDF 文件")
|
|
|
|
|
merged = fitz.open()
|
|
|
|
|
try:
|
|
|
|
|
for source_path in source_paths:
|
|
|
|
|
with fitz.open(source_path) as source:
|
|
|
|
|
merged.insert_pdf(source)
|
|
|
|
|
merged.save(target_path, garbage=4, deflate=True)
|
|
|
|
|
finally:
|
|
|
|
|
merged.close()
|
|
|
|
|
|
2026-06-29 15:05:19 +08:00
|
|
|
def export_page_image(self, page_index: int, target_path: str | Path, zoom: float = 2.0) -> None:
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
pixmap = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), alpha=False)
|
|
|
|
|
pixmap.save(target_path)
|
|
|
|
|
|
|
|
|
|
def export_pages_images(
|
|
|
|
|
self,
|
|
|
|
|
page_numbers: list[int],
|
|
|
|
|
target_folder: str | Path,
|
|
|
|
|
zoom: float = 2.0,
|
|
|
|
|
) -> None:
|
|
|
|
|
folder = Path(target_folder)
|
|
|
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
base_name = self.path.stem if self.path else "PDFReaderLite"
|
|
|
|
|
for page_number in page_numbers:
|
|
|
|
|
page_index = page_number - 1
|
|
|
|
|
if page_index < 0 or page_index >= self.page_count:
|
|
|
|
|
raise ValueError(f"页码超出范围:{page_number}")
|
|
|
|
|
self.export_page_image(page_index, folder / f"{base_name}_第{page_number}页.png", zoom)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def images_to_pdf(image_paths: list[str | Path], target_path: str | Path) -> None:
|
|
|
|
|
if not image_paths:
|
|
|
|
|
raise ValueError("没有选择图片文件")
|
|
|
|
|
document = fitz.open()
|
|
|
|
|
try:
|
|
|
|
|
for image_path in image_paths:
|
|
|
|
|
image_doc = fitz.open(image_path)
|
|
|
|
|
try:
|
|
|
|
|
rect = image_doc[0].rect
|
|
|
|
|
pdf_bytes = image_doc.convert_to_pdf()
|
|
|
|
|
finally:
|
|
|
|
|
image_doc.close()
|
|
|
|
|
image_pdf = fitz.open("pdf", pdf_bytes)
|
|
|
|
|
try:
|
|
|
|
|
page = document.new_page(width=rect.width, height=rect.height)
|
|
|
|
|
page.show_pdf_page(page.rect, image_pdf, 0)
|
|
|
|
|
finally:
|
|
|
|
|
image_pdf.close()
|
|
|
|
|
document.save(target_path, garbage=4, deflate=True)
|
|
|
|
|
finally:
|
|
|
|
|
document.close()
|
|
|
|
|
|
|
|
|
|
def metadata(self) -> dict[str, str]:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
return {key: value or "" for key, value in self._doc.metadata.items()}
|
|
|
|
|
|
|
|
|
|
def update_metadata(
|
|
|
|
|
self,
|
|
|
|
|
title: str = "",
|
|
|
|
|
author: str = "",
|
|
|
|
|
subject: str = "",
|
|
|
|
|
keywords: str = "",
|
|
|
|
|
) -> None:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 15:05:19 +08:00
|
|
|
metadata = self.metadata()
|
|
|
|
|
metadata.update(
|
|
|
|
|
{
|
|
|
|
|
"title": title,
|
|
|
|
|
"author": author,
|
|
|
|
|
"subject": subject,
|
|
|
|
|
"keywords": keywords,
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
self._doc.set_metadata(metadata)
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
|
|
|
|
|
|
|
|
|
def annotations(self) -> list[AnnotationInfo]:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
items: list[AnnotationInfo] = []
|
|
|
|
|
for page_index in range(self.page_count):
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
annot = page.first_annot
|
|
|
|
|
while annot:
|
|
|
|
|
content = annot.info.get("content", "") if annot.info else ""
|
|
|
|
|
items.append(
|
|
|
|
|
AnnotationInfo(
|
|
|
|
|
page_index=page_index,
|
|
|
|
|
xref=annot.xref,
|
|
|
|
|
annotation_type=annot.type[1],
|
|
|
|
|
content=content,
|
2026-06-29 17:48:48 +08:00
|
|
|
rect=self._rect_tuple(annot.rect),
|
2026-06-29 15:26:55 +08:00
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
annot = annot.next
|
|
|
|
|
return items
|
|
|
|
|
|
2026-06-29 17:48:48 +08:00
|
|
|
def annotation_at_point(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
point: tuple[float, float],
|
|
|
|
|
) -> AnnotationInfo | None:
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
hit = fitz.Point(*point)
|
|
|
|
|
matches: list[AnnotationInfo] = []
|
|
|
|
|
annot = page.first_annot
|
|
|
|
|
while annot:
|
|
|
|
|
if annot.rect.contains(hit):
|
|
|
|
|
content = annot.info.get("content", "") if annot.info else ""
|
|
|
|
|
matches.append(
|
|
|
|
|
AnnotationInfo(
|
|
|
|
|
page_index=page_index,
|
|
|
|
|
xref=annot.xref,
|
|
|
|
|
annotation_type=annot.type[1],
|
|
|
|
|
content=content,
|
|
|
|
|
rect=self._rect_tuple(annot.rect),
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
annot = annot.next
|
|
|
|
|
return matches[-1] if matches else None
|
|
|
|
|
|
|
|
|
|
def annotation_rect(self, page_index: int, xref: int) -> tuple[float, float, float, float] | None:
|
|
|
|
|
annot = self._annotation(page_index, xref)
|
|
|
|
|
return self._rect_tuple(annot.rect) if annot else None
|
|
|
|
|
|
|
|
|
|
def update_annotation_rect(
|
|
|
|
|
self,
|
|
|
|
|
page_index: int,
|
|
|
|
|
xref: int,
|
|
|
|
|
rect: tuple[float, float, float, float],
|
|
|
|
|
) -> bool:
|
|
|
|
|
annot = self._annotation(page_index, xref)
|
|
|
|
|
if not annot:
|
|
|
|
|
return False
|
|
|
|
|
x0, y0, x1, y1 = rect
|
|
|
|
|
if x1 - x0 < 12 or y1 - y0 < 12:
|
|
|
|
|
return False
|
|
|
|
|
self.snapshot()
|
|
|
|
|
annot.set_rect(fitz.Rect(x0, y0, x1, y1))
|
|
|
|
|
annot.update()
|
|
|
|
|
self.mark_changed()
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def move_annotation(self, page_index: int, xref: int, dx: float, dy: float) -> bool:
|
|
|
|
|
annot = self._annotation(page_index, xref)
|
|
|
|
|
if not annot:
|
|
|
|
|
return False
|
|
|
|
|
rect = annot.rect + (dx, dy, dx, dy)
|
|
|
|
|
return self.update_annotation_rect(page_index, xref, self._rect_tuple(rect))
|
|
|
|
|
|
2026-06-29 15:26:55 +08:00
|
|
|
def delete_annotation(self, page_index: int, xref: int) -> bool:
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
annot = page.first_annot
|
|
|
|
|
while annot:
|
|
|
|
|
if annot.xref == xref:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 15:26:55 +08:00
|
|
|
page.delete_annot(annot)
|
|
|
|
|
self.mark_changed()
|
|
|
|
|
return True
|
|
|
|
|
annot = annot.next
|
|
|
|
|
return False
|
2026-06-29 15:05:19 +08:00
|
|
|
|
2026-06-29 15:12:05 +08:00
|
|
|
def form_fields(self) -> list[FormField]:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
fields: list[FormField] = []
|
|
|
|
|
for page_index in range(self.page_count):
|
|
|
|
|
widgets = self._page(page_index).widgets() or []
|
|
|
|
|
for widget in widgets:
|
|
|
|
|
name = widget.field_name or ""
|
|
|
|
|
if not name:
|
|
|
|
|
continue
|
|
|
|
|
fields.append(
|
|
|
|
|
FormField(
|
|
|
|
|
page_index=page_index,
|
|
|
|
|
name=name,
|
|
|
|
|
field_type=widget.field_type_string or "",
|
|
|
|
|
value=str(widget.field_value or ""),
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
return fields
|
|
|
|
|
|
|
|
|
|
def update_form_field(self, field_name: str, value: str) -> bool:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
for page_index in range(self.page_count):
|
|
|
|
|
widgets = self._page(page_index).widgets() or []
|
|
|
|
|
for widget in widgets:
|
|
|
|
|
if widget.field_name == field_name:
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 15:12:05 +08:00
|
|
|
widget.field_value = value
|
|
|
|
|
widget.update()
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 15:12:05 +08:00
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
|
2026-06-29 14:42:42 +08:00
|
|
|
def delete_page(self, page_index: int) -> None:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
2026-06-29 15:38:36 +08:00
|
|
|
self.snapshot()
|
2026-06-29 14:42:42 +08:00
|
|
|
self._doc.delete_page(page_index)
|
2026-06-29 15:26:55 +08:00
|
|
|
self.mark_changed()
|
2026-06-29 14:42:42 +08:00
|
|
|
|
2026-06-29 15:38:36 +08:00
|
|
|
def move_page(self, from_page_index: int, to_page_index: int) -> None:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
if from_page_index < 0 or from_page_index >= self.page_count:
|
|
|
|
|
raise IndexError("源页码超出范围")
|
|
|
|
|
if to_page_index < 0 or to_page_index >= self.page_count:
|
|
|
|
|
raise IndexError("目标页码超出范围")
|
|
|
|
|
if from_page_index == to_page_index:
|
|
|
|
|
return
|
|
|
|
|
self.snapshot()
|
|
|
|
|
self._doc.move_page(from_page_index, to_page_index)
|
|
|
|
|
self.mark_changed()
|
|
|
|
|
|
2026-06-29 16:30:27 +08:00
|
|
|
def reorder_pages(self, page_order: list[int]) -> None:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
if sorted(page_order) != list(range(self.page_count)):
|
|
|
|
|
raise ValueError("页面顺序必须包含所有页面且不能重复")
|
|
|
|
|
if page_order == list(range(self.page_count)):
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
self.snapshot()
|
|
|
|
|
reordered = fitz.open()
|
|
|
|
|
try:
|
|
|
|
|
for page_index in page_order:
|
|
|
|
|
reordered.insert_pdf(self._doc, from_page=page_index, to_page=page_index)
|
|
|
|
|
data = reordered.tobytes(garbage=4, deflate=True)
|
|
|
|
|
finally:
|
|
|
|
|
reordered.close()
|
|
|
|
|
self._replace_with_bytes(data)
|
|
|
|
|
|
2026-06-29 14:42:42 +08:00
|
|
|
def save(self) -> None:
|
|
|
|
|
if not self.path:
|
|
|
|
|
raise RuntimeError("没有原始文件路径")
|
|
|
|
|
self.save_as(self.path)
|
|
|
|
|
|
|
|
|
|
def save_as(self, path: str | Path) -> None:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
|
|
|
|
|
target = Path(path)
|
|
|
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
original_path = self.path
|
2026-06-29 15:38:36 +08:00
|
|
|
can_incremental = (
|
|
|
|
|
original_path
|
|
|
|
|
and target.resolve() == original_path.resolve()
|
|
|
|
|
and self._doc.name
|
|
|
|
|
and Path(self._doc.name).resolve() == target.resolve()
|
|
|
|
|
)
|
|
|
|
|
if can_incremental:
|
2026-06-29 15:26:55 +08:00
|
|
|
self._doc.saveIncr()
|
|
|
|
|
self._doc.close()
|
|
|
|
|
self.path = target
|
|
|
|
|
self._doc = fitz.open(target)
|
2026-06-29 18:24:59 +08:00
|
|
|
self.mark_saved()
|
2026-06-29 15:26:55 +08:00
|
|
|
return
|
2026-06-29 14:42:42 +08:00
|
|
|
|
|
|
|
|
with NamedTemporaryFile(delete=False, suffix=".pdf", dir=target.parent) as tmp:
|
|
|
|
|
temp_path = Path(tmp.name)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
self._doc.save(temp_path, garbage=4, deflate=True)
|
|
|
|
|
temp_path.replace(target)
|
|
|
|
|
self.path = target
|
|
|
|
|
if self._doc:
|
|
|
|
|
self._doc.close()
|
|
|
|
|
self._doc = fitz.open(target)
|
2026-06-29 18:24:59 +08:00
|
|
|
self.mark_saved()
|
2026-06-29 14:42:42 +08:00
|
|
|
finally:
|
|
|
|
|
if temp_path.exists():
|
|
|
|
|
temp_path.unlink()
|
|
|
|
|
|
2026-06-29 15:38:36 +08:00
|
|
|
def save_encrypted(
|
|
|
|
|
self,
|
|
|
|
|
path: str | Path,
|
|
|
|
|
password: str,
|
|
|
|
|
allow_print: bool = True,
|
|
|
|
|
allow_copy: bool = True,
|
|
|
|
|
allow_modify: bool = False,
|
|
|
|
|
) -> None:
|
2026-06-29 15:05:19 +08:00
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
if not password:
|
|
|
|
|
raise ValueError("密码不能为空")
|
|
|
|
|
|
|
|
|
|
target = Path(path)
|
|
|
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
2026-06-29 15:38:36 +08:00
|
|
|
permissions = fitz.PDF_PERM_ACCESSIBILITY
|
|
|
|
|
if allow_print:
|
|
|
|
|
permissions |= fitz.PDF_PERM_PRINT
|
|
|
|
|
if allow_copy:
|
|
|
|
|
permissions |= fitz.PDF_PERM_COPY
|
|
|
|
|
if allow_modify:
|
|
|
|
|
permissions |= fitz.PDF_PERM_MODIFY
|
2026-06-29 15:05:19 +08:00
|
|
|
self._doc.save(
|
|
|
|
|
target,
|
|
|
|
|
garbage=4,
|
|
|
|
|
deflate=True,
|
|
|
|
|
encryption=fitz.PDF_ENCRYPT_AES_256,
|
|
|
|
|
owner_pw=password,
|
|
|
|
|
user_pw=password,
|
2026-06-29 15:38:36 +08:00
|
|
|
permissions=permissions,
|
2026-06-29 15:05:19 +08:00
|
|
|
)
|
2026-06-29 18:29:32 +08:00
|
|
|
self._dirty = False
|
2026-06-29 15:05:19 +08:00
|
|
|
|
2026-06-29 14:42:42 +08:00
|
|
|
def _page(self, page_index: int) -> fitz.Page:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
raise RuntimeError("没有打开 PDF")
|
|
|
|
|
if page_index < 0 or page_index >= len(self._doc):
|
|
|
|
|
raise IndexError("页码超出范围")
|
|
|
|
|
return self._doc.load_page(page_index)
|
2026-06-29 14:50:47 +08:00
|
|
|
|
2026-06-29 17:48:48 +08:00
|
|
|
def _annotation(self, page_index: int, xref: int):
|
|
|
|
|
page = self._page(page_index)
|
|
|
|
|
annot = page.first_annot
|
|
|
|
|
while annot:
|
|
|
|
|
if annot.xref == xref:
|
|
|
|
|
return annot
|
|
|
|
|
annot = annot.next
|
|
|
|
|
return None
|
|
|
|
|
|
2026-06-29 15:26:55 +08:00
|
|
|
def mark_changed(self) -> None:
|
|
|
|
|
self._revision += 1
|
2026-06-29 18:24:59 +08:00
|
|
|
self._dirty = True
|
|
|
|
|
self.clear_cache()
|
|
|
|
|
|
|
|
|
|
def mark_saved(self) -> None:
|
|
|
|
|
self._revision += 1
|
|
|
|
|
self._dirty = False
|
2026-06-29 15:26:55 +08:00
|
|
|
self.clear_cache()
|
|
|
|
|
|
2026-06-29 15:38:36 +08:00
|
|
|
def snapshot(self) -> None:
|
|
|
|
|
if not self._doc:
|
|
|
|
|
return
|
|
|
|
|
self._undo_stack.append(self._doc.tobytes(garbage=4, deflate=True))
|
|
|
|
|
if len(self._undo_stack) > 20:
|
|
|
|
|
self._undo_stack.pop(0)
|
|
|
|
|
self._redo_stack.clear()
|
|
|
|
|
|
|
|
|
|
def can_undo(self) -> bool:
|
|
|
|
|
return bool(self._undo_stack)
|
|
|
|
|
|
|
|
|
|
def can_redo(self) -> bool:
|
|
|
|
|
return bool(self._redo_stack)
|
|
|
|
|
|
|
|
|
|
def undo(self) -> bool:
|
|
|
|
|
if not self._doc or not self._undo_stack:
|
|
|
|
|
return False
|
|
|
|
|
self._redo_stack.append(self._doc.tobytes(garbage=4, deflate=True))
|
|
|
|
|
data = self._undo_stack.pop()
|
|
|
|
|
self._replace_with_bytes(data)
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def redo(self) -> bool:
|
|
|
|
|
if not self._doc or not self._redo_stack:
|
|
|
|
|
return False
|
|
|
|
|
self._undo_stack.append(self._doc.tobytes(garbage=4, deflate=True))
|
|
|
|
|
data = self._redo_stack.pop()
|
|
|
|
|
self._replace_with_bytes(data)
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def clear_history(self) -> None:
|
|
|
|
|
self._undo_stack.clear()
|
|
|
|
|
self._redo_stack.clear()
|
|
|
|
|
|
|
|
|
|
def _replace_with_bytes(self, data: bytes) -> None:
|
|
|
|
|
if self._doc:
|
|
|
|
|
self._doc.close()
|
|
|
|
|
self._doc = fitz.open("pdf", data)
|
|
|
|
|
self.mark_changed()
|
|
|
|
|
|
2026-06-29 15:26:55 +08:00
|
|
|
def clear_cache(self) -> None:
|
|
|
|
|
self._render_cache.clear()
|
|
|
|
|
self._thumbnail_cache.clear()
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _remember_cache_item(
|
|
|
|
|
cache: OrderedDict,
|
|
|
|
|
key: tuple,
|
|
|
|
|
image: QImage,
|
|
|
|
|
max_items: int,
|
|
|
|
|
) -> None:
|
|
|
|
|
cache[key] = image
|
|
|
|
|
cache.move_to_end(key)
|
|
|
|
|
while len(cache) > max_items:
|
|
|
|
|
cache.popitem(last=False)
|
|
|
|
|
|
2026-06-29 14:50:47 +08:00
|
|
|
@staticmethod
|
|
|
|
|
def _default_rect(page: fitz.Page) -> fitz.Rect:
|
|
|
|
|
width = min(220, page.rect.width * 0.45)
|
|
|
|
|
height = min(120, page.rect.height * 0.2)
|
|
|
|
|
x0 = max(36, page.rect.width * 0.12)
|
|
|
|
|
y0 = max(36, page.rect.height * 0.16)
|
|
|
|
|
return fitz.Rect(x0, y0, x0 + width, y0 + height)
|
2026-06-29 17:48:48 +08:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _rect_tuple(rect: fitz.Rect) -> tuple[float, float, float, float]:
|
|
|
|
|
return (float(rect.x0), float(rect.y0), float(rect.x1), float(rect.y1))
|