Files
MDHelper/mdhelper/docx_exporter.py
T

461 lines
19 KiB
Python
Raw 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 shutil
import subprocess
import sys
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path
from xml.sax.saxutils import escape
from markdown_it import MarkdownIt
from markdown_it.token import Token
WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
DOCX_EXPORT_ENGINES = {
"pandoc": "Pandoc(推荐,保真度较高)",
"python-docx": "python-docx(纯 Python)",
"builtin": "内置基础导出",
}
class DocxExportError(RuntimeError):
pass
def resolve_pandoc_executable() -> Path | None:
"""Locate the bundled Pandoc first, with PATH as a development fallback."""
roots: list[Path] = []
bundled_root = getattr(sys, "_MEIPASS", None)
if bundled_root:
roots.append(Path(bundled_root))
roots.append(Path(__file__).resolve().parent.parent)
executable_name = "pandoc.exe" if sys.platform == "win32" else "pandoc"
for root in roots:
candidate = root / "vendor" / "pandoc" / executable_name
if candidate.is_file():
return candidate
path_executable = shutil.which("pandoc")
return Path(path_executable) if path_executable else None
def export_markdown_to_docx(
source: str,
output_path: Path,
engine: str = "builtin",
source_path: Path | None = None,
) -> Path:
if engine == "pandoc":
return export_markdown_to_docx_pandoc(source, output_path, source_path=source_path)
if engine == "python-docx":
return export_markdown_to_docx_python_docx(source, output_path)
return export_markdown_to_docx_builtin(source, output_path)
def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path:
if output_path.suffix.lower() != ".docx":
output_path = output_path.with_suffix(".docx")
blocks = _markdown_blocks(source)
document_xml = _document_xml(blocks)
output_path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(output_path, "w", compression=zipfile.ZIP_DEFLATED) as package:
package.writestr("[Content_Types].xml", CONTENT_TYPES_XML)
package.writestr("_rels/.rels", PACKAGE_RELS_XML)
package.writestr("word/document.xml", document_xml)
package.writestr("word/styles.xml", STYLES_XML)
package.writestr("word/settings.xml", SETTINGS_XML)
return output_path
def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None) -> Path:
if output_path.suffix.lower() != ".docx":
output_path = output_path.with_suffix(".docx")
output_path.parent.mkdir(parents=True, exist_ok=True)
pandoc_path = resolve_pandoc_executable()
if pandoc_path is None:
raise DocxExportError("未找到程序内置的 Pandoc,当前 MDHelper 安装包可能不完整,请重新获取完整版本。")
temporary_path: Path | None = None
input_path = source_path if source_path is not None and source_path.exists() else None
if input_path is None:
with tempfile.NamedTemporaryFile("w", suffix=".md", encoding="utf-8", delete=False) as handle:
handle.write(source)
temporary_path = Path(handle.name)
input_path = temporary_path
command = [str(pandoc_path), str(input_path), "-o", str(output_path), "--standalone"]
run_options: dict[str, object] = {}
if sys.platform == "win32":
run_options["creationflags"] = subprocess.CREATE_NO_WINDOW
try:
result = subprocess.run(
command,
cwd=str(input_path.parent),
capture_output=True,
text=True,
timeout=120,
check=False,
**run_options,
)
except FileNotFoundError as exc:
raise DocxExportError("程序内置的 Pandoc 无法启动,当前 MDHelper 安装包可能不完整。") from exc
except subprocess.TimeoutExpired as exc:
raise DocxExportError("pandoc 导出超时。") from exc
finally:
if temporary_path is not None:
try:
temporary_path.unlink(missing_ok=True)
except OSError:
pass
if result.returncode != 0:
detail = (result.stderr or result.stdout or "pandoc 返回错误。").strip()
raise DocxExportError(detail)
return output_path
def export_markdown_to_docx_python_docx(source: str, output_path: Path) -> Path:
if output_path.suffix.lower() != ".docx":
output_path = output_path.with_suffix(".docx")
try:
from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt
except ImportError as exc:
raise DocxExportError("未找到 python-docx,请先安装 python-docx。") from exc
document = Document()
normal = document.styles["Normal"]
normal.font.name = "Microsoft YaHei"
normal.font.size = Pt(11)
normal.element.rPr.rFonts.set(qn("w:eastAsia"), "Microsoft YaHei")
for block in _markdown_blocks(source):
if isinstance(block, TableBlock):
_add_python_docx_table(document, block)
continue
_add_python_docx_paragraph(document, block)
output_path.parent.mkdir(parents=True, exist_ok=True)
document.save(str(output_path))
return output_path
def _markdown_blocks(source: str) -> list[ParagraphBlock | TableBlock]:
markdown = MarkdownIt("commonmark", {"html": True}).enable(["table", "strikethrough"])
return _DocxBuilder(markdown.parse(source)).build()
def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None:
style = f"Heading {block.style.removeprefix('Heading')}" if block.style.startswith("Heading") else None
if block.list_kind == "bullet":
style = "List Bullet"
elif block.list_kind == "number":
style = "List Number"
elif block.style == "Code":
style = None
paragraph = document.add_paragraph(style=style)
if block.quote_depth:
paragraph.paragraph_format.left_indent = _docx_inches(0.35)
for text, run_style in block.runs:
parts = text.split("\n")
for part_index, part in enumerate(parts):
if part_index:
paragraph.add_run().add_break()
run = paragraph.add_run(part)
run.bold = bool(run_style.get("bold"))
run.italic = bool(run_style.get("italic"))
if run_style.get("code") or block.style == "Code":
run.font.name = "Consolas"
run.font.size = _docx_pt(10)
def _add_python_docx_table(document: object, block: TableBlock) -> None:
if not block.rows:
return
column_count = max(len(row) for row in block.rows)
table = document.add_table(rows=len(block.rows), cols=column_count)
table.style = "Table Grid"
for row_index, row in enumerate(block.rows):
for col_index in range(column_count):
cell = table.cell(row_index, col_index)
runs = row[col_index] if col_index < len(row) else [("", {})]
paragraph = cell.paragraphs[0]
for text, run_style in runs:
run = paragraph.add_run(text)
run.bold = bool(run_style.get("bold") or row_index == 0)
run.italic = bool(run_style.get("italic"))
if run_style.get("code"):
run.font.name = "Consolas"
run.font.size = _docx_pt(10)
def _docx_pt(value: int) -> object:
from docx.shared import Pt
return Pt(value)
def _docx_inches(value: float) -> object:
from docx.shared import Inches
return Inches(value)
@dataclass
class ParagraphBlock:
runs: list[tuple[str, dict[str, bool]]]
style: str = "Normal"
list_kind: str = ""
quote_depth: int = 0
@dataclass
class TableBlock:
rows: list[list[list[tuple[str, dict[str, bool]]]]]
class _DocxBuilder:
def __init__(self, tokens: list[Token]) -> None:
self.tokens = tokens
self.blocks: list[ParagraphBlock | TableBlock] = []
self.index = 0
self.list_stack: list[str] = []
self.quote_depth = 0
def build(self) -> list[ParagraphBlock | TableBlock]:
while self.index < len(self.tokens):
token = self.tokens[self.index]
if token.type == "heading_open":
level = min(max(int(token.tag[1:]), 1), 6) if token.tag.startswith("h") else 1
self._add_next_inline(f"Heading{level}")
continue
if token.type == "paragraph_open":
style = "Quote" if self.quote_depth else "Normal"
self._add_next_inline(style, list_kind=self.list_stack[-1] if self.list_stack else "")
continue
if token.type in {"fence", "code_block"}:
for line in token.content.rstrip("\n").splitlines() or [""]:
self.blocks.append(ParagraphBlock([(line, {"code": True})], style="Code"))
elif token.type == "blockquote_open":
self.quote_depth += 1
elif token.type == "blockquote_close":
self.quote_depth = max(0, self.quote_depth - 1)
elif token.type == "bullet_list_open":
self.list_stack.append("bullet")
elif token.type == "ordered_list_open":
self.list_stack.append("number")
elif token.type in {"bullet_list_close", "ordered_list_close"} and self.list_stack:
self.list_stack.pop()
elif token.type == "table_open":
self.blocks.append(self._collect_table())
continue
elif token.type == "hr":
self.blocks.append(ParagraphBlock([("_" * 30, {})]))
self.index += 1
return self.blocks
def _add_next_inline(self, style: str, list_kind: str = "") -> None:
inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None
runs = _inline_runs(inline.children if inline is not None else None)
self.blocks.append(ParagraphBlock(runs, style=style, list_kind=list_kind, quote_depth=self.quote_depth))
self.index += 3
def _collect_table(self) -> TableBlock:
rows: list[list[list[tuple[str, dict[str, bool]]]]] = []
current_row: list[list[tuple[str, dict[str, bool]]]] | None = None
while self.index < len(self.tokens):
token = self.tokens[self.index]
if token.type == "tr_open":
current_row = []
elif token.type == "tr_close" and current_row is not None:
rows.append(current_row)
current_row = None
elif token.type in {"th_open", "td_open"} and current_row is not None:
inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None
cell_runs = _inline_runs(inline.children if inline is not None else None)
current_row.append(cell_runs)
elif token.type == "table_close":
self.index += 1
break
self.index += 1
return TableBlock(rows)
def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, bool]]]:
if not children:
return [("", {})]
runs: list[tuple[str, dict[str, bool]]] = []
style_stack: list[str] = []
for child in children:
if child.type == "strong_open":
style_stack.append("bold")
elif child.type == "strong_close":
_pop_style(style_stack, "bold")
elif child.type == "em_open":
style_stack.append("italic")
elif child.type == "em_close":
_pop_style(style_stack, "italic")
elif child.type == "code_inline":
runs.append((child.content, {"code": True}))
elif child.type in {"text", "html_inline"}:
text = html.unescape(child.content) if child.type == "html_inline" else child.content
runs.append((text, {"bold": "bold" in style_stack, "italic": "italic" in style_stack}))
elif child.type in {"softbreak", "hardbreak"}:
runs.append(("\n", {}))
elif child.children:
runs.extend(_inline_runs(child.children))
return runs or [("", {})]
def _pop_style(style_stack: list[str], value: str) -> None:
for index in range(len(style_stack) - 1, -1, -1):
if style_stack[index] == value:
del style_stack[index]
return
def _document_xml(blocks: list[ParagraphBlock | TableBlock]) -> str:
body = "\n".join(_block_xml(block) for block in blocks)
return f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="{WP_NS}">
<w:body>
{body}
<w:sectPr>
<w:pgSz w:w="11906" w:h="16838"/>
<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>
</w:sectPr>
</w:body>
</w:document>
"""
def _block_xml(block: ParagraphBlock | TableBlock) -> str:
if isinstance(block, TableBlock):
return _table_xml(block)
return _paragraph_xml(block)
def _paragraph_xml(block: ParagraphBlock) -> str:
props = [f'<w:pStyle w:val="{block.style}"/>'] if block.style != "Normal" else []
if block.list_kind:
bullet = "•" if block.list_kind == "bullet" else "1."
block = ParagraphBlock([(bullet + " ", {"bold": True}), *block.runs], style=block.style, quote_depth=block.quote_depth)
props.append('<w:ind w:left="720" w:hanging="360"/>')
if block.quote_depth:
props.append('<w:ind w:left="720"/>')
ppr = f"<w:pPr>{''.join(props)}</w:pPr>" if props else ""
return f"<w:p>{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}</w:p>"
def _run_xml(text: str, style: dict[str, bool]) -> str:
if text == "\n":
return "<w:r><w:br/></w:r>"
props = []
if style.get("bold"):
props.append("<w:b/>")
if style.get("italic"):
props.append("<w:i/>")
if style.get("code"):
props.append('<w:rStyle w:val="CodeChar"/>')
rpr = f"<w:rPr>{''.join(props)}</w:rPr>" if props else ""
preserve = ' xml:space="preserve"' if text[:1].isspace() or text[-1:].isspace() else ""
return f"<w:r>{rpr}<w:t{preserve}>{escape(text)}</w:t></w:r>"
def _table_xml(block: TableBlock) -> str:
rows = []
for row in block.rows:
cells = []
for cell in row:
cells.append(f"<w:tc><w:tcPr><w:tcW w:w=\"0\" w:type=\"auto\"/></w:tcPr>{_paragraph_xml(ParagraphBlock(cell))}</w:tc>")
rows.append(f"<w:tr>{''.join(cells)}</w:tr>")
return (
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/>'
'<w:tblBorders><w:top w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
'<w:left w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
'<w:bottom w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
'<w:right w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
'<w:insideH w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
'<w:insideV w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/></w:tblBorders></w:tblPr>'
f"{''.join(rows)}</w:tbl>"
)
CONTENT_TYPES_XML = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
<Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>
</Types>
"""
PACKAGE_RELS_XML = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>
"""
SETTINGS_XML = f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:settings xmlns:w="{WP_NS}">
<w:defaultTabStop w:val="720"/>
</w:settings>
"""
STYLES_XML = f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="{WP_NS}">
<w:style w:type="paragraph" w:default="1" w:styleId="Normal">
<w:name w:val="Normal"/>
<w:qFormat/>
<w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr>
<w:rPr><w:rFonts w:ascii="Microsoft YaHei" w:eastAsia="Microsoft YaHei" w:hAnsi="Microsoft YaHei"/><w:sz w:val="22"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:styleId="Heading1">
<w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:qFormat/>
<w:pPr><w:spacing w:before="360" w:after="160"/><w:outlineLvl w:val="0"/></w:pPr>
<w:rPr><w:b/><w:sz w:val="32"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:styleId="Heading2">
<w:name w:val="heading 2"/><w:basedOn w:val="Normal"/><w:qFormat/>
<w:pPr><w:spacing w:before="280" w:after="140"/><w:outlineLvl w:val="1"/></w:pPr>
<w:rPr><w:b/><w:sz w:val="28"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:styleId="Heading3">
<w:name w:val="heading 3"/><w:basedOn w:val="Normal"/><w:qFormat/>
<w:pPr><w:spacing w:before="220" w:after="120"/><w:outlineLvl w:val="2"/></w:pPr>
<w:rPr><w:b/><w:sz w:val="24"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:styleId="Heading4"><w:name w:val="heading 4"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading5"><w:name w:val="heading 5"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading6"><w:name w:val="heading 6"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Quote">
<w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/>
<w:pPr><w:ind w:left="720"/><w:spacing w:before="120" w:after="120"/></w:pPr>
<w:rPr><w:i/><w:color w:val="57606A"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:styleId="Code">
<w:name w:val="Code"/><w:basedOn w:val="Normal"/>
<w:pPr><w:spacing w:before="80" w:after="80"/></w:pPr>
<w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:eastAsia="Microsoft YaHei"/><w:sz w:val="20"/></w:rPr>
</w:style>
<w:style w:type="character" w:styleId="CodeChar">
<w:name w:val="Code Char"/>
<w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:eastAsia="Microsoft YaHei"/><w:sz w:val="20"/></w:rPr>
</w:style>
<w:style w:type="table" w:default="1" w:styleId="TableGrid">
<w:name w:val="Table Grid"/>
</w:style>
</w:styles>
"""