Initial PDFReaderLite application
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
|
||||
|
||||
class PdfDocument:
|
||||
def __init__(self) -> None:
|
||||
self.path: Path | None = None
|
||||
self._doc: fitz.Document | None = None
|
||||
|
||||
@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
|
||||
|
||||
def open(self, path: str | Path) -> None:
|
||||
self.close()
|
||||
self.path = Path(path)
|
||||
self._doc = fitz.open(self.path)
|
||||
|
||||
def close(self) -> None:
|
||||
if self._doc:
|
||||
self._doc.close()
|
||||
self._doc = None
|
||||
self.path = None
|
||||
|
||||
def render_page(self, page_index: int, zoom: float) -> QImage:
|
||||
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,
|
||||
)
|
||||
return image.copy()
|
||||
|
||||
def render_thumbnail(self, page_index: int, width: int = 150) -> QImage:
|
||||
page = self._page(page_index)
|
||||
rect = page.rect
|
||||
zoom = width / rect.width
|
||||
return self.render_page(page_index, zoom)
|
||||
|
||||
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:
|
||||
page = self._page(page_index)
|
||||
page.set_rotation((page.rotation + degrees) % 360)
|
||||
|
||||
def highlight_text(self, page_index: int, text: str) -> int:
|
||||
page = self._page(page_index)
|
||||
rects = page.search_for(text.strip())
|
||||
for rect in rects:
|
||||
annot = page.add_highlight_annot(rect)
|
||||
annot.update()
|
||||
return len(rects)
|
||||
|
||||
def add_note(self, page_index: int, text: str) -> None:
|
||||
page = self._page(page_index)
|
||||
point = fitz.Point(72, 72)
|
||||
annot = page.add_text_annot(point, text)
|
||||
annot.update()
|
||||
|
||||
def add_text(self, page_index: int, text: str) -> None:
|
||||
page = self._page(page_index)
|
||||
point = fitz.Point(72, 96)
|
||||
page.insert_text(point, text, fontsize=14, fontname="china-s", color=(0, 0, 0))
|
||||
|
||||
def insert_image(self, page_index: int, image_path: str | Path) -> None:
|
||||
page = self._page(page_index)
|
||||
page_rect = page.rect
|
||||
width = page_rect.width * 0.35
|
||||
height = width * 0.75
|
||||
rect = fitz.Rect(72, 120, 72 + width, 120 + height)
|
||||
page.insert_image(rect, filename=str(image_path), keep_proportion=True)
|
||||
|
||||
def delete_page(self, page_index: int) -> None:
|
||||
if not self._doc:
|
||||
raise RuntimeError("没有打开 PDF")
|
||||
self._doc.delete_page(page_index)
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
if original_path and target.resolve() == original_path.resolve():
|
||||
self._doc.close()
|
||||
self._doc = None
|
||||
temp_path.replace(target)
|
||||
self.path = target
|
||||
if self._doc:
|
||||
self._doc.close()
|
||||
self._doc = fitz.open(target)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink()
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user