from __future__ import annotations import re import markdown from markdown.extensions.codehilite import CodeHiliteExtension from markdown.extensions.fenced_code import FencedCodeExtension from premailer import transform def convert_markdown_to_wechat(md_content: str) -> tuple[str, str]: """ 将 Markdown 文本转换为微信公众号 HTML Args: md_content: Markdown 格式的文本 Returns: (标题, HTML内容) 元组 """ if not md_content or not md_content.strip(): return "", "

" # 提取标题 title = extract_title(md_content) # 1. 定义微信风格的基础 CSS 样式 # 微信对这些属性支持较好:color, font-size, margin, padding, line-height custom_css = """ .wechat-body { font-family: -apple-system-font, BlinkMacSystemFont, "Helvetica Neue", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif; font-size: 16px; color: #353535; line-height: 1.75; padding: 10px; } h1 { font-size: 24px; color: #007aff; border-bottom: 2px solid #007aff; padding-bottom: 10px; margin-top: 30px; margin-bottom: 15px; } h2 { font-size: 20px; color: #007aff; margin-top: 25px; margin-bottom: 10px; border-left: 4px solid #007aff; padding-left: 10px; } h3 { font-size: 18px; color: #007aff; margin-top: 20px; margin-bottom: 10px; } h4 { font-size: 16px; font-weight: bold; color: #007aff; margin-top: 15px; margin-bottom: 8px; } h5 { font-size: 14px; font-weight: bold; color: #007aff; margin-top: 12px; margin-bottom: 6px; } p { margin: 15px 0; text-align: justify; } code { background-color: #f8f8f8; color: #ff502c; padding: 2px 4px; border-radius: 3px; font-family: Consolas, Monaco, 'Andale Mono', monospace; font-size: 14px; } pre { background-color: #282c34; color: #abb2bf; padding: 15px; border-radius: 5px; overflow-x: auto; line-height: 1.4; font-family: Consolas, Monaco, 'Andale Mono', monospace; font-size: 13px; } pre code { background-color: transparent; color: inherit; padding: 0; border-radius: 0; font-size: inherit; } ul, ol { padding-left: 30px; color: #555; margin: 15px 0; } li { margin: 8px 0; } blockquote { border-left: 4px solid #007aff; color: #666; padding-left: 15px; margin: 20px 0; background-color: #f8f9fa; font-style: italic; } img { max-width: 100%; border-radius: 4px; display: block; margin: 20px auto; } a { color: #007aff; text-decoration: none; } table { width: 100%; border-collapse: collapse; margin: 15px 0; font-size: 14px; } th, td { border: 1px solid #ddd; padding: 10px; text-align: left; } th { background-color: #f8f9fa; font-weight: bold; } hr { border: none; border-top: 1px solid #e0e0e0; margin: 30px 0; } """ # 2. 将 Markdown 转为 HTML # 使用 fenced_code 处理代码块,codehilite 处理高亮 html_body = markdown.markdown(md_content, extensions=[ FencedCodeExtension(), CodeHiliteExtension(css_class='highlight', linenums=False, guess_lang=False), 'tables', 'nl2br' ]) # 3. 包装在外层容器中 full_html = f"""
{html_body}
""" # 4. 关键步骤:使用 premailer 将 CSS 内联化 # 它会扫描