Add encrypted PDF form and print support
This commit is contained in:
@@ -14,6 +14,18 @@ class SearchMatch:
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FormField:
|
||||
page_index: int
|
||||
name: str
|
||||
field_type: str
|
||||
value: str
|
||||
|
||||
|
||||
class EncryptedPdfError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class PdfDocument:
|
||||
def __init__(self) -> None:
|
||||
self.path: Path | None = None
|
||||
@@ -33,13 +45,14 @@ class PdfDocument:
|
||||
return "未打开文档"
|
||||
return self.path.name
|
||||
|
||||
def open(self, path: str | Path) -> None:
|
||||
def open(self, path: str | Path, password: str | None = None) -> None:
|
||||
self.close()
|
||||
self.path = Path(path)
|
||||
self._doc = fitz.open(self.path)
|
||||
if self._doc.needs_pass:
|
||||
self.close()
|
||||
raise RuntimeError("该 PDF 需要密码,当前版本暂不支持打开加密 PDF。")
|
||||
if not password or not self._doc.authenticate(password):
|
||||
self.close()
|
||||
raise EncryptedPdfError("该 PDF 需要密码。")
|
||||
|
||||
def close(self) -> None:
|
||||
if self._doc:
|
||||
@@ -316,6 +329,38 @@ class PdfDocument:
|
||||
)
|
||||
self._doc.set_metadata(metadata)
|
||||
|
||||
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:
|
||||
widget.field_value = value
|
||||
widget.update()
|
||||
return True
|
||||
return False
|
||||
|
||||
def delete_page(self, page_index: int) -> None:
|
||||
if not self._doc:
|
||||
raise RuntimeError("没有打开 PDF")
|
||||
|
||||
Reference in New Issue
Block a user