Files
shen 8dae91c2ca fix: protect editor content and harden document exports
Protect pending edits on window close, keep save-as paths and drafts consistent,
copy relative image resources, reject oversized table imports without truncation,
and preserve independent preview scrolling during refresh.

Archive rendered MHTML resources with portable references and embedded local
fonts. Preserve existing outputs on export cancellation or failure. Convert
editor match positions and filter directory results in linear passes.

Include the previously completed editor image/table/history improvements,
undoable replacement, export snapshots, shared page settings, and cancellable
PDF/Word export workflow. Update documentation and version to 0.3.1.

Validation: 142 pytest cases passed; GUI smoke, improvements integration, and
offline MHTML/scroll reliability smoke checks passed.
2026-10-29 18:22:42 +08:00

341 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import html
import re
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path
from PySide6.QtCore import QMarginsF
from PySide6.QtGui import QPageLayout, QPageSize
from PySide6.QtWidgets import (
QDialog,
QCheckBox,
QComboBox,
QDialogButtonBox,
QDoubleSpinBox,
QFormLayout,
QLabel,
QLineEdit,
QSpinBox,
QVBoxLayout,
QWidget,
)
from .markdown_utils import Heading
from .export_settings import PageSettings
PDF_BODY_MARKER = "MDHELPER_PDF_BODY_START_7A61"
PDF_HEADING_MARKER_PREFIX = "MDHELPER_PDF_HEADING_"
@dataclass(frozen=True)
class PdfMargins:
top: float = 15.0
bottom: float = 15.0
left: float = 15.0
right: float = 15.0
def build_pdf_page_layout(margins: PdfMargins | PageSettings | None = None) -> QPageLayout:
selected = margins or PdfMargins()
return QPageLayout(
QPageSize(getattr(QPageSize.PageSizeId, getattr(selected, "paper", "A4"))),
QPageLayout.Orientation.Landscape if getattr(selected, "landscape", False) else QPageLayout.Orientation.Portrait,
QMarginsF(selected.left, selected.top, selected.right, selected.bottom),
QPageLayout.Unit.Millimeter,
)
class PdfExportSettingsDialog(QDialog):
def __init__(self, margins: PdfMargins | PageSettings, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setWindowTitle("导出页面设置(PDF / Word)")
self.setModal(True)
self.setMinimumWidth(480)
note = QLabel("PDF 与 Word 共用这些设置。Word 目录页码由 Word 更新域后生成。\n启用页眉或页脚时,相应页边距至少为 12 mm,以免遮挡正文。")
note.setWordWrap(True)
self.top_spin = self._margin_spin(margins.top)
self.bottom_spin = self._margin_spin(margins.bottom)
self.left_spin = self._margin_spin(margins.left)
self.right_spin = self._margin_spin(margins.right)
form = QFormLayout()
defaults = margins if isinstance(margins, PageSettings) else PageSettings()
self.paper_combo = QComboBox(); self.paper_combo.addItems(["A4", "A3", "Letter"])
self.paper_combo.setCurrentText(defaults.paper)
self.landscape_check = QCheckBox("横向"); self.landscape_check.setChecked(defaults.landscape)
self.toc_check = QCheckBox("在正文前生成目录"); self.toc_check.setChecked(defaults.include_toc)
self.depth_spin = QSpinBox(); self.depth_spin.setRange(1, 6); self.depth_spin.setValue(defaults.toc_depth)
self.depth_spin.setEnabled(defaults.include_toc); self.toc_check.toggled.connect(self.depth_spin.setEnabled)
self.header_edit = QLineEdit(defaults.header); self.header_edit.setMaxLength(100)
self.footer_edit = QLineEdit(defaults.footer); self.footer_edit.setMaxLength(100)
self.numbers_check = QCheckBox("显示页码和总页数"); self.numbers_check.setChecked(defaults.page_numbers)
form.addRow("纸张", self.paper_combo); form.addRow("方向", self.landscape_check)
form.addRow("上边距", self.top_spin)
form.addRow("下边距", self.bottom_spin)
form.addRow("左边距", self.left_spin)
form.addRow("右边距", self.right_spin)
form.addRow("目录", self.toc_check); form.addRow("目录层级", self.depth_spin)
form.addRow("页眉", self.header_edit); form.addRow("页脚", self.footer_edit)
form.addRow("页码", self.numbers_check)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout = QVBoxLayout(self)
layout.addWidget(note)
layout.addLayout(form)
layout.addWidget(buttons)
def margins(self) -> PdfMargins:
return PdfMargins(
top=float(self.top_spin.value()),
bottom=float(self.bottom_spin.value()),
left=float(self.left_spin.value()),
right=float(self.right_spin.value()),
)
def page_settings(self) -> PageSettings:
margins = self.margins()
return PageSettings(paper=self.paper_combo.currentText(), landscape=self.landscape_check.isChecked(),
top=margins.top, bottom=margins.bottom, left=margins.left, right=margins.right,
include_toc=self.toc_check.isChecked(), toc_depth=self.depth_spin.value(),
header=self.header_edit.text(), footer=self.footer_edit.text(),
page_numbers=self.numbers_check.isChecked()).normalized()
def _margin_spin(self, value: float) -> QDoubleSpinBox:
spin = QDoubleSpinBox()
spin.setRange(0.0, 50.0)
spin.setDecimals(1)
spin.setSingleStep(1.0)
spin.setSuffix(" mm")
spin.setValue(value)
return spin
def build_pdf_export_html(
html_document: str,
headings: list[Heading],
page_numbers: dict[int, int] | None = None,
*,
include_page_markers: bool = True,
settings: PageSettings | None = None,
) -> str:
selected = settings or PageSettings()
# Export uses light paper independently of the application's reading theme.
html_document = html_document.replace('data-theme="dark"', 'data-theme="light"', 1)
printable_headings = [heading for heading in headings if heading.level <= selected.toc_depth] if selected.include_toc else []
marked_document = _insert_heading_markers(html_document, printable_headings) if include_page_markers else html_document
toc_html = _toc_html(printable_headings, page_numbers or {}) if selected.include_toc else ""
print_css = _print_css(len(printable_headings))
usable_height = max(20, selected.size_mm()[1] - selected.top - selected.bottom - 2)
print_css += f"\n@media print {{ html {{ color-scheme: light !important; }} .reader img {{ max-height: {usable_height:g}mm; object-fit: contain; }} }}\n"
marked_document = marked_document.replace("</style>", f"{print_css}\n </style>", 1)
body_class = ' class="pdf-export"'
marked_document = marked_document.replace("<body>", f"<body{body_class}>", 1)
body_marker = f'<div class="pdf-body-start-marker">{PDF_BODY_MARKER}</div>\n' if include_page_markers else ""
export_front_matter = f"\n{toc_html}\n{body_marker}"
return marked_document.replace(f"<body{body_class}>", f"<body{body_class}>{export_front_matter}", 1)
def extract_heading_page_numbers(pdf_data: bytes, heading_count: int) -> dict[int, int]:
from pypdf import PdfReader
reader = PdfReader(BytesIO(pdf_data))
page_texts = [(page.extract_text() or "") for page in reader.pages]
normalized_page_texts = [_normalized_marker_text(text) for text in page_texts]
normalized_body_marker = _normalized_marker_text(PDF_BODY_MARKER)
body_page_index = next(
(index for index, text in enumerate(normalized_page_texts) if normalized_body_marker in text),
None,
)
if body_page_index is None:
raise ValueError("无法在预打印 PDF 中定位正文起始页。")
page_numbers: dict[int, int] = {}
for heading_index in range(heading_count):
marker = _normalized_marker_text(f"{PDF_HEADING_MARKER_PREFIX}{heading_index:04d}")
page_index = next(
(index for index in range(body_page_index, len(normalized_page_texts)) if marker in normalized_page_texts[index]),
None,
)
if page_index is not None:
page_numbers[heading_index] = page_index + 1
if heading_count and len(page_numbers) != heading_count:
missing = sorted(set(range(heading_count)) - set(page_numbers))
raise ValueError(f"无法识别全部目录页码,缺少标题索引:{missing}")
return page_numbers
def _normalized_marker_text(value: str) -> str:
return re.sub(r"[^A-Z0-9]", "", value.upper())
def _insert_heading_markers(html_document: str, headings: list[Heading]) -> str:
marked = html_document
search_from = 0
for index, heading in enumerate(headings):
escaped_slug = html.escape(heading.slug, quote=True)
positions = [
position
for needle in (f'id="{escaped_slug}"', f"id='{escaped_slug}'")
if (position := marked.find(needle, search_from)) >= 0
]
if not positions:
continue
attribute_position = min(positions)
tag_end = marked.find(">", attribute_position)
if tag_end < 0:
continue
marker = (
'<span class="pdf-heading-marker">'
f"{PDF_HEADING_MARKER_PREFIX}{index:04d}"
"</span>"
)
marked = f"{marked[:tag_end + 1]}{marker}{marked[tag_end + 1:]}"
search_from = tag_end + len(marker) + 1
return marked
def _toc_html(headings: list[Heading], page_numbers: dict[int, int]) -> str:
density_class = " pdf-toc--dense" if len(headings) > 28 else ""
if len(headings) > 70:
density_class += " pdf-toc--very-dense"
rows = []
for index, heading in enumerate(headings):
title = html.escape(heading.title)
slug = html.escape(heading.slug, quote=True)
page_number = str(page_numbers.get(index, "--"))
rows.append(
f'<li class="pdf-toc__item pdf-toc__item--level-{heading.level}">'
f'<a href="#{slug}"><span class="pdf-toc__text">{title}</span>'
'<span class="pdf-toc__dots"></span>'
f'<span class="pdf-toc__page">{page_number}</span></a></li>'
)
items = "\n".join(rows) or '<li class="pdf-toc__empty">本文档没有可用的章节标题。</li>'
return (
f'<section class="pdf-toc{density_class}">'
'<h1>目录</h1>'
f'<ol class="pdf-toc__list">{items}</ol>'
"</section>"
)
def _print_css(heading_count: int) -> str:
column_count = 2 if heading_count > 28 else 1
return f"""
@media print {{
html,
body,
.reader-shell,
.reader {{
background: #ffffff !important;
background-image: none !important;
}}
html,
body {{
margin: 0 !important;
padding: 0 !important;
}}
.reader-shell {{
display: block !important;
width: 100% !important;
min-height: 0 !important;
padding: 0 !important;
}}
.reader {{
box-sizing: border-box !important;
width: 100% !important;
max-width: none !important;
min-height: 0 !important;
margin: 0 !important;
padding: 0 !important;
border: 0 !important;
box-shadow: none !important;
}}
.image-lightbox {{
display: none !important;
}}
.pdf-toc {{
display: block !important;
box-sizing: border-box;
width: 100%;
min-height: 100%;
color: #111827;
background: #ffffff !important;
break-after: page;
page-break-after: always;
}}
.pdf-toc h1 {{
margin: 0 0 10mm;
padding: 0 0 4mm;
border-bottom: 1px solid #cbd5e1;
color: #111827;
font-size: 24pt;
line-height: 1.2;
}}
.pdf-toc__list {{
column-count: {column_count};
column-gap: 10mm;
margin: 0;
padding: 0;
list-style: none;
}}
.pdf-toc__item {{
margin: 0 0 3.2mm;
break-inside: avoid;
page-break-inside: avoid;
font-size: 10.5pt;
line-height: 1.35;
}}
.pdf-toc--dense .pdf-toc__item {{
margin-bottom: 2.2mm;
font-size: 9.5pt;
}}
.pdf-toc--very-dense .pdf-toc__item {{
margin-bottom: 1.4mm;
font-size: 8.5pt;
}}
.pdf-toc__item a {{
display: flex;
align-items: baseline;
color: inherit !important;
text-decoration: none !important;
}}
.pdf-toc__item--level-2 {{ padding-left: 5mm; }}
.pdf-toc__item--level-3 {{ padding-left: 10mm; }}
.pdf-toc__item--level-4 {{ padding-left: 15mm; }}
.pdf-toc__item--level-5 {{ padding-left: 20mm; }}
.pdf-toc__item--level-6 {{ padding-left: 25mm; }}
.pdf-toc__text {{ max-width: 78%; }}
.pdf-toc__dots {{
min-width: 8mm;
margin: 0 2mm;
flex: 1;
border-bottom: 1px dotted #94a3b8;
}}
.pdf-toc__page {{
min-width: 8mm;
font-variant-numeric: tabular-nums;
text-align: right;
}}
.pdf-body-start-marker,
.pdf-heading-marker {{
color: #ffffff !important;
font-size: 1px !important;
line-height: 1px !important;
}}
.pdf-body-start-marker {{
height: 1px;
overflow: hidden;
}}
}}
"""