from __future__ import annotations import html import shutil import subprocess import sys import tempfile import time 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 from .markdown_compat import cjk_strong_plugin 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, style_rules: dict | None = None, document_font_family: str = "", document_font_size: float = 16, preset: str = "default", page_settings: object = None, cancel: object = None, progress: object = None, ) -> Path: from .docx_style import apply_docx_styles from .export_jobs import check_cancelled from .file_versions import atomic_write if output_path.suffix.lower() != ".docx": output_path = output_path.with_suffix(".docx") check_cancelled(cancel) if progress: progress("正在转换 Word 内容…") with tempfile.TemporaryDirectory(prefix="mdhelper-export-") as directory: target = Path(directory) / "document.docx" if engine == "pandoc": result = export_markdown_to_docx_pandoc(source, target, source_path=source_path, cancel=cancel) elif engine == "python-docx": result = export_markdown_to_docx_python_docx(source, target) else: result = export_markdown_to_docx_builtin(source, target) check_cancelled(cancel) if progress: progress("正在应用字体、段落和页面设置…") apply_docx_styles(result, style_rules, font_family=document_font_family, font_size_px=document_font_size, preset=preset) if page_settings is not None: from .export_settings import apply_docx_page_settings apply_docx_page_settings(result, page_settings) check_cancelled(cancel) data = result.read_bytes() check_cancelled(cancel) atomic_write(output_path, data) return 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) package.writestr("word/_rels/document.xml.rels", DOCUMENT_RELS_XML) return output_path def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None, cancel: object = None) -> Path: output_path = output_path.resolve() 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 安装包可能不完整,请重新获取完整版本。") # Export the current editor text, including unsaved edits. Retain the source # directory only for resolving linked images and other local resources. 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 resource_directory = source_path.resolve().parent if source_path is not None else input_path.parent 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: from .export_jobs import check_cancelled process = subprocess.Popen( command, cwd=str(resource_directory), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", **run_options, ) started = time.monotonic() try: while True: check_cancelled(cancel) if time.monotonic() - started > 120: raise subprocess.TimeoutExpired(command, 120) try: stdout, stderr = process.communicate(timeout=0.1) break except subprocess.TimeoutExpired: continue finally: if process.poll() is None: process.kill() process.communicate() 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 process.returncode != 0: detail = (stderr or 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 from docx.enum.style import WD_STYLE_TYPE 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") document.styles.add_style("MDHelper Code Char", WD_STYLE_TYPE.CHARACTER) 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"]).use(cjk_strong_plugin) 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": from docx.enum.style import WD_STYLE_TYPE if "MDHelper Code" not in document.styles: document.styles.add_style("MDHelper Code", WD_STYLE_TYPE.PARAGRAPH) style = "MDHelper Code" elif block.quote_depth: style = "Quote" 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) if run_style.get("bold"): run.bold = True if run_style.get("italic"): run.italic = True if run_style.get("code") or block.style == "Code": if run_style.get("code"): run.style = "MDHelper Code Char" 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) if run_style.get("bold") or row_index == 0: run.bold = True if run_style.get("italic"): run.italic = True if run_style.get("code"): run.style = "MDHelper Code Char" 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""" {body} """ 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''] if block.style != "Normal" else [] if block.list_kind: props = [''] 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('') if block.quote_depth: props.append('') ppr = f"{''.join(props)}" if props else "" return f"{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}" def _run_xml(text: str, style: dict[str, bool]) -> str: if text == "\n": return "" props = [] if style.get("bold"): props.append("") if style.get("italic"): props.append("") if style.get("code"): props.append('') rpr = f"{''.join(props)}" if props else "" preserve = ' xml:space="preserve"' if text[:1].isspace() or text[-1:].isspace() else "" return f"{rpr}{escape(text)}" def _table_xml(block: TableBlock) -> str: rows = [] for row in block.rows: cells = [] for cell in row: cells.append(f"{_paragraph_xml(ParagraphBlock(cell))}") rows.append(f"{''.join(cells)}") return ( '' '' '' '' '' '' '' f"{''.join(rows)}" ) CONTENT_TYPES_XML = """ """ PACKAGE_RELS_XML = """ """ DOCUMENT_RELS_XML = """ """ SETTINGS_XML = f""" """ STYLES_XML = f""" """