diff --git a/zhenxun/utils/_image_template.py b/zhenxun/utils/_image_template.py index 7f27db76..2254fda0 100644 --- a/zhenxun/utils/_image_template.py +++ b/zhenxun/utils/_image_template.py @@ -3,6 +3,7 @@ from io import BytesIO from pathlib import Path import random +from nonebot_plugin_htmlrender import md_to_pic from PIL.ImageFont import FreeTypeFont from pydantic import BaseModel @@ -283,3 +284,83 @@ class ImageTemplate: width = max(width, w) height += h return width, height + + +class MarkdownTable: + def __init__(self, headers: list[str], rows: list[list[str]]): + self.headers = headers + self.rows = rows + + def to_markdown(self) -> str: + """将表格转换为Markdown格式""" + header_row = "| " + " | ".join(self.headers) + " |" + separator_row = "| " + " | ".join(["---"] * len(self.headers)) + " |" + data_rows = "\n".join( + "| " + " | ".join(map(str, row)) + " |" for row in self.rows + ) + return f"{header_row}\n{separator_row}\n{data_rows}" + + +class Markdown: + def __init__(self, data: list[str] | None = None): + if data is None: + data = [] + self._data = data + + def text(self, text: str) -> "Markdown": + """添加Markdown文本""" + self._data.append(text) + return Markdown(self._data) + + def head(self, text: str, level: int = 1) -> "Markdown": + """添加Markdown标题""" + if level < 1 or level > 6: + raise ValueError("标题级别必须在1到6之间") + self._data.append(f"{'#' * level} {text}") + return Markdown(self._data) + + def image(self, url: str) -> "Markdown": + """添加Markdown图片""" + self._data.append(f"![image]({url})") + return Markdown(self._data) + + def quote(self, text: str | list[str]) -> "Markdown": + """添加Markdown引用""" + if isinstance(text, str): + self._data.append(f"> {text}") + elif isinstance(text, list): + for t in text: + self._data.append(f"> {t}") + self._add_empty_line() + return Markdown(self._data) + + def code(self, code: str, language: str = "python") -> "Markdown": + """添加Markdown代码块""" + self._data.append(f"```{language}\n{code}\n```") + return Markdown(self._data) + + def table(self, headers: list[str], rows: list[list[str]]) -> "Markdown": + """添加Markdown表格""" + table = MarkdownTable(headers, rows) + self._data.append(table.to_markdown()) + return Markdown(self._data) + + def list(self, items: list[str | list[str]]) -> "Markdown": + """添加Markdown列表""" + self._add_empty_line() + _text = "\n".join( + f"- {item}" + if isinstance(item, str) + else "\n".join(f"- {sub_item}" for sub_item in item) + for item in items + ) + self._data.append(_text) + return Markdown(self._data) + + def _add_empty_line(self): + """添加空行""" + self._data.append("") + + async def build(self, width: int = 800) -> bytes: + """构建Markdown文本""" + return await md_to_pic(md="\n".join(self._data), width=width)