#!/usr/bin/env python3 """ Markdown to PDF converter with Chinese font support and theme system. Converts markdown files to PDF using: - pandoc (markdown → HTML) - weasyprint or headless Chrome (HTML → PDF), auto-detected Usage: python md_to_pdf.py input.md output.pdf python md_to_pdf.py input.md --theme warm-terra python md_to_pdf.py input.md --theme default --backend chrome python md_to_pdf.py input.md # outputs input.pdf, default theme, auto backend Themes: Stored in ../themes/*.css. Built-in themes: - default: Songti SC + black/grey, formal documents - warm-terra: PingFang SC + terra cotta, training/workshop materials Requirements: pandoc (system install, e.g. brew install pandoc) weasyprint (pip install weasyprint) OR Google Chrome (for --backend chrome) """ from __future__ import annotations import argparse import os import platform import re import shutil import subprocess import sys import tempfile from pathlib import Path SCRIPT_DIR = Path(__file__).resolve().parent THEMES_DIR = SCRIPT_DIR.parent / "themes" # macOS ARM: auto-configure library path for weasyprint if platform.system() == "Darwin": _homebrew_lib = "/opt/homebrew/lib" if Path(_homebrew_lib).is_dir(): _cur = os.environ.get("DYLD_LIBRARY_PATH", "") if _homebrew_lib not in _cur: os.environ["DYLD_LIBRARY_PATH"] = ( f"{_homebrew_lib}:{_cur}" if _cur else _homebrew_lib ) def _find_chrome() -> str | None: """Find Chrome/Chromium binary path.""" candidates = [ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", shutil.which("google-chrome"), shutil.which("chromium"), shutil.which("chrome"), ] for c in candidates: if c and Path(c).exists(): return str(c) return None def _has_weasyprint() -> bool: """Check if weasyprint is importable.""" try: import weasyprint # noqa: F401 return True except ImportError: return False def _detect_backend() -> str: """Auto-detect best available backend: weasyprint > chrome.""" if _has_weasyprint(): return "weasyprint" if _find_chrome(): return "chrome" print( "Error: No PDF backend found. Install weasyprint (pip install weasyprint) " "or Google Chrome.", file=sys.stderr, ) sys.exit(1) def _load_theme(theme_name: str) -> str: """Load CSS from themes directory.""" theme_file = THEMES_DIR / f"{theme_name}.css" if not theme_file.exists(): available = [f.stem for f in THEMES_DIR.glob("*.css")] print( f"Error: Theme '{theme_name}' not found. Available: {available}", file=sys.stderr, ) sys.exit(1) return theme_file.read_text(encoding="utf-8") def _list_themes() -> list[str]: """List available theme names.""" if not THEMES_DIR.exists(): return [] return sorted(f.stem for f in THEMES_DIR.glob("*.css")) def _ensure_list_spacing(text: str) -> str: """Ensure blank lines before list items for proper markdown parsing. Both Python markdown library and pandoc require a blank line before a list when it follows a paragraph. Without it, list items render as plain text. """ lines = text.split("\n") result = [] list_re = re.compile(r"^(\s*)([-*+]|\d+\.)\s") for i, line in enumerate(lines): if i > 0 and list_re.match(line): prev = lines[i - 1] if prev.strip() and not list_re.match(prev): result.append("") result.append(line) return "\n".join(result) def _md_to_html(md_file: str) -> str: """Convert markdown to HTML using pandoc with list spacing preprocessing.""" if not shutil.which("pandoc"): print( "Error: pandoc not found. Install with: brew install pandoc", file=sys.stderr, ) sys.exit(1) md_content = Path(md_file).read_text(encoding="utf-8") md_content = _ensure_list_spacing(md_content) result = subprocess.run( ["pandoc", "-f", "markdown", "-t", "html"], input=md_content, capture_output=True, text=True, ) if result.returncode != 0: print(f"Error: pandoc failed: {result.stderr}", file=sys.stderr) sys.exit(1) return result.stdout def _build_full_html(html_content: str, css: str, title: str) -> str: """Wrap HTML content in a full document with CSS.""" return f"""