Add encrypted PDF form and print support
This commit is contained in:
@@ -35,8 +35,13 @@ PDFReaderLite 是一个面向 Windows 的轻量 PDF 阅读与编辑工具,目
|
||||
- 图片合成为 PDF
|
||||
- 文档信息查看与编辑
|
||||
- 密码保护另存为
|
||||
- 打开加密 PDF
|
||||
- 移除密码另存为
|
||||
- 打印
|
||||
- 基础表单填写
|
||||
- 图片签名
|
||||
- 深色模式
|
||||
- 常用快捷键
|
||||
|
||||
## 本地开发
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ PDFReaderLite 是 Windows 平台的轻量 PDF 阅读与编辑工具。功能重
|
||||
|
||||
## V3:实用工具版
|
||||
|
||||
- 填写已有 PDF 表单
|
||||
- 填写已有 PDF 表单(已完成基础字段填写)
|
||||
- 基础文本框、复选框、单选按钮
|
||||
- 手写签名
|
||||
- 图片签名(已完成基础放置)
|
||||
@@ -53,9 +53,9 @@ PDFReaderLite 是 Windows 平台的轻量 PDF 阅读与编辑工具。功能重
|
||||
- 图片转 PDF(已完成)
|
||||
- 查看、修改文档信息(已完成)
|
||||
- 设置打开密码(已完成密码另存为)
|
||||
- 移除密码
|
||||
- 移除密码(已完成另存为无密码 PDF)
|
||||
- 基础权限设置
|
||||
- 打印
|
||||
- 打印(已完成)
|
||||
- 多标签页
|
||||
- 深色模式(已完成)
|
||||
|
||||
@@ -64,7 +64,7 @@ PDFReaderLite 是 Windows 平台的轻量 PDF 阅读与编辑工具。功能重
|
||||
- 大文件性能优化
|
||||
- 页面缓存
|
||||
- 后台渲染
|
||||
- 快捷键
|
||||
- 快捷键(已完成常用快捷键)
|
||||
- 配置保存
|
||||
- 异常恢复
|
||||
- PyInstaller 打包
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -3,8 +3,10 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QSettings, Qt
|
||||
from PySide6.QtGui import QAction, QIcon, QKeySequence
|
||||
from PySide6.QtGui import QAction, QIcon, QKeySequence, QPainter
|
||||
from PySide6.QtPrintSupport import QPrintDialog, QPrinter
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QFormLayout,
|
||||
@@ -23,7 +25,7 @@ from PySide6.QtWidgets import (
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
from pdfreaderlite.core.document import PdfDocument, SearchMatch
|
||||
from pdfreaderlite.core.document import EncryptedPdfError, FormField, PdfDocument, SearchMatch
|
||||
from pdfreaderlite.resources import software_icon_path
|
||||
from pdfreaderlite.ui.pdf_viewer import PdfViewer
|
||||
from pdfreaderlite.ui.sidebar import Sidebar
|
||||
@@ -66,6 +68,23 @@ class MainWindow(QMainWindow):
|
||||
self._remember_file(str(path))
|
||||
self._update_title()
|
||||
self._update_status()
|
||||
except EncryptedPdfError:
|
||||
password, ok = QInputDialog.getText(
|
||||
self,
|
||||
"输入密码",
|
||||
"该 PDF 需要打开密码:",
|
||||
QLineEdit.EchoMode.Password,
|
||||
)
|
||||
if ok and password:
|
||||
try:
|
||||
self.document.open(path, password)
|
||||
self.viewer.set_document(self.document)
|
||||
self.sidebar.load_document(self.document)
|
||||
self._remember_file(str(path))
|
||||
self._update_title()
|
||||
self._update_status()
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "打开失败", f"密码错误或无法打开 PDF:\n{exc}")
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "打开失败", f"无法打开 PDF:\n{exc}")
|
||||
|
||||
@@ -120,6 +139,53 @@ class MainWindow(QMainWindow):
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "保存失败", f"无法保存加密 PDF:\n{exc}")
|
||||
|
||||
def remove_password_file(self) -> None:
|
||||
if not self._ensure_document():
|
||||
return
|
||||
selected, _ = QFileDialog.getSaveFileName(
|
||||
self, "移除密码并另存为", self.document.title, "PDF 文件 (*.pdf)"
|
||||
)
|
||||
if not selected:
|
||||
return
|
||||
if not selected.lower().endswith(".pdf"):
|
||||
selected += ".pdf"
|
||||
try:
|
||||
self.document.save_as(selected)
|
||||
self.statusBar().showMessage("已另存为无密码 PDF", 3000)
|
||||
except Exception as exc:
|
||||
QMessageBox.critical(self, "移除失败", f"无法移除密码:\n{exc}")
|
||||
|
||||
def print_document(self) -> None:
|
||||
if not self._ensure_document():
|
||||
return
|
||||
printer = QPrinter(QPrinter.PrinterMode.HighResolution)
|
||||
printer.setDocName(self.document.title)
|
||||
dialog = QPrintDialog(printer, self)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
|
||||
painter = QPainter()
|
||||
if not painter.begin(printer):
|
||||
QMessageBox.critical(self, "打印失败", "无法启动打印任务。")
|
||||
return
|
||||
try:
|
||||
for page_index in range(self.document.page_count):
|
||||
if page_index > 0:
|
||||
printer.newPage()
|
||||
image = self.document.render_page(page_index, 2.0)
|
||||
page_rect = printer.pageRect(QPrinter.Unit.DevicePixel)
|
||||
scaled = image.scaled(
|
||||
page_rect.size().toSize(),
|
||||
Qt.AspectRatioMode.KeepAspectRatio,
|
||||
Qt.TransformationMode.SmoothTransformation,
|
||||
)
|
||||
x = int(page_rect.x() + (page_rect.width() - scaled.width()) / 2)
|
||||
y = int(page_rect.y() + (page_rect.height() - scaled.height()) / 2)
|
||||
painter.drawImage(x, y, scaled)
|
||||
finally:
|
||||
painter.end()
|
||||
self.statusBar().showMessage("打印任务已发送", 3000)
|
||||
|
||||
def rotate_page(self) -> None:
|
||||
if not self._ensure_document():
|
||||
return
|
||||
@@ -316,6 +382,46 @@ class MainWindow(QMainWindow):
|
||||
)
|
||||
self.statusBar().showMessage("文档信息已更新,记得保存", 3000)
|
||||
|
||||
def fill_form_field(self) -> None:
|
||||
if not self._ensure_document():
|
||||
return
|
||||
fields = self.document.form_fields()
|
||||
if not fields:
|
||||
QMessageBox.information(self, "表单", "当前 PDF 没有可填写的表单字段。")
|
||||
return
|
||||
|
||||
dialog = QDialog(self)
|
||||
dialog.setWindowTitle("填写表单")
|
||||
layout = QFormLayout(dialog)
|
||||
field_combo = QComboBox()
|
||||
value_edit = QLineEdit()
|
||||
for field in fields:
|
||||
label = f"{field.name}(第 {field.page_index + 1} 页,{field.field_type})"
|
||||
field_combo.addItem(label, field)
|
||||
layout.addRow("字段", field_combo)
|
||||
layout.addRow("值", value_edit)
|
||||
|
||||
def load_field(index: int) -> None:
|
||||
field: FormField = field_combo.itemData(index)
|
||||
value_edit.setText(field.value)
|
||||
|
||||
field_combo.currentIndexChanged.connect(load_field)
|
||||
load_field(0)
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
buttons.accepted.connect(dialog.accept)
|
||||
buttons.rejected.connect(dialog.reject)
|
||||
layout.addRow(buttons)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
selected_field: FormField = field_combo.currentData()
|
||||
if self.document.update_form_field(selected_field.name, value_edit.text()):
|
||||
self.viewer.render()
|
||||
self.statusBar().showMessage("表单字段已更新,记得保存", 3000)
|
||||
else:
|
||||
QMessageBox.warning(self, "填写失败", "没有找到对应的表单字段。")
|
||||
|
||||
def go_to_page_dialog(self) -> None:
|
||||
if not self._ensure_document():
|
||||
return
|
||||
@@ -384,14 +490,22 @@ class MainWindow(QMainWindow):
|
||||
self.save_as_action = QAction("另存为", self)
|
||||
self.save_as_action.setShortcut(QKeySequence.StandardKey.SaveAs)
|
||||
self.save_encrypted_action = QAction("密码另存为", self)
|
||||
self.remove_password_action = QAction("移除密码另存为", self)
|
||||
self.print_action = QAction("打印", self)
|
||||
self.print_action.setShortcut(QKeySequence.StandardKey.Print)
|
||||
|
||||
self.previous_action = QAction("上一页", self)
|
||||
self.previous_action.setShortcut(QKeySequence(Qt.Key.Key_PageUp))
|
||||
self.next_action = QAction("下一页", self)
|
||||
self.next_action.setShortcut(QKeySequence(Qt.Key.Key_PageDown))
|
||||
self.zoom_out_action = QAction("缩小", self)
|
||||
self.zoom_out_action.setShortcut(QKeySequence.StandardKey.ZoomOut)
|
||||
self.zoom_in_action = QAction("放大", self)
|
||||
self.zoom_in_action.setShortcut(QKeySequence.StandardKey.ZoomIn)
|
||||
self.fit_width_action = QAction("适应宽度", self)
|
||||
self.fit_page_action = QAction("适应页面", self)
|
||||
self.go_to_page_action = QAction("跳转", self)
|
||||
self.go_to_page_action.setShortcut(QKeySequence("Ctrl+G"))
|
||||
self.rotate_action = QAction("旋转", self)
|
||||
self.delete_action = QAction("删除页", self)
|
||||
self.insert_blank_action = QAction("插入空白页", self)
|
||||
@@ -403,7 +517,10 @@ class MainWindow(QMainWindow):
|
||||
self.export_pages_images_action = QAction("批量导出图片", self)
|
||||
self.images_to_pdf_action = QAction("图片转 PDF", self)
|
||||
self.metadata_action = QAction("文档信息", self)
|
||||
self.metadata_action.setShortcut(QKeySequence("Ctrl+I"))
|
||||
self.form_fill_action = QAction("填写表单", self)
|
||||
self.highlight_action = QAction("高亮", self)
|
||||
self.highlight_action.setShortcut(QKeySequence("Ctrl+H"))
|
||||
self.underline_action = QAction("下划线", self)
|
||||
self.strikeout_action = QAction("删除线", self)
|
||||
self.note_action = QAction("批注", self)
|
||||
@@ -424,6 +541,8 @@ class MainWindow(QMainWindow):
|
||||
file_menu.addAction(self.save_action)
|
||||
file_menu.addAction(self.save_as_action)
|
||||
file_menu.addAction(self.save_encrypted_action)
|
||||
file_menu.addAction(self.remove_password_action)
|
||||
file_menu.addAction(self.print_action)
|
||||
self.recent_menu = file_menu.addMenu("最近打开")
|
||||
self._refresh_recent_menu()
|
||||
|
||||
@@ -451,6 +570,7 @@ class MainWindow(QMainWindow):
|
||||
tools_menu.addAction(self.export_pages_images_action)
|
||||
tools_menu.addAction(self.images_to_pdf_action)
|
||||
tools_menu.addAction(self.metadata_action)
|
||||
tools_menu.addAction(self.form_fill_action)
|
||||
|
||||
edit_menu = self.menuBar().addMenu("编辑")
|
||||
edit_menu.addAction(self.highlight_action)
|
||||
@@ -476,6 +596,7 @@ class MainWindow(QMainWindow):
|
||||
self.open_action,
|
||||
self.save_action,
|
||||
self.save_as_action,
|
||||
self.print_action,
|
||||
self.export_current_image_action,
|
||||
self.previous_action,
|
||||
self.next_action,
|
||||
@@ -505,6 +626,8 @@ class MainWindow(QMainWindow):
|
||||
self.save_action.triggered.connect(self.save_file)
|
||||
self.save_as_action.triggered.connect(self.save_as_file)
|
||||
self.save_encrypted_action.triggered.connect(self.save_encrypted_file)
|
||||
self.remove_password_action.triggered.connect(self.remove_password_file)
|
||||
self.print_action.triggered.connect(self.print_document)
|
||||
self.previous_action.triggered.connect(self.viewer.previous_page)
|
||||
self.next_action.triggered.connect(self.viewer.next_page)
|
||||
self.zoom_out_action.triggered.connect(self.viewer.zoom_out)
|
||||
@@ -523,6 +646,7 @@ class MainWindow(QMainWindow):
|
||||
self.export_pages_images_action.triggered.connect(self.export_pages_images)
|
||||
self.images_to_pdf_action.triggered.connect(self.images_to_pdf)
|
||||
self.metadata_action.triggered.connect(self.edit_metadata)
|
||||
self.form_fill_action.triggered.connect(self.fill_form_field)
|
||||
self.highlight_action.triggered.connect(self.highlight_current_page)
|
||||
self.underline_action.triggered.connect(self.underline_current_page)
|
||||
self.strikeout_action.triggered.connect(self.strikeout_current_page)
|
||||
|
||||
@@ -24,6 +24,21 @@ def create_pdf(path: Path, text: str = "PDFReaderLite feature test") -> None:
|
||||
doc.close()
|
||||
|
||||
|
||||
def create_form_pdf(path: Path) -> None:
|
||||
doc = fitz.open()
|
||||
try:
|
||||
page = doc.new_page()
|
||||
widget = fitz.Widget()
|
||||
widget.field_name = "name"
|
||||
widget.field_type = fitz.PDF_WIDGET_TYPE_TEXT
|
||||
widget.rect = fitz.Rect(72, 72, 260, 96)
|
||||
widget.field_value = ""
|
||||
page.add_widget(widget)
|
||||
doc.save(path)
|
||||
finally:
|
||||
doc.close()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
temp_dir = Path(tempfile.mkdtemp(prefix="pdfreaderlite_"))
|
||||
try:
|
||||
@@ -34,12 +49,15 @@ def main() -> int:
|
||||
merged_pdf = temp_dir / "merged.pdf"
|
||||
image_pdf = temp_dir / "image.pdf"
|
||||
encrypted_pdf = temp_dir / "encrypted.pdf"
|
||||
decrypted_pdf = temp_dir / "decrypted.pdf"
|
||||
form_pdf = temp_dir / "form.pdf"
|
||||
exported_image = temp_dir / "page.png"
|
||||
split_folder = temp_dir / "split"
|
||||
image_export_folder = temp_dir / "images"
|
||||
|
||||
create_pdf(source_pdf)
|
||||
create_pdf(insert_pdf, "inserted page")
|
||||
create_form_pdf(form_pdf)
|
||||
Image.new("RGB", (80, 60), (80, 130, 220)).save(image_path)
|
||||
|
||||
document = PdfDocument()
|
||||
@@ -76,10 +94,24 @@ def main() -> int:
|
||||
document.save()
|
||||
document.close()
|
||||
|
||||
encrypted_document = PdfDocument()
|
||||
encrypted_document.open(encrypted_pdf, "123456")
|
||||
encrypted_document.save_as(decrypted_pdf)
|
||||
encrypted_document.close()
|
||||
|
||||
form_document = PdfDocument()
|
||||
form_document.open(form_pdf)
|
||||
fields = form_document.form_fields()
|
||||
assert fields and fields[0].name == "name"
|
||||
assert form_document.update_form_field("name", "PDFReaderLite")
|
||||
form_document.save()
|
||||
form_document.close()
|
||||
|
||||
assert extracted_pdf.exists()
|
||||
assert merged_pdf.exists()
|
||||
assert image_pdf.exists()
|
||||
assert encrypted_pdf.exists()
|
||||
assert decrypted_pdf.exists()
|
||||
assert exported_image.exists()
|
||||
assert len(list(split_folder.glob("*.pdf"))) == 3
|
||||
assert len(list(image_export_folder.glob("*.png"))) == 2
|
||||
|
||||
Reference in New Issue
Block a user