Files
hsa/Html/apps/services/markdown_service.py
2025-08-27 19:39:38 +08:00

41 lines
1.2 KiB
Python

import os, shutil, markdown
def convert_markdown_to_html(md_file_path: str) -> str:
"""读取 markdown 并转成 HTML 片段"""
with open(md_file_path, 'r', encoding='utf-8') as f:
md_content = f.read()
return markdown.markdown(md_content)
def wrap_with_styles(html_content: str) -> str:
"""加上 CSS 样式和外层 HTML"""
return f"""
<html>
<head>
<style>
img {{
max-width: 100%;
height: auto;
}}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
</head>
<body class="markdown-body">
{html_content}
</body>
</html>
"""
def save_html(html_str: str, output_path: str) -> None:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
f.write(html_str)
def copy_images(source_dir: str, target_dir: str) -> None:
if not os.path.exists(source_dir):
return
os.makedirs(target_dir, exist_ok=True)
for filename in os.listdir(source_dir):
src = os.path.join(source_dir, filename)
if os.path.isfile(src):
shutil.copy(src, target_dir)