Add caching logging packaging and annotation management

This commit is contained in:
2026-06-29 15:26:55 +08:00
parent d34529c7bf
commit 736f9249b9
11 changed files with 303 additions and 25 deletions
+1
View File
@@ -10,6 +10,7 @@ __pycache__/
build/
dist/
*.spec
!packaging/*.spec
.pytest_cache/
.mypy_cache/
+16
View File
@@ -39,6 +39,10 @@ PDFReaderLite 是一个面向 Windows 的轻量 PDF 阅读与编辑工具,目
- 移除密码另存为
- 打印
- 基础表单填写
- 注释列表与删除注释
- 页面渲染缓存
- 分批加载缩略图
- 异常日志
- 图片签名
- 深色模式
- 常用快捷键
@@ -57,3 +61,15 @@ python main.py
```powershell
python scripts\smoke_test.py
```
打包单文件 exe:
```powershell
.\build.ps1
```
打包产物位于:
```text
dist\PDFReaderLite.exe
```
+3 -6
View File
@@ -6,9 +6,6 @@ if (-not (Test-Path ".\.venv\Scripts\python.exe")) {
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe -m PyInstaller `
--onefile `
--windowed `
--icon resources\icons\icon_software.ico `
--add-data "resources\icons;resources\icons" `
--name PDFReaderLite `
main.py
--clean `
--noconfirm `
packaging\PDFReaderLite.spec
+9 -9
View File
@@ -30,8 +30,8 @@ PDFReaderLite 是 Windows 平台的轻量 PDF 阅读与编辑工具。功能重
- 下划线、删除线
- 画笔
- 矩形、圆形、线条、箭头
- 注释列表
- 删除注释
- 注释列表(已完成)
- 删除注释(已完成)
- 移动、缩放、删除新增对象
- 遮盖区域
- 插入空白页
@@ -62,15 +62,15 @@ PDFReaderLite 是 Windows 平台的轻量 PDF 阅读与编辑工具。功能重
## V4:打包与体验优化
- 大文件性能优化
- 页面缓存
- 后台渲染
- 页面缓存(已完成基础缓存)
- 后台渲染(已完成缩略图分批加载)
- 快捷键(已完成常用快捷键)
- 配置保存
- 异常恢复
- PyInstaller 打包
- 单文件 exe
- 程序图标
- 版本号
- 异常恢复(已完成异常日志)
- PyInstaller 打包(已完成)
- 单文件 exe(已完成)
- 程序图标(已完成)
- 版本号(已完成)
## 不纳入范围
+43
View File
@@ -0,0 +1,43 @@
# -*- mode: python ; coding: utf-8 -*-
from pathlib import Path
project_root = Path(SPECPATH).parent
a = Analysis(
[str(project_root / "main.py")],
pathex=[str(project_root)],
binaries=[],
datas=[(str(project_root / "resources" / "icons"), "resources/icons")],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
noarchive=False,
optimize=0,
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
name="PDFReaderLite",
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=str(project_root / "resources" / "icons" / "icon_software.ico"),
)
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.1.0"
__version__ = "0.2.0"
+33 -1
View File
@@ -1,19 +1,51 @@
from __future__ import annotations
import logging
import sys
from pathlib import Path
from PySide6.QtCore import QStandardPaths
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication
from PySide6.QtWidgets import QApplication, QMessageBox
from pdfreaderlite import __version__
from pdfreaderlite.resources import software_icon_path
from pdfreaderlite.ui.main_window import MainWindow
def configure_logging() -> Path:
log_dir = Path(
QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
)
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / "PDFReaderLite.log"
logging.basicConfig(
filename=log_path,
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
encoding="utf-8",
)
logging.info("PDFReaderLite %s started", __version__)
return log_path
def main() -> int:
app = QApplication(sys.argv)
app.setApplicationName("PDFReaderLite")
app.setOrganizationName("PDFReaderLite")
app.setApplicationVersion(__version__)
app.setWindowIcon(QIcon(software_icon_path().as_posix()))
log_path = configure_logging()
def handle_exception(exc_type, exc_value, exc_traceback) -> None:
logging.exception("Unhandled exception", exc_info=(exc_type, exc_value, exc_traceback))
QMessageBox.critical(
None,
"程序错误",
f"PDFReaderLite 遇到未处理错误。\n\n日志位置:{log_path}",
)
sys.excepthook = handle_exception
window = MainWindow()
window.show()
+108 -5
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
from collections import OrderedDict
from dataclasses import dataclass
from pathlib import Path
from tempfile import NamedTemporaryFile
@@ -22,6 +23,14 @@ class FormField:
value: str
@dataclass(frozen=True)
class AnnotationInfo:
page_index: int
xref: int
annotation_type: str
content: str
class EncryptedPdfError(RuntimeError):
pass
@@ -30,6 +39,9 @@ class PdfDocument:
def __init__(self) -> None:
self.path: Path | None = None
self._doc: fitz.Document | None = None
self._revision = 0
self._render_cache: OrderedDict[tuple[int, int, float], QImage] = OrderedDict()
self._thumbnail_cache: OrderedDict[tuple[int, int, int], QImage] = OrderedDict()
@property
def is_open(self) -> bool:
@@ -59,8 +71,14 @@ class PdfDocument:
self._doc.close()
self._doc = None
self.path = None
self.clear_cache()
def render_page(self, page_index: int, zoom: float) -> QImage:
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()
page = self._page(page_index)
matrix = fitz.Matrix(zoom, zoom)
pixmap = page.get_pixmap(matrix=matrix, alpha=False)
@@ -71,13 +89,22 @@ class PdfDocument:
pixmap.stride,
QImage.Format.Format_RGB888,
)
return image.copy()
cached = image.copy()
self._remember_cache_item(self._render_cache, cache_key, cached, max_items=16)
return cached.copy()
def render_thumbnail(self, page_index: int, width: int = 150) -> QImage:
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()
page = self._page(page_index)
rect = page.rect
zoom = width / rect.width
return self.render_page(page_index, zoom)
thumbnail = self.render_page(page_index, zoom)
self._remember_cache_item(self._thumbnail_cache, cache_key, thumbnail, max_items=80)
return thumbnail.copy()
def search(self, text: str, limit: int = 200) -> list[SearchMatch]:
if not self._doc or not text.strip():
@@ -103,6 +130,7 @@ class PdfDocument:
def rotate_page(self, page_index: int, degrees: int = 90) -> None:
page = self._page(page_index)
page.set_rotation((page.rotation + degrees) % 360)
self.mark_changed()
def highlight_text(self, page_index: int, text: str) -> int:
page = self._page(page_index)
@@ -110,6 +138,8 @@ class PdfDocument:
for rect in rects:
annot = page.add_highlight_annot(rect)
annot.update()
if rects:
self.mark_changed()
return len(rects)
def underline_text(self, page_index: int, text: str) -> int:
@@ -118,6 +148,8 @@ class PdfDocument:
for rect in rects:
annot = page.add_underline_annot(rect)
annot.update()
if rects:
self.mark_changed()
return len(rects)
def strikeout_text(self, page_index: int, text: str) -> int:
@@ -126,6 +158,8 @@ class PdfDocument:
for rect in rects:
annot = page.add_strikeout_annot(rect)
annot.update()
if rects:
self.mark_changed()
return len(rects)
def add_note(self, page_index: int, text: str) -> None:
@@ -133,11 +167,13 @@ class PdfDocument:
point = fitz.Point(72, 72)
annot = page.add_text_annot(point, text)
annot.update()
self.mark_changed()
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))
self.mark_changed()
def insert_image(self, page_index: int, image_path: str | Path) -> None:
page = self._page(page_index)
@@ -146,6 +182,7 @@ class PdfDocument:
height = width * 0.75
rect = fitz.Rect(72, 120, 72 + width, 120 + height)
page.insert_image(rect, filename=str(image_path), keep_proportion=True)
self.mark_changed()
def add_signature(self, page_index: int, image_path: str | Path) -> None:
page = self._page(page_index)
@@ -160,6 +197,7 @@ class PdfDocument:
page_rect.height - margin,
)
page.insert_image(rect, filename=str(image_path), keep_proportion=True)
self.mark_changed()
def add_rectangle(self, page_index: int) -> None:
page = self._page(page_index)
@@ -168,6 +206,7 @@ class PdfDocument:
annot.set_colors(stroke=(0.9, 0.1, 0.1))
annot.set_border(width=2)
annot.update()
self.mark_changed()
def add_circle(self, page_index: int) -> None:
page = self._page(page_index)
@@ -176,6 +215,7 @@ class PdfDocument:
annot.set_colors(stroke=(0.1, 0.3, 0.9))
annot.set_border(width=2)
annot.update()
self.mark_changed()
def add_line(self, page_index: int, arrow: bool = False) -> None:
page = self._page(page_index)
@@ -188,6 +228,7 @@ class PdfDocument:
if arrow:
annot.set_line_ends(fitz.PDF_ANNOT_LE_NONE, fitz.PDF_ANNOT_LE_CLOSED_ARROW)
annot.update()
self.mark_changed()
def add_cover_area(self, page_index: int) -> None:
page = self._page(page_index)
@@ -196,6 +237,7 @@ class PdfDocument:
annot.set_colors(stroke=(1, 1, 1), fill=(1, 1, 1))
annot.set_border(width=0)
annot.update()
self.mark_changed()
def insert_blank_page(self, after_page_index: int | None = None) -> int:
if not self._doc:
@@ -209,6 +251,7 @@ class PdfDocument:
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)
self.mark_changed()
return insert_at
def insert_pdf(self, source_path: str | Path, after_page_index: int | None = None) -> int:
@@ -218,6 +261,7 @@ class PdfDocument:
with fitz.open(source_path) as source:
count = source.page_count
self._doc.insert_pdf(source, start_at=insert_at)
self.mark_changed()
return count
def extract_pages(self, page_numbers: list[int], target_path: str | Path) -> None:
@@ -328,6 +372,38 @@ class PdfDocument:
}
)
self._doc.set_metadata(metadata)
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,
)
)
annot = annot.next
return items
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:
page.delete_annot(annot)
self.mark_changed()
return True
annot = annot.next
return False
def form_fields(self) -> list[FormField]:
if not self._doc:
@@ -358,6 +434,7 @@ class PdfDocument:
if widget.field_name == field_name:
widget.field_value = value
widget.update()
self.mark_changed()
return True
return False
@@ -365,6 +442,7 @@ class PdfDocument:
if not self._doc:
raise RuntimeError("没有打开 PDF")
self._doc.delete_page(page_index)
self.mark_changed()
def save(self) -> None:
if not self.path:
@@ -378,20 +456,25 @@ class PdfDocument:
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
original_path = self.path
if original_path and target.resolve() == original_path.resolve():
self._doc.saveIncr()
self._doc.close()
self.path = target
self._doc = fitz.open(target)
self.mark_changed()
return
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)
self.mark_changed()
finally:
if temp_path.exists():
temp_path.unlink()
@@ -421,6 +504,26 @@ class PdfDocument:
raise IndexError("页码超出范围")
return self._doc.load_page(page_index)
def mark_changed(self) -> None:
self._revision += 1
self.clear_cache()
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)
@staticmethod
def _default_rect(page: fitz.Page) -> fitz.Rect:
width = min(220, page.rect.width * 0.45)
+65
View File
@@ -422,6 +422,68 @@ class MainWindow(QMainWindow):
else:
QMessageBox.warning(self, "填写失败", "没有找到对应的表单字段。")
def show_annotations(self) -> None:
if not self._ensure_document():
return
annotations = self.document.annotations()
if not annotations:
QMessageBox.information(self, "注释列表", "当前 PDF 没有注释。")
return
dialog = QDialog(self)
dialog.setWindowTitle("注释列表")
layout = QVBoxLayout(dialog)
annotation_list = QListWidget()
for annotation in annotations:
content = annotation.content or annotation.annotation_type
item = QListWidgetItem(
f"第 {annotation.page_index + 1} 页 {annotation.annotation_type} {content}"
)
item.setData(Qt.ItemDataRole.UserRole, annotation)
annotation_list.addItem(item)
layout.addWidget(annotation_list)
buttons = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Close
)
buttons.button(QDialogButtonBox.StandardButton.Ok).setText("跳转")
delete_button = buttons.addButton("删除", QDialogButtonBox.ButtonRole.ActionRole)
buttons.accepted.connect(dialog.accept)
buttons.rejected.connect(dialog.reject)
layout.addWidget(buttons)
deleted = {"value": False}
def delete_selected_annotation() -> None:
item = annotation_list.currentItem()
if not item:
return
annotation = item.data(Qt.ItemDataRole.UserRole)
reply = QMessageBox.question(
self,
"删除注释",
"确定删除选中的注释吗?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
)
if reply == QMessageBox.StandardButton.Yes:
self.document.delete_annotation(annotation.page_index, annotation.xref)
self.viewer.render()
self.statusBar().showMessage("注释已删除,记得保存", 3000)
deleted["value"] = True
dialog.accept()
delete_button.clicked.connect(delete_selected_annotation)
result = dialog.exec()
if deleted["value"]:
return
item = annotation_list.currentItem()
if not item:
return
annotation = item.data(Qt.ItemDataRole.UserRole)
if result == QDialog.DialogCode.Accepted:
self.viewer.go_to_page(annotation.page_index)
def go_to_page_dialog(self) -> None:
if not self._ensure_document():
return
@@ -519,6 +581,7 @@ class MainWindow(QMainWindow):
self.metadata_action = QAction("文档信息", self)
self.metadata_action.setShortcut(QKeySequence("Ctrl+I"))
self.form_fill_action = QAction("填写表单", self)
self.annotation_list_action = QAction("注释列表", self)
self.highlight_action = QAction("高亮", self)
self.highlight_action.setShortcut(QKeySequence("Ctrl+H"))
self.underline_action = QAction("下划线", self)
@@ -571,6 +634,7 @@ class MainWindow(QMainWindow):
tools_menu.addAction(self.images_to_pdf_action)
tools_menu.addAction(self.metadata_action)
tools_menu.addAction(self.form_fill_action)
tools_menu.addAction(self.annotation_list_action)
edit_menu = self.menuBar().addMenu("编辑")
edit_menu.addAction(self.highlight_action)
@@ -647,6 +711,7 @@ class MainWindow(QMainWindow):
self.images_to_pdf_action.triggered.connect(self.images_to_pdf)
self.metadata_action.triggered.connect(self.edit_metadata)
self.form_fill_action.triggered.connect(self.fill_form_field)
self.annotation_list_action.triggered.connect(self.show_annotations)
self.highlight_action.triggered.connect(self.highlight_current_page)
self.underline_action.triggered.connect(self.underline_current_page)
self.strikeout_action.triggered.connect(self.strikeout_current_page)
+20 -3
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from PySide6.QtCore import QSize, Qt, Signal
from PySide6.QtCore import QSize, Qt, QTimer, Signal
from PySide6.QtGui import QIcon, QPixmap
from PySide6.QtWidgets import QListWidget, QListWidgetItem, QTabWidget, QWidget, QVBoxLayout
@@ -12,18 +12,25 @@ class ThumbnailList(QListWidget):
def __init__(self) -> None:
super().__init__()
self.document: PdfDocument | None = None
self._next_thumbnail_index = 0
self._thumbnail_timer = QTimer(self)
self._thumbnail_timer.timeout.connect(self._render_next_thumbnail)
self.setIconSize(QSize(132, 176))
self.setViewMode(QListWidget.ViewMode.ListMode)
self.setSpacing(8)
self.itemClicked.connect(self._emit_page)
def load_document(self, document: PdfDocument) -> None:
self._thumbnail_timer.stop()
self.document = document
self._next_thumbnail_index = 0
self.clear()
for page_index in range(document.page_count):
image = document.render_thumbnail(page_index)
item = QListWidgetItem(QIcon(QPixmap.fromImage(image)), f"第 {page_index + 1} 页")
item = QListWidgetItem(f"第 {page_index + 1} 页")
item.setData(Qt.ItemDataRole.UserRole, page_index)
self.addItem(item)
self._thumbnail_timer.start(1)
def select_page(self, page_index: int) -> None:
if 0 <= page_index < self.count():
@@ -33,6 +40,16 @@ class ThumbnailList(QListWidget):
page_index = item.data(Qt.ItemDataRole.UserRole)
self.page_selected.emit(page_index)
def _render_next_thumbnail(self) -> None:
if not self.document or self._next_thumbnail_index >= self.count():
self._thumbnail_timer.stop()
return
page_index = self._next_thumbnail_index
item = self.item(page_index)
image = self.document.render_thumbnail(page_index)
item.setIcon(QIcon(QPixmap.fromImage(image)))
self._next_thumbnail_index += 1
class Sidebar(QTabWidget):
page_selected = Signal(int)
+4
View File
@@ -63,12 +63,16 @@ def main() -> int:
document = PdfDocument()
document.open(source_pdf)
assert document.render_page(0, 1.0).width() > 0
assert document.render_page(0, 1.0).width() > 0
assert document.search("feature")
assert document.highlight_text(0, "feature") == 1
assert document.underline_text(0, "feature") == 1
assert document.strikeout_text(0, "feature") == 1
document.add_note(0, "note")
annotations = document.annotations()
assert annotations
assert document.delete_annotation(annotations[0].page_index, annotations[0].xref)
document.add_text(0, "PDFReaderLite")
document.insert_image(0, image_path)
document.add_signature(0, image_path)