Release v0.2.3
This commit is contained in:
+397
-135
@@ -46,6 +46,11 @@ class EncryptedPdfError(RuntimeError):
|
||||
|
||||
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
|
||||
@@ -54,8 +59,14 @@ class PdfDocument:
|
||||
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:
|
||||
@@ -82,7 +93,18 @@ class PdfDocument:
|
||||
def open(self, path: str | Path, password: str | None = None) -> None:
|
||||
self.close()
|
||||
self.path = Path(path)
|
||||
self._doc = fitz.open(self.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()
|
||||
@@ -116,7 +138,7 @@ class PdfDocument:
|
||||
QImage.Format.Format_RGB888,
|
||||
)
|
||||
cached = image.copy()
|
||||
self._remember_cache_item(self._render_cache, cache_key, cached, max_items=16)
|
||||
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:
|
||||
@@ -143,13 +165,15 @@ class PdfDocument:
|
||||
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) -> list[SearchMatch]:
|
||||
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", " ")
|
||||
@@ -185,8 +209,8 @@ class PdfDocument:
|
||||
return items
|
||||
|
||||
def rotate_page(self, page_index: int, degrees: int = 90) -> None:
|
||||
self.snapshot()
|
||||
page = self._page(page_index)
|
||||
self.snapshot()
|
||||
page.set_rotation((page.rotation + degrees) % 360)
|
||||
self.mark_changed()
|
||||
|
||||
@@ -253,7 +277,7 @@ class PdfDocument:
|
||||
all_chars = self._page_text_chars(page)
|
||||
selectable_chars = all_chars
|
||||
if start is not None:
|
||||
column_split = self._detect_text_char_column_split(all_chars, float(page.rect.width))
|
||||
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 = [
|
||||
@@ -307,8 +331,25 @@ class PdfDocument:
|
||||
lines.append("".join(current_chars))
|
||||
return "\n".join(lines), rects
|
||||
|
||||
@staticmethod
|
||||
def _page_text_chars(page: fitz.Page) -> list[tuple[int, int, int, str, fitz.Rect]]:
|
||||
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)
|
||||
@@ -359,6 +400,7 @@ class PdfDocument:
|
||||
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
|
||||
@@ -644,7 +686,6 @@ class PdfDocument:
|
||||
) -> AnnotationInfo | None:
|
||||
if not rects:
|
||||
return None
|
||||
self.snapshot()
|
||||
page = self._page(page_index)
|
||||
fitz_rects = self._merge_markup_rects_for_selection(
|
||||
[self._normalized_rect(rect) for rect in rects],
|
||||
@@ -652,6 +693,7 @@ class PdfDocument:
|
||||
)
|
||||
if not fitz_rects:
|
||||
return None
|
||||
self.snapshot()
|
||||
if markup == "highlight":
|
||||
annot = page.add_highlight_annot(fitz_rects)
|
||||
elif markup == "underline":
|
||||
@@ -840,9 +882,15 @@ class PdfDocument:
|
||||
image_path: str | Path,
|
||||
rect: tuple[float, float, float, float],
|
||||
) -> None:
|
||||
self.snapshot()
|
||||
image_file = Path(image_path)
|
||||
if not image_file.exists():
|
||||
raise FileNotFoundError(f"图片文件不存在:{image_file}")
|
||||
page = self._page(page_index)
|
||||
page.insert_image(fitz.Rect(*rect), filename=str(image_path), keep_proportion=True)
|
||||
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(
|
||||
@@ -879,9 +927,15 @@ class PdfDocument:
|
||||
image_path: str | Path,
|
||||
rect: tuple[float, float, float, float],
|
||||
) -> None:
|
||||
self.snapshot()
|
||||
image_file = Path(image_path)
|
||||
if not image_file.exists():
|
||||
raise FileNotFoundError(f"签名图片不存在:{image_file}")
|
||||
page = self._page(page_index)
|
||||
page.insert_image(fitz.Rect(*rect), filename=str(image_path), keep_proportion=True)
|
||||
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(
|
||||
@@ -1029,7 +1083,6 @@ class PdfDocument:
|
||||
def insert_blank_page(self, after_page_index: int | None = None) -> int:
|
||||
if not self._doc:
|
||||
raise RuntimeError("没有打开 PDF")
|
||||
self.snapshot()
|
||||
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
|
||||
@@ -1038,6 +1091,7 @@ class PdfDocument:
|
||||
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
|
||||
@@ -1045,10 +1099,12 @@ class PdfDocument:
|
||||
def insert_pdf(self, source_path: str | Path, after_page_index: int | None = None) -> int:
|
||||
if not self._doc:
|
||||
raise RuntimeError("没有打开 PDF")
|
||||
self.snapshot()
|
||||
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
|
||||
@@ -1164,18 +1220,23 @@ class PdfDocument:
|
||||
self._doc.set_metadata(metadata)
|
||||
self.mark_changed()
|
||||
|
||||
def annotations(self) -> list[AnnotationInfo]:
|
||||
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] = []
|
||||
for page_index in range(self.page_count):
|
||||
page = self._page(page_index)
|
||||
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=page_index,
|
||||
page_index=int(current_page_index),
|
||||
xref=annot.xref,
|
||||
annotation_type=annot.type[1],
|
||||
content=content,
|
||||
@@ -1183,6 +1244,7 @@ class PdfDocument:
|
||||
)
|
||||
)
|
||||
annot = annot.next
|
||||
self._remember_cache_item(self._annotation_cache, cache_key, list(items), max_items=96)
|
||||
return items
|
||||
|
||||
def annotation_at_point(
|
||||
@@ -1339,30 +1401,35 @@ class PdfDocument:
|
||||
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()
|
||||
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:
|
||||
try:
|
||||
page = self._page(page_index)
|
||||
annot = page.first_annot
|
||||
while annot and annot.xref != xref:
|
||||
annot = annot.next
|
||||
if not 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),
|
||||
)
|
||||
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,
|
||||
@@ -1380,6 +1447,7 @@ class PdfDocument:
|
||||
if not normalized_updates:
|
||||
return {}
|
||||
|
||||
checkpoint = self._mutation_checkpoint()
|
||||
self.snapshot()
|
||||
page = self._page(page_index)
|
||||
targets = []
|
||||
@@ -1391,30 +1459,34 @@ class PdfDocument:
|
||||
if not targets:
|
||||
return {}
|
||||
|
||||
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:
|
||||
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
|
||||
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
|
||||
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)
|
||||
@@ -1516,36 +1588,41 @@ class PdfDocument:
|
||||
if not rects:
|
||||
return None
|
||||
|
||||
checkpoint = self._mutation_checkpoint()
|
||||
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
|
||||
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),
|
||||
)
|
||||
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,
|
||||
@@ -1562,32 +1639,37 @@ class PdfDocument:
|
||||
if not annot or annot.type[1].lower() != "freetext":
|
||||
return None
|
||||
rect = self._rect_tuple(annot.rect)
|
||||
checkpoint = self._mutation_checkpoint()
|
||||
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
|
||||
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),
|
||||
)
|
||||
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,
|
||||
@@ -1767,6 +1849,8 @@ class PdfDocument:
|
||||
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()
|
||||
@@ -1859,21 +1943,37 @@ class PdfDocument:
|
||||
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)
|
||||
if self._doc:
|
||||
self._doc.close()
|
||||
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(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,
|
||||
@@ -1889,7 +1989,13 @@ class PdfDocument:
|
||||
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
|
||||
@@ -1897,16 +2003,85 @@ class PdfDocument:
|
||||
permissions |= fitz.PDF_PERM_COPY
|
||||
if allow_modify:
|
||||
permissions |= fitz.PDF_PERM_MODIFY
|
||||
self._doc.save(
|
||||
target,
|
||||
garbage=4,
|
||||
deflate=True,
|
||||
encryption=fitz.PDF_ENCRYPT_AES_256,
|
||||
owner_pw=password,
|
||||
user_pw=password,
|
||||
permissions=permissions,
|
||||
)
|
||||
self._dirty = False
|
||||
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:
|
||||
@@ -1948,10 +2123,24 @@ class PdfDocument:
|
||||
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)
|
||||
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)
|
||||
@@ -1962,22 +2151,26 @@ class PdfDocument:
|
||||
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))
|
||||
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._undo_stack.append(self._doc.tobytes(garbage=4, deflate=True))
|
||||
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:
|
||||
@@ -1985,9 +2178,78 @@ class PdfDocument:
|
||||
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(
|
||||
|
||||
Reference in New Issue
Block a user