304 lines
9.7 KiB
Python
304 lines
9.7 KiB
Python
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,
|
|
QDialogButtonBox,
|
|
QDoubleSpinBox,
|
|
QFormLayout,
|
|
QLabel,
|
|
QVBoxLayout,
|
|
QWidget,
|
|
)
|
|
|
|
from .markdown_utils import Heading
|
|
|
|
|
|
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 | None = None) -> QPageLayout:
|
|
selected = margins or PdfMargins()
|
|
return QPageLayout(
|
|
QPageSize(QPageSize.PageSizeId.A4),
|
|
QPageLayout.Orientation.Portrait,
|
|
QMarginsF(selected.left, selected.top, selected.right, selected.bottom),
|
|
QPageLayout.Unit.Millimeter,
|
|
)
|
|
|
|
|
|
class PdfExportSettingsDialog(QDialog):
|
|
def __init__(self, margins: PdfMargins, parent: QWidget | None = None) -> None:
|
|
super().__init__(parent)
|
|
self.setWindowTitle("PDF 导出设置")
|
|
self.setModal(True)
|
|
|
|
note = QLabel("纸张:A4;导出背景:白色;正文前自动生成带页码目录。")
|
|
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()
|
|
form.addRow("上边距", self.top_spin)
|
|
form.addRow("下边距", self.bottom_spin)
|
|
form.addRow("左边距", self.left_spin)
|
|
form.addRow("右边距", self.right_spin)
|
|
|
|
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 _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,
|
|
) -> str:
|
|
printable_headings = [heading for heading in headings if heading.level <= 3]
|
|
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 {})
|
|
print_css = _print_css(len(printable_headings))
|
|
|
|
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__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;
|
|
}}
|
|
}}
|
|
"""
|