from __future__ import annotations from collections import OrderedDict 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 rects: list[tuple[float, float, float, float]] @dataclass(frozen=True) class Bookmark: level: int title: str page_index: int @dataclass(frozen=True) class FormField: page_index: int name: str field_type: str value: str @dataclass(frozen=True) class AnnotationInfo: page_index: int xref: int annotation_type: str content: str rect: tuple[float, float, float, float] | None = None class EncryptedPdfError(RuntimeError): pass class PdfDocument: _TEXT_MARKUP_TYPES = {"highlight", "underline", "strikeout", "squiggly"} _MAX_HISTORY_ITEMS = 20 _MAX_HISTORY_BYTES = 256 * 1024 * 1024 _MAX_SNAPSHOT_BYTES = 96 * 1024 * 1024 _MAX_SNAPSHOT_PAGES = 300 _MAX_RENDER_CACHE_BYTES = 192 * 1024 * 1024 def __init__(self) -> None: self.path: Path | None = None self._doc: fitz.Document | None = None self._revision = 0 self._dirty = False self._undo_stack: list[bytes] = [] self._redo_stack: list[bytes] = [] self._undo_stack_bytes = 0 self._redo_stack_bytes = 0 self._render_cache: OrderedDict[tuple[int, int, float], QImage] = OrderedDict() self._render_cache_bytes = 0 self._thumbnail_cache: OrderedDict[tuple[int, int, int], QImage] = OrderedDict() self._text_char_cache: OrderedDict[tuple[int, int], list[tuple[int, int, int, str, fitz.Rect]]] = OrderedDict() self._text_column_split_cache: OrderedDict[tuple[int, int], float | None] = OrderedDict() self._annotation_cache: OrderedDict[tuple[int, int | None], list[AnnotationInfo]] = OrderedDict() @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 @property def is_dirty(self) -> bool: return self._dirty @property def revision(self) -> int: return self._revision def open(self, path: str | Path, password: str | None = None) -> None: self.close() self.path = Path(path) self._doc = fitz.open("pdf", self.path.read_bytes()) if self._doc.needs_pass: if not password or not self._doc.authenticate(password): self.close() raise EncryptedPdfError("该 PDF 需要密码。") self._dirty = False self.clear_history() def open_bytes(self, data: bytes, title: str | Path | None = None, password: str | None = None) -> None: self.close() self.path = Path(title) if title else None self._doc = fitz.open("pdf", data) if self._doc.needs_pass: if not password or not self._doc.authenticate(password): self.close() raise EncryptedPdfError("该 PDF 需要密码。") self._dirty = False self.clear_history() def close(self) -> None: if self._doc: self._doc.close() self._doc = None self.path = None self._dirty = False self.clear_history() 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) image = QImage( pixmap.samples, pixmap.width, pixmap.height, pixmap.stride, QImage.Format.Format_RGB888, ) cached = image.copy() self._remember_image_cache_item(self._render_cache, cache_key, cached) 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 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() self._remember_cache_item(self._thumbnail_cache, cache_key, thumbnail, max_items=80) return thumbnail.copy() def page_rect(self, page_index: int) -> tuple[float, float, float, float]: return self._rect_tuple(self._page(page_index).rect) def search(self, text: str, limit: int = 200, progress_callback=None) -> 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 progress_callback and not progress_callback(page_index + 1, self.page_count): break rects = page.search_for(query) if rects: 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, rects=[self._rect_tuple(rect) for rect in rects], ) ) if len(matches) >= limit: break return matches def bookmarks(self) -> list[Bookmark]: if not self._doc: raise RuntimeError("没有打开 PDF") items: list[Bookmark] = [] for entry in self._doc.get_toc(simple=True): if len(entry) < 3: continue level, title, page_number = entry[:3] page_index = int(page_number) - 1 if 0 <= page_index < self.page_count: items.append(Bookmark(level=max(1, int(level)), title=str(title), page_index=page_index)) return items def rotate_page(self, page_index: int, degrees: int = 90) -> None: page = self._page(page_index) self.snapshot() page.set_rotation((page.rotation + degrees) % 360) self.mark_changed() def rotate_pages(self, page_indices: list[int], degrees: int = 90) -> None: if not self._doc: raise RuntimeError("没有打开 PDF") unique_pages = sorted(set(page_indices)) if not unique_pages: return for page_index in unique_pages: if page_index < 0 or page_index >= self.page_count: raise IndexError("页码超出范围") self.snapshot() for page_index in unique_pages: 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) rects = page.search_for(text.strip()) if rects: self.snapshot() 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: page = self._page(page_index) rects = page.search_for(text.strip()) if rects: self.snapshot() 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: page = self._page(page_index) rects = page.search_for(text.strip()) if rects: self.snapshot() for rect in rects: annot = page.add_strikeout_annot(rect) annot.update() if rects: self.mark_changed() return len(rects) def text_selection( self, page_index: int, rect: tuple[float, float, float, float], start: tuple[float, float] | None = None, end: tuple[float, float] | None = None, ) -> tuple[str, list[tuple[float, float, float, float]]]: page = self._page(page_index) selection = self._normalized_rect(rect) all_chars = self._page_text_chars(page) selectable_chars = all_chars if start is not None: column_split = self._page_text_column_split(page.number, all_chars, float(page.rect.width)) if column_split is not None: start_column = 0 if float(start[0]) < column_split else 1 column_chars = [ char_item for char_item in all_chars if self._char_belongs_to_column(char_item, column_split, start_column) ] if column_chars: selectable_chars = column_chars selected_chars: list[tuple[int, int, int, str, fitz.Rect]] = [] if start is not None and end is not None and selectable_chars: start_index = self._text_char_index_for_point(selectable_chars, start) end_index = self._text_char_index_for_point(selectable_chars, end) if start_index is not None and end_index is not None: first = min(start_index, end_index) last = max(start_index, end_index) selected_chars = selectable_chars[first : last + 1] if not selected_chars: for char_item in selectable_chars: char_rect = char_item[4] if not selection.intersects(char_rect): continue selected_chars.append(char_item) if not selected_chars: return "", [] if start is not None: selected_chars = self._filter_chars_to_start_cluster( selected_chars, start, float(page.rect.width), ) if not selected_chars: return "", [] lines: list[str] = [] current_key: tuple[int, int] | None = None current_chars: list[str] = [] rects: list[tuple[float, float, float, float]] = [] for block, line, _char_index, text, char_rect in selected_chars: key = (block, line) if current_key is not None and key != current_key: lines.append("".join(current_chars)) current_chars = [] current_key = key current_chars.append(text) rects.append(self._rect_tuple(char_rect)) if current_chars: lines.append("".join(current_chars)) return "\n".join(lines), rects def _page_text_column_split( self, page_index: int, chars: list[tuple[int, int, int, str, fitz.Rect]], page_width: float, ) -> float | None: cache_key = (self._revision, page_index) if cache_key in self._text_column_split_cache: self._text_column_split_cache.move_to_end(cache_key) return self._text_column_split_cache[cache_key] split = self._detect_text_char_column_split(chars, page_width) self._remember_cache_item(self._text_column_split_cache, cache_key, split, max_items=16) return split def _page_text_chars(self, page: fitz.Page) -> list[tuple[int, int, int, str, fitz.Rect]]: cache_key = (self._revision, page.number) if cache_key in self._text_char_cache: self._text_char_cache.move_to_end(cache_key) return self._text_char_cache[cache_key] raw = page.get_text("rawdict") lines: list[dict[str, object]] = [] page_width = float(page.rect.width) for block_index, block in enumerate(raw.get("blocks", [])): for line_index, line in enumerate(block.get("lines", [])): direction = line.get("dir", (1, 0)) if not PdfDocument._is_selectable_text_direction(direction): continue line_chars: list[tuple[int, int, str, fitz.Rect]] = [] for span in line.get("spans", []): for char in span.get("chars", []): text = str(char.get("c", "")) bbox = char.get("bbox") if not text or not bbox: continue line_chars.append((block_index, line_index, text, fitz.Rect(bbox))) if not line_chars: continue line_rect = PdfDocument._union_rect([item[3] for item in line_chars]) line_text = "".join(item[2] for item in line_chars).strip() if not line_text: continue lines.append( { "chars": line_chars, "rect": line_rect, "text": line_text, } ) body_left = PdfDocument._estimate_body_left(lines, page_width) selectable_lines: list[dict[str, object]] = [] for line in lines: line_rect = line["rect"] line_text = str(line["text"]) if isinstance(line_rect, fitz.Rect) and PdfDocument._is_margin_artifact_line( line_text, line_rect, body_left, ): continue selectable_lines.append(line) ordered_lines = PdfDocument._sort_text_lines_reading_order(selectable_lines, page_width) chars: list[tuple[int, int, int, str, fitz.Rect]] = [] char_index = 0 for reading_line_index, line in enumerate(ordered_lines): for _block_index, _line_index, text, rect in line["chars"]: chars.append((0, reading_line_index, char_index, text, rect)) char_index += 1 self._remember_cache_item(self._text_char_cache, cache_key, chars, max_items=8) return chars @staticmethod def _is_selectable_text_direction(direction: object) -> bool: try: dx, dy = direction return abs(float(dy)) <= 0.12 and abs(float(dx)) >= 0.85 except Exception: return True @staticmethod def _union_rect(rects: list[fitz.Rect]) -> fitz.Rect: rect = fitz.Rect(rects[0]) for item in rects[1:]: rect |= item return rect @staticmethod def _estimate_body_left(lines: list[dict[str, object]], page_width: float) -> float: candidates: list[float] = [] for line in lines: rect = line["rect"] text = str(line["text"]) if not isinstance(rect, fitz.Rect): continue if rect.width < page_width * 0.16: continue if len(text) < 12: continue if not any(char.isalpha() or "\u4e00" <= char <= "\u9fff" for char in text): continue candidates.append(float(rect.x0)) if not candidates: return page_width * 0.08 candidates.sort() return candidates[min(len(candidates) - 1, max(0, len(candidates) // 10))] @staticmethod def _is_margin_artifact_line(text: str, rect: fitz.Rect, body_left: float) -> bool: stripped = text.strip() if not stripped: return True if rect.x1 >= body_left - 5: return False compact = stripped.replace(" ", "") if compact.isdigit(): return True if len(compact) <= 3 and rect.width <= 28: return True return False @staticmethod def _sort_text_lines_reading_order( lines: list[dict[str, object]], page_width: float, ) -> list[dict[str, object]]: if len(lines) < 6: return sorted(lines, key=PdfDocument._line_yx_sort_key) body_lines = [ line for line in lines if isinstance(line.get("rect"), fitz.Rect) and fitz.Rect(line["rect"]).width < page_width * 0.62 and len(str(line.get("text", "")).strip()) >= 6 ] split = PdfDocument._detect_column_split(body_lines, page_width) if split is None: return sorted(lines, key=PdfDocument._line_yx_sort_key) column_lines = [ line for line in lines if isinstance(line.get("rect"), fitz.Rect) and not PdfDocument._line_spans_column_split(fitz.Rect(line["rect"]), split, page_width) ] if not column_lines: return sorted(lines, key=PdfDocument._line_yx_sort_key) top_y = min(fitz.Rect(line["rect"]).y0 for line in column_lines) bottom_y = max(fitz.Rect(line["rect"]).y1 for line in column_lines) def sort_key(line: dict[str, object]) -> tuple[int, int, float, float]: rect = fitz.Rect(line["rect"]) if PdfDocument._line_spans_column_split(rect, split, page_width): if rect.y1 < top_y - 2: return (0, 0, rect.y0, rect.x0) if rect.y0 > bottom_y + 2: return (3, 0, rect.y0, rect.x0) return (2, 0, rect.y0, rect.x0) column = 0 if rect.x0 < split else 1 return (1, column, rect.y0, rect.x0) return sorted(lines, key=sort_key) @staticmethod def _detect_column_split(lines: list[dict[str, object]], page_width: float) -> float | None: centers = sorted(float((fitz.Rect(line["rect"]).x0 + fitz.Rect(line["rect"]).x1) / 2) for line in lines) if len(centers) < 6: return None best_gap = 0.0 best_index = -1 for index in range(len(centers) - 1): gap = centers[index + 1] - centers[index] if gap > best_gap: best_gap = gap best_index = index if best_index < 0 or best_gap < page_width * 0.12: return None left_count = best_index + 1 right_count = len(centers) - left_count if left_count < 3 or right_count < 3: return None split = (centers[best_index] + centers[best_index + 1]) / 2 if split < page_width * 0.25 or split > page_width * 0.75: return None return split @staticmethod def _line_spans_column_split(rect: fitz.Rect, split: float, page_width: float) -> bool: margin = max(10.0, page_width * 0.025) return rect.x0 < split - margin and rect.x1 > split + margin @staticmethod def _line_yx_sort_key(line: dict[str, object]) -> tuple[float, float]: rect = fitz.Rect(line["rect"]) return (rect.y0, rect.x0) @staticmethod def _text_char_index_for_point( chars: list[tuple[int, int, int, str, fitz.Rect]], point: tuple[float, float], ) -> int | None: if not chars: return None px, py = point line_groups: dict[tuple[int, int], list[tuple[int, tuple[int, int, int, str, fitz.Rect]]]] = {} for index, char in enumerate(chars): line_groups.setdefault((char[0], char[1]), []).append((index, char)) best_line: list[tuple[int, tuple[int, int, int, str, fitz.Rect]]] | None = None best_distance: tuple[float, float] | None = None for line_chars in line_groups.values(): y0 = min(item[1][4].y0 for item in line_chars) y1 = max(item[1][4].y1 for item in line_chars) x0 = min(item[1][4].x0 for item in line_chars) x1 = max(item[1][4].x1 for item in line_chars) if y0 <= py <= y1: y_distance = 0.0 else: y_distance = min(abs(py - y0), abs(py - y1)) if x0 <= px <= x1: x_distance = 0.0 else: x_distance = min(abs(px - x0), abs(px - x1)) distance = (y_distance, x_distance) if best_distance is None or distance < best_distance: best_distance = distance best_line = line_chars if not best_line: return None best_index = best_line[0][0] best_x_distance: float | None = None for index, char in best_line: rect = char[4] if rect.x0 <= px <= rect.x1: return index distance = min(abs(px - rect.x0), abs(px - rect.x1)) if best_x_distance is None or distance < best_x_distance: best_x_distance = distance best_index = index return best_index @staticmethod def _detect_text_char_column_split( chars: list[tuple[int, int, int, str, fitz.Rect]], page_width: float, ) -> float | None: if len(chars) < 80: return None line_groups: dict[int, list[tuple[int, int, int, str, fitz.Rect]]] = {} for char_item in chars: line_groups.setdefault(char_item[1], []).append(char_item) lines: list[dict[str, object]] = [] for line_chars in line_groups.values(): rect = PdfDocument._union_rect([char_item[4] for char_item in line_chars]) text = "".join(char_item[3] for char_item in line_chars).strip() if len(text) < 6: continue lines.append({"rect": rect, "text": text}) split = PdfDocument._detect_column_split(lines, page_width) if split is not None: return split centers = sorted((char_item[4].x0 + char_item[4].x1) / 2 for char_item in chars) if len(centers) < 80: return None best_gap = 0.0 best_index = -1 for index in range(len(centers) - 1): gap = centers[index + 1] - centers[index] if gap > best_gap: best_gap = gap best_index = index if best_index < 0 or best_gap < page_width * 0.035: return None left_count = best_index + 1 right_count = len(centers) - left_count if left_count < 20 or right_count < 20: return None split = (centers[best_index] + centers[best_index + 1]) / 2 if split < page_width * 0.25 or split > page_width * 0.75: return None return split @staticmethod def _filter_chars_to_start_cluster( chars: list[tuple[int, int, int, str, fitz.Rect]], start: tuple[float, float], page_width: float, ) -> list[tuple[int, int, int, str, fitz.Rect]]: if len(chars) < 24: return chars centers = sorted((char_item[4].x0 + char_item[4].x1) / 2 for char_item in chars) best_gap = 0.0 best_index = -1 for index in range(len(centers) - 1): gap = centers[index + 1] - centers[index] if gap > best_gap: best_gap = gap best_index = index if best_index < 0 or best_gap < max(14.0, page_width * 0.025): return chars left_count = best_index + 1 right_count = len(centers) - left_count if left_count < 8 or right_count < 8: return chars split = (centers[best_index] + centers[best_index + 1]) / 2 if split < page_width * 0.25 or split > page_width * 0.75: return chars start_column = 0 if float(start[0]) < split else 1 return [ char_item for char_item in chars if PdfDocument._char_belongs_to_column(char_item, split, start_column) ] @staticmethod def _char_belongs_to_column( char_item: tuple[int, int, int, str, fitz.Rect], split: float, column: int, ) -> bool: rect = char_item[4] center_x = (rect.x0 + rect.x1) / 2 return center_x < split if column == 0 else center_x >= split @staticmethod def _point_on_spanning_text_line( chars: list[tuple[int, int, int, str, fitz.Rect]], point: tuple[float, float], split: float, page_width: float, ) -> bool: px, py = point line_groups: dict[int, list[tuple[int, int, int, str, fitz.Rect]]] = {} for char_item in chars: line_groups.setdefault(char_item[1], []).append(char_item) for line_chars in line_groups.values(): rect = PdfDocument._union_rect([char_item[4] for char_item in line_chars]) if rect.y0 <= py <= rect.y1 and rect.x0 - 2 <= px <= rect.x1 + 2: return PdfDocument._line_spans_column_split(rect, split, page_width) return False def add_text_markup( self, page_index: int, rects: list[tuple[float, float, float, float]], markup: str, content: str = "", color: tuple[float, float, float] | None = None, ) -> AnnotationInfo | None: if not rects: return None page = self._page(page_index) fitz_rects = self._merge_markup_rects_for_selection( [self._normalized_rect(rect) for rect in rects], float(page.rect.width), ) if not fitz_rects: return None self.snapshot() if markup == "highlight": annot = page.add_highlight_annot(fitz_rects) elif markup == "underline": annot = page.add_underline_annot(fitz_rects) elif markup == "strikeout": annot = page.add_strikeout_annot(fitz_rects) else: raise ValueError("未知的文本标记类型") if color: annot.set_colors(stroke=color) if content: annot.set_info(content=content) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) def add_note( self, page_index: int, text: str, point: tuple[float, float] | None = None, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) x, y = point or (72, 72) annot = page.add_text_annot(fitz.Point(x, y), text) annot.set_info(content=text) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=text, rect=self._rect_tuple(annot.rect), ) def add_text( self, page_index: int, text: str, point: tuple[float, float] | None = None, font_size: int = 14, text_color: tuple[float, float, float] = (0, 0, 0), ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) 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=max(8, min(72, int(font_size))), fontname="china-s", text_color=text_color, border_width=0, ) annot.set_info(content=text) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=text, rect=self._rect_tuple(annot.rect), ) def add_area_highlight( self, page_index: int, rect: tuple[float, float, float, float], color: tuple[float, float, float] = (1.0, 0.92, 0.2), opacity: float = 0.35, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) annot = page.add_rect_annot(self._normalized_rect(rect)) annot.set_colors(stroke=color, fill=color) annot.set_border(width=0) annot.set_opacity(max(0.1, min(1.0, float(opacity)))) annot.set_info(content="区域高亮") annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content="区域高亮", rect=self._rect_tuple(annot.rect), ) def add_area_line_mark( self, page_index: int, rect: tuple[float, float, float, float], strikeout: bool = False, color: tuple[float, float, float] = (0.9, 0.1, 0.1), border_width: float = 2, opacity: float = 1.0, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) area = self._normalized_rect(rect) y = area.y0 + area.height * (0.55 if strikeout else 0.88) annot = page.add_line_annot(fitz.Point(area.x0, y), fitz.Point(area.x1, y)) self._apply_annotation_style(annot, color, border_width, opacity) annot.set_info(content="区域删除线" if strikeout else "区域下划线") annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) def add_text_stamp( self, page_index: int, text: str, point: tuple[float, float] | None = None, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) x0, y0 = point or (96, 120) width = max(120, min(page.rect.width - x0 - 24, len(text) * 34 + 36)) height = 58 rect = fitz.Rect(x0, y0, x0 + width, y0 + height) annot = page.add_freetext_annot( rect, text, fontsize=28, fontname="china-s", text_color=(0.85, 0.05, 0.05), fill_color=(1, 1, 1), border_width=2, opacity=0.86, align=1, ) annot.set_info(content=text) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=text, rect=self._rect_tuple(annot.rect), ) def insert_image( self, page_index: int, image_path: str | Path, point: tuple[float, float] | None = None, ) -> None: 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]: page = self._page(page_index) page_rect = page.rect width = page_rect.width * 0.35 height = width * 0.75 x0, y0 = point or (72, 120) 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: image_file = Path(image_path) if not image_file.exists(): raise FileNotFoundError(f"图片文件不存在:{image_file}") page = self._page(page_index) target_rect = fitz.Rect(*rect) if target_rect.is_empty or target_rect.is_infinite: raise ValueError("图片区域无效") self.snapshot() page.insert_image(target_rect, filename=str(image_file), keep_proportion=True) self.mark_changed() def add_signature( self, page_index: int, image_path: str | Path, point: tuple[float, float] | None = None, ) -> None: 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]: page = self._page(page_index) page_rect = page.rect width = page_rect.width * 0.28 height = width * 0.42 margin = 54 if point: x0, y0 = point 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: image_file = Path(image_path) if not image_file.exists(): raise FileNotFoundError(f"签名图片不存在:{image_file}") page = self._page(page_index) target_rect = fitz.Rect(*rect) if target_rect.is_empty or target_rect.is_infinite: raise ValueError("签名区域无效") self.snapshot() page.insert_image(target_rect, filename=str(image_file), keep_proportion=True) self.mark_changed() def add_rectangle( self, page_index: int, stroke_color: tuple[float, float, float] = (0.9, 0.1, 0.1), border_width: float = 2, opacity: float = 1.0, rect: tuple[float, float, float, float] | None = None, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) target_rect = self._normalized_rect(rect) if rect else self._default_rect(page) annot = page.add_rect_annot(target_rect) self._apply_annotation_style(annot, stroke_color, border_width, opacity) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) def add_circle( self, page_index: int, stroke_color: tuple[float, float, float] = (0.1, 0.3, 0.9), border_width: float = 2, opacity: float = 1.0, rect: tuple[float, float, float, float] | None = None, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) target_rect = self._normalized_rect(rect) if rect else self._default_rect(page) annot = page.add_circle_annot(target_rect) self._apply_annotation_style(annot, stroke_color, border_width, opacity) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) def add_line( self, page_index: int, arrow: bool = False, stroke_color: tuple[float, float, float] = (0.1, 0.1, 0.1), border_width: float = 2, opacity: float = 1.0, start_point: tuple[float, float] | None = None, end_point: tuple[float, float] | None = None, ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) if start_point and end_point: start = fitz.Point(float(start_point[0]), float(start_point[1])) end = fitz.Point(float(end_point[0]), float(end_point[1])) else: 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) self._apply_annotation_style(annot, stroke_color, border_width, opacity) if arrow: annot.set_line_ends(fitz.PDF_ANNOT_LE_NONE, fitz.PDF_ANNOT_LE_CLOSED_ARROW) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) def add_ink( self, page_index: int, points: list[tuple[float, float]], stroke_color: tuple[float, float, float] = (0.05, 0.05, 0.05), border_width: float = 2, opacity: float = 1.0, ) -> AnnotationInfo | None: if len(points) < 2: return None self.snapshot() page = self._page(page_index) stroke_points = [(float(x), float(y)) for x, y in points] annot = page.add_ink_annot([stroke_points]) self._apply_annotation_style(annot, stroke_color, border_width, opacity) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) def add_cover_area( self, page_index: int, fill_color: tuple[float, float, float] = (1, 1, 1), opacity: float = 1.0, text: str = "", ) -> AnnotationInfo: self.snapshot() page = self._page(page_index) rect = self._default_rect(page) annot = page.add_rect_annot(rect) annot.set_colors(stroke=fill_color, fill=fill_color) annot.set_border(width=0) annot.set_opacity(max(0.1, min(1.0, float(opacity)))) annot.set_info(content="遮盖") annot.update() if text.strip(): text_annot = page.add_freetext_annot( rect, text.strip(), fontsize=16, fontname="china-s", text_color=(0, 0, 0), fill_color=None, border_width=0, align=1, ) text_annot.set_info(content=text.strip()) text_annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content="遮盖", rect=self._rect_tuple(annot.rect), ) def insert_blank_page(self, after_page_index: int | None = None) -> int: if not self._doc: raise RuntimeError("没有打开 PDF") 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.snapshot() 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: if not self._doc: raise RuntimeError("没有打开 PDF") 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 if count <= 0: return 0 self.snapshot() 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: 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() 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") self.snapshot() metadata = self.metadata() metadata.update( { "title": title, "author": author, "subject": subject, "keywords": keywords, } ) self._doc.set_metadata(metadata) self.mark_changed() def annotations(self, page_index: int | None = None) -> list[AnnotationInfo]: if not self._doc: raise RuntimeError("没有打开 PDF") cache_key = (self._revision, page_index) if cache_key in self._annotation_cache: self._annotation_cache.move_to_end(cache_key) return list(self._annotation_cache[cache_key]) items: list[AnnotationInfo] = [] page_indexes = [page_index] if page_index is not None else range(self.page_count) for current_page_index in page_indexes: page = self._page(int(current_page_index)) annot = page.first_annot while annot: content = annot.info.get("content", "") if annot.info else "" items.append( AnnotationInfo( page_index=int(current_page_index), xref=annot.xref, annotation_type=annot.type[1], content=content, rect=self._rect_tuple(annot.rect), ) ) annot = annot.next self._remember_cache_item(self._annotation_cache, cache_key, list(items), max_items=96) return items 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: annot_type = annot.type[1].lower() if annot_type in self._TEXT_MARKUP_TYPES: hit_annotation = any(rect.contains(hit) for rect in self._annotation_markup_rects(annot, inflate=2.5)) else: hit_annotation = annot.rect.contains(hit) if hit_annotation: 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_text_selection( self, page_index: int, xref: int, include_text: bool = True, ) -> tuple[str, list[tuple[float, float, float, float]]] | None: page = self._page(page_index) annot = self._annotation(page_index, xref) if not annot or annot.type[1].lower() not in self._TEXT_MARKUP_TYPES: return None rects = self._merge_markup_rects_for_selection(self._annotation_markup_rects(annot), float(page.rect.width)) if not rects: return None if not include_text: return "", [self._rect_tuple(rect) for rect in rects] fallback_lines = [page.get_textbox(rect + (-1, -1, 1, 1)).strip() for rect in rects] fallback_text = "\n".join(line for line in fallback_lines if line) return fallback_text, [self._rect_tuple(rect) for rect in rects] @staticmethod def _annotation_markup_rects(annot, inflate: float = 0.0) -> list[fitz.Rect]: vertices = getattr(annot, "vertices", None) or [] rects: list[fitz.Rect] = [] for index in range(0, len(vertices), 4): quad_points = vertices[index : index + 4] if len(quad_points) < 4: continue xs: list[float] = [] ys: list[float] = [] for point in quad_points: try: xs.append(float(point.x)) ys.append(float(point.y)) except AttributeError: xs.append(float(point[0])) ys.append(float(point[1])) rect = fitz.Rect(min(xs), min(ys), max(xs), max(ys)) if rect.width > 0 and rect.height > 0: if inflate: rect = rect + (-inflate, -inflate, inflate, inflate) rects.append(rect) if rects: return rects rect = fitz.Rect(annot.rect) if annot.rect else None if rect and inflate: rect = rect + (-inflate, -inflate, inflate, inflate) return [rect] if rect else [] @staticmethod def _merge_markup_rects_for_selection(rects: list[fitz.Rect], page_width: float) -> list[fitz.Rect]: if not rects: return [] sorted_rects = sorted(rects, key=lambda rect: (round(rect.y0, 1), rect.x0)) lines: list[list[fitz.Rect]] = [] for rect in sorted_rects: placed = False center_y = (rect.y0 + rect.y1) / 2 for line in lines: line_rect = PdfDocument._union_rect(line) line_center_y = (line_rect.y0 + line_rect.y1) / 2 tolerance = max(3.0, min(rect.height, line_rect.height) * 0.65) if abs(center_y - line_center_y) <= tolerance: line.append(rect) placed = True break if not placed: lines.append([rect]) merged: list[fitz.Rect] = [] max_gap = max(8.0, page_width * 0.035) for line in lines: current: fitz.Rect | None = None for rect in sorted(line, key=lambda item: item.x0): if current is None: current = fitz.Rect(rect) continue gap = rect.x0 - current.x1 if gap <= max_gap: current |= rect else: merged.append(current) current = fitz.Rect(rect) if current is not None: merged.append(current) return merged def annotation_rect(self, page_index: int, xref: int) -> tuple[float, float, float, float] | None: page = self._page(page_index) annot = page.first_annot while annot: if annot.xref == xref: return self._rect_tuple(annot.rect) annot = annot.next return None def update_annotation_rect( self, page_index: int, xref: int, rect: tuple[float, float, float, float], ) -> bool: return self.update_annotation_rect_info(page_index, xref, rect) is not None def update_annotation_rect_info( self, page_index: int, xref: int, rect: tuple[float, float, float, float], ) -> AnnotationInfo | None: page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot: return None x0, y0, x1, y1 = rect annot_type = annot.type[1].lower() min_size = 2 if annot_type in self._TEXT_MARKUP_TYPES else 12 if x1 - x0 < min_size or y1 - y0 < min_size: return None content = annot.info.get("content", "") if annot.info else "" style = self._annotation_visual_style_from_annot(annot) checkpoint = self._mutation_checkpoint() self.snapshot() try: page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot: return None target_rect = fitz.Rect(x0, y0, x1, y1) if annot_type in self._TEXT_MARKUP_TYPES: new_annot = self._replace_text_markup_annotation(page, annot, annot_type, target_rect, content, style) if not new_annot: return None annot = new_annot else: annot.set_rect(target_rect) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) except Exception: self._rollback_mutation(checkpoint) raise def update_annotation_rects( self, page_index: int, rect_updates: dict[int, tuple[float, float, float, float]], ) -> dict[int, AnnotationInfo]: if not rect_updates: return {} normalized_updates: dict[int, fitz.Rect] = {} for xref, rect in rect_updates.items(): x0, y0, x1, y1 = rect if x1 - x0 < 2 or y1 - y0 < 2: continue normalized_updates[int(xref)] = fitz.Rect(x0, y0, x1, y1) if not normalized_updates: return {} checkpoint = self._mutation_checkpoint() self.snapshot() page = self._page(page_index) targets = [] annot = page.first_annot while annot: if annot.xref in normalized_updates: targets.append((annot.xref, annot, normalized_updates[annot.xref])) annot = annot.next if not targets: return {} try: updated: dict[int, AnnotationInfo] = {} for original_xref, annot, rect in targets: annot_type = annot.type[1].lower() content = annot.info.get("content", "") if annot.info else "" if annot_type not in self._TEXT_MARKUP_TYPES and (rect.width < 12 or rect.height < 12): continue if annot_type in self._TEXT_MARKUP_TYPES: style = self._annotation_visual_style_from_annot(annot) new_annot = self._replace_text_markup_annotation(page, annot, annot_type, rect, content, style) if not new_annot: continue annot = new_annot else: annot.set_rect(rect) annot.update() updated[original_xref] = AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) self.mark_changed() return updated except Exception: self._rollback_mutation(checkpoint) raise 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)) def update_annotation_content(self, page_index: int, xref: int, content: str) -> bool: if not self._annotation(page_index, xref): return False self.snapshot() page = self._page(page_index) annot = page.first_annot while annot: if annot.xref == xref: annot.set_info(content=content) annot.update() self.mark_changed() return True annot = annot.next return False def update_annotation_style( self, page_index: int, xref: int, stroke_color: tuple[float, float, float], border_width: float, opacity: float, content: str | None = None, ) -> AnnotationInfo | None: page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot: return None annot_type = annot.type[1].lower() content_text = annot.info.get("content", "") if annot.info else "" self.snapshot() page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot: return None if annot_type == "square" and content_text == "区域高亮": annot.set_colors(stroke=stroke_color, fill=stroke_color) annot.set_border(width=0) elif annot_type in {"square", "circle"}: annot.set_colors(stroke=stroke_color) annot.set_border(width=max(0, float(border_width))) elif annot_type in {"line", "ink", "underline", "strikeout", "highlight"}: annot.set_colors(stroke=stroke_color) annot.set_border(width=max(0, float(border_width))) elif annot_type == "text": annot.set_colors(stroke=stroke_color) elif annot_type == "freetext": annot.set_colors(stroke=stroke_color) else: annot.set_colors(stroke=stroke_color) annot.set_border(width=max(0, float(border_width))) if annot_type not in {"text", "freetext", "square", "circle", "line", "ink", "underline", "strikeout", "highlight"}: annot.set_border(width=max(0, float(border_width))) annot.set_opacity(max(0.1, min(1.0, float(opacity)))) if content is not None: annot.set_info(content=content) annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=annot.xref, annotation_type=annot.type[1], content=annot.info.get("content", "") if annot.info else "", rect=self._rect_tuple(annot.rect), ) def update_text_markup_color( self, page_index: int, xref: int, color: tuple[float, float, float], ) -> AnnotationInfo | None: page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot: return None annot_type = annot.type[1].lower() if annot_type not in self._TEXT_MARKUP_TYPES: return None content = annot.info.get("content", "") if annot.info else "" rects = self._merge_markup_rects_for_selection( self._annotation_markup_rects(annot), float(page.rect.width), ) if not rects: return None checkpoint = self._mutation_checkpoint() self.snapshot() try: page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot: return None page.delete_annot(annot) if annot_type == "highlight": new_annot = page.add_highlight_annot(rects) elif annot_type == "underline": new_annot = page.add_underline_annot(rects) elif annot_type == "strikeout": new_annot = page.add_strikeout_annot(rects) elif annot_type == "squiggly": new_annot = page.add_squiggly_annot(rects) else: return None new_annot.set_colors(stroke=color) if content: new_annot.set_info(content=content) new_annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=new_annot.xref, annotation_type=new_annot.type[1], content=new_annot.info.get("content", "") if new_annot.info else "", rect=self._rect_tuple(new_annot.rect), ) except Exception: self._rollback_mutation(checkpoint) raise def update_freetext_annotation( self, page_index: int, xref: int, content: str, font_size: int, text_color: tuple[float, float, float], ) -> AnnotationInfo | None: page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot or annot.type[1].lower() != "freetext": return None rect = self._rect_tuple(annot.rect) checkpoint = self._mutation_checkpoint() self.snapshot() try: page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot: return None page.delete_annot(annot) new_annot = page.add_freetext_annot( fitz.Rect(*rect), content, fontsize=max(8, min(72, int(font_size))), fontname="china-s", text_color=text_color, border_width=0, ) new_annot.set_info(content=content) new_annot.update() self.mark_changed() return AnnotationInfo( page_index=page_index, xref=new_annot.xref, annotation_type=new_annot.type[1], content=content, rect=self._rect_tuple(new_annot.rect), ) except Exception: self._rollback_mutation(checkpoint) raise def duplicate_annotation_info( self, annotation: AnnotationInfo, target_page_index: int, offset: tuple[float, float] = (18, 18), ) -> AnnotationInfo | None: if not annotation.rect: return None dx, dy = offset rect = fitz.Rect(*annotation.rect) + (dx, dy, dx, dy) content = annotation.content or "" annot_type = annotation.annotation_type.lower() source_style = self._annotation_visual_style(annotation.page_index, annotation.xref) self.snapshot() page = self._page(target_page_index) if annot_type == "freetext": duplicate = page.add_freetext_annot( rect, content, fontsize=14, fontname="china-s", text_color=(0, 0, 0), border_width=0, ) elif annot_type == "text": duplicate = page.add_text_annot(rect.tl, content) elif annot_type in {"square", "rect"}: duplicate = page.add_rect_annot(rect) elif annot_type in {"circle", "ellipse"}: duplicate = page.add_circle_annot(rect) elif annot_type == "line": start = fitz.Point(rect.x0, rect.y0 + rect.height / 2) end = fitz.Point(rect.x1, rect.y0 + rect.height / 2) duplicate = page.add_line_annot(start, end) elif annot_type == "highlight": duplicate = page.add_highlight_annot(rect) elif annot_type == "underline": duplicate = page.add_underline_annot(rect) elif annot_type == "strikeout": duplicate = page.add_strikeout_annot(rect) else: return None self._apply_annotation_visual_style_snapshot(duplicate, source_style) if content: duplicate.set_info(content=content) duplicate.update() self.mark_changed() return AnnotationInfo( page_index=target_page_index, xref=duplicate.xref, annotation_type=duplicate.type[1], content=content, rect=self._rect_tuple(duplicate.rect), ) def _annotation_visual_style(self, page_index: int, xref: int) -> dict[str, object]: page = self._page(page_index) annot = page.first_annot while annot and annot.xref != xref: annot = annot.next if not annot: return {} return self._annotation_visual_style_from_annot(annot) @staticmethod def _annotation_visual_style_from_annot(annot) -> dict[str, object]: colors = annot.colors or {} border = annot.border or {} style: dict[str, object] = { "stroke": colors.get("stroke"), "fill": colors.get("fill"), "border_width": border.get("width"), } try: style["opacity"] = annot.opacity except Exception: style["opacity"] = None return style def _replace_text_markup_annotation( self, page: fitz.Page, annot, annot_type: str, rect: fitz.Rect, content: str, style: dict[str, object], ): page.delete_annot(annot) if annot_type == "highlight": new_annot = page.add_highlight_annot(rect) elif annot_type == "underline": new_annot = page.add_underline_annot(rect) elif annot_type == "strikeout": new_annot = page.add_strikeout_annot(rect) elif annot_type == "squiggly": new_annot = page.add_squiggly_annot(rect) else: return None if content: new_annot.set_info(content=content) self._apply_annotation_visual_style_snapshot(new_annot, style) new_annot.update() return new_annot def _apply_annotation_visual_style_snapshot(self, annot, style: dict[str, object]) -> None: stroke = style.get("stroke") fill = style.get("fill") if stroke is not None or fill is not None: try: annot.set_colors(stroke=stroke, fill=fill) except Exception: if stroke is not None: annot.set_colors(stroke=stroke) border_width = style.get("border_width") if border_width is not None: try: annot.set_border(width=max(0, float(border_width))) except Exception: pass opacity = style.get("opacity") if opacity is not None: try: annot.set_opacity(max(0.1, min(1.0, float(opacity)))) except Exception: pass 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: self.snapshot() page.delete_annot(annot) self.mark_changed() return True annot = annot.next return False 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: self.snapshot() widget.field_value = value widget.update() self.mark_changed() return True return False def delete_page(self, page_index: int) -> None: if not self._doc: raise RuntimeError("没有打开 PDF") if page_index < 0 or page_index >= self.page_count: raise IndexError("页码超出范围") self.snapshot() self._doc.delete_page(page_index) self.mark_changed() 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() def reorder_pages(self, page_order: list[int]) -> None: if not self._doc: raise RuntimeError("没有打开 PDF") if not page_order: raise ValueError("页面顺序不能为空") if len(set(page_order)) != len(page_order): raise ValueError("页面顺序不能包含重复页面") if any(page_index < 0 or page_index >= self.page_count for page_index in page_order): 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) def apply_page_plan(self, page_plan: list[dict[str, object]]) -> None: if not self._doc: raise RuntimeError("没有打开 PDF") if not page_plan: raise ValueError("页面计划不能为空") current_order = [ int(entry["page_index"]) for entry in page_plan if entry.get("source") == "current" ] has_external = any(entry.get("source") == "external" for entry in page_plan) if not has_external and current_order == list(range(self.page_count)): return self.snapshot() rebuilt = fitz.open() external_docs: dict[str, fitz.Document] = {} try: for entry in page_plan: source = entry.get("source") page_index = int(entry["page_index"]) if source == "current": if page_index < 0 or page_index >= self.page_count: raise ValueError("页面计划包含超出范围的当前 PDF 页面") rebuilt.insert_pdf(self._doc, from_page=page_index, to_page=page_index) elif source == "external": path = str(entry["path"]) source_doc = external_docs.get(path) if source_doc is None: source_doc = fitz.open(path) external_docs[path] = source_doc if page_index < 0 or page_index >= source_doc.page_count: raise ValueError("页面计划包含超出范围的外部 PDF 页面") rebuilt.insert_pdf(source_doc, from_page=page_index, to_page=page_index) else: raise ValueError("未知页面来源") data = rebuilt.tobytes(garbage=4, deflate=True) finally: rebuilt.close() for source_doc in external_docs.values(): source_doc.close() self._replace_with_bytes(data) 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) original_path = self.path target.parent.mkdir(parents=True, exist_ok=True) with NamedTemporaryFile(delete=False, suffix=".pdf", dir=target.parent) as tmp: temp_path = Path(tmp.name) backup_path: Path | None = None try: self._doc.save(temp_path, garbage=4, deflate=True) self._validate_saved_pdf(temp_path) backup_path = self._write_recovery_copy(target.parent) self._doc.close() self._doc = None temp_path.replace(target) self.path = target self._doc = fitz.open("pdf", target.read_bytes()) self.mark_saved() except Exception: if self._doc is None: self.path = original_path if original_path and original_path.exists(): try: self._doc = fitz.open("pdf", original_path.read_bytes()) except Exception: self._restore_from_recovery_copy(backup_path) else: self._restore_from_recovery_copy(backup_path) raise finally: if temp_path.exists(): temp_path.unlink() self._delete_temp_pdf(backup_path) def save_encrypted( self, path: str | Path, password: str, allow_print: bool = True, allow_copy: bool = True, allow_modify: bool = False, ) -> None: if not self._doc: raise RuntimeError("没有打开 PDF") if not password: raise ValueError("密码不能为空") target = Path(path) original_path = self.path original_dirty = self._dirty target.parent.mkdir(parents=True, exist_ok=True) with NamedTemporaryFile(delete=False, suffix=".pdf", dir=target.parent) as tmp: temp_path = Path(tmp.name) backup_path: Path | None = None 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 try: self._doc.save( temp_path, garbage=4, deflate=True, encryption=fitz.PDF_ENCRYPT_AES_256, owner_pw=password, user_pw=password, permissions=permissions, ) self._validate_saved_pdf(temp_path, password) same_as_current = ( original_path is not None and target.resolve() == original_path.resolve() ) if same_as_current: backup_path = self._write_recovery_copy(target.parent) self._doc.close() self._doc = None temp_path.replace(target) if same_as_current: self.path = target self._doc = fitz.open("pdf", target.read_bytes()) if self._doc.needs_pass and not self._doc.authenticate(password): raise EncryptedPdfError("无法重新打开加密 PDF。") self.mark_saved() else: self._dirty = original_dirty except Exception: if self._doc is None: self.path = original_path self._restore_from_recovery_copy(backup_path) self._dirty = original_dirty raise finally: if temp_path.exists(): temp_path.unlink() self._delete_temp_pdf(backup_path) def to_bytes(self) -> bytes: if not self._doc: raise RuntimeError("没有打开 PDF") return self._doc.tobytes(garbage=4, deflate=True) def save_copy(self, path: str | Path) -> None: if not self._doc: raise RuntimeError("没有打开 PDF") target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) self._doc.save(target, garbage=4, deflate=True) self._validate_saved_pdf(target) def _write_recovery_copy(self, directory: Path) -> Path: with NamedTemporaryFile(delete=False, suffix=".pdf", dir=directory) as tmp: backup_path = Path(tmp.name) self.save_copy(backup_path) return backup_path def _restore_from_recovery_copy(self, backup_path: Path | None) -> None: if not backup_path or not backup_path.exists(): raise RuntimeError("无法恢复保存前的 PDF 内容") self._doc = fitz.open("pdf", backup_path.read_bytes()) def _delete_temp_pdf(self, path: Path | None) -> None: if not path: return try: if path.exists(): path.unlink() except OSError: pass def restore_bytes(self, data: bytes, dirty: bool = True) -> None: if self._doc: self._doc.close() self._doc = fitz.open("pdf", data) self._dirty = dirty self._revision += 1 self.clear_cache() 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) 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 def _apply_annotation_style( self, annot, stroke_color: tuple[float, float, float], border_width: float, opacity: float, ) -> None: annot.set_colors(stroke=stroke_color) annot.set_border(width=max(1, float(border_width))) annot.set_opacity(max(0.1, min(1.0, float(opacity)))) def mark_changed(self) -> None: self._revision += 1 self._dirty = True self.clear_cache() def mark_saved(self) -> None: self._revision += 1 self._dirty = False self.clear_cache() def snapshot(self) -> None: if not self._doc: return if self._should_skip_history_snapshot(): self.clear_history() return data = self.to_bytes() self._push_history(self._undo_stack, data, "undo") self._redo_stack.clear() self._redo_stack_bytes = 0 def _should_skip_history_snapshot(self) -> bool: if self.page_count >= self._MAX_SNAPSHOT_PAGES: return True if self.path and self.path.exists(): try: if self.path.stat().st_size >= self._MAX_SNAPSHOT_BYTES: return True except OSError: return False return False 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._push_history(self._redo_stack, self.to_bytes(), "redo") data = self._undo_stack.pop() self._undo_stack_bytes -= len(data) self._replace_with_bytes(data) return True def redo(self) -> bool: if not self._doc or not self._redo_stack: return False self._push_history(self._undo_stack, self.to_bytes(), "undo") data = self._redo_stack.pop() self._redo_stack_bytes -= len(data) self._replace_with_bytes(data) return True def clear_history(self) -> None: self._undo_stack.clear() self._redo_stack.clear() self._undo_stack_bytes = 0 self._redo_stack_bytes = 0 def _replace_with_bytes(self, data: bytes) -> None: if self._doc: self._doc.close() self._doc = fitz.open("pdf", data) self.mark_changed() def _mutation_checkpoint(self) -> tuple[bytes, bool, list[bytes], list[bytes], int, int]: return ( self.to_bytes(), self._dirty, list(self._undo_stack), list(self._redo_stack), self._undo_stack_bytes, self._redo_stack_bytes, ) def _rollback_mutation(self, checkpoint: tuple[bytes, bool, list[bytes], list[bytes], int, int]) -> None: data, dirty, undo_stack, redo_stack, undo_bytes, redo_bytes = checkpoint self.restore_bytes(data, dirty=dirty) self._undo_stack = undo_stack self._redo_stack = redo_stack self._undo_stack_bytes = undo_bytes self._redo_stack_bytes = redo_bytes def _push_history(self, stack: list[bytes], data: bytes, stack_name: str) -> None: if len(data) > self._MAX_HISTORY_BYTES: return stack.append(data) if stack_name == "undo": self._undo_stack_bytes += len(data) self._trim_history_stack(stack, "undo") else: self._redo_stack_bytes += len(data) self._trim_history_stack(stack, "redo") def _trim_history_stack(self, stack: list[bytes], stack_name: str) -> None: if stack_name == "undo": while ( len(stack) > self._MAX_HISTORY_ITEMS or self._undo_stack_bytes > self._MAX_HISTORY_BYTES ) and stack: self._undo_stack_bytes -= len(stack.pop(0)) else: while ( len(stack) > self._MAX_HISTORY_ITEMS or self._redo_stack_bytes > self._MAX_HISTORY_BYTES ) and stack: self._redo_stack_bytes -= len(stack.pop(0)) @staticmethod def _validate_saved_pdf(path: Path, password: str | None = None) -> None: with fitz.open(path) as check: if check.needs_pass and (not password or not check.authenticate(password)): raise EncryptedPdfError("保存后的 PDF 无法通过密码验证。") _ = check.page_count def clear_cache(self) -> None: self._render_cache.clear() self._render_cache_bytes = 0 self._thumbnail_cache.clear() self._text_char_cache.clear() self._text_column_split_cache.clear() self._annotation_cache.clear() def _remember_image_cache_item( self, cache: OrderedDict, key: tuple, image: QImage, ) -> None: if key in cache: self._render_cache_bytes -= max(0, cache[key].sizeInBytes()) cache[key] = image cache.move_to_end(key) self._render_cache_bytes += max(0, image.sizeInBytes()) while cache and self._render_cache_bytes > self._MAX_RENDER_CACHE_BYTES: _, removed = cache.popitem(last=False) self._render_cache_bytes -= max(0, removed.sizeInBytes()) @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) 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) @staticmethod def _normalized_rect(rect: tuple[float, float, float, float]) -> fitz.Rect: x0, y0, x1, y1 = rect normalized = fitz.Rect(float(x0), float(y0), float(x1), float(y1)).normalize() if normalized.width < 2: normalized.x1 = normalized.x0 + 2 if normalized.height < 2: normalized.y1 = normalized.y0 + 2 return normalized @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))