yimo-kit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. yimo/__init__.py +26 -0
  2. yimo/kit/__init__.py +98 -0
  3. yimo/kit/ai/__init__.py +110 -0
  4. yimo/kit/ai/_internal/__init__.py +27 -0
  5. yimo/kit/ai/_internal/failover.py +535 -0
  6. yimo/kit/ai/_internal/pool.py +526 -0
  7. yimo/kit/ai/_internal/rerank_transport.py +137 -0
  8. yimo/kit/ai/_internal/retry_after.py +51 -0
  9. yimo/kit/ai/_internal/sdk_client.py +463 -0
  10. yimo/kit/ai/_internal/service_base.py +115 -0
  11. yimo/kit/ai/_internal/types.py +28 -0
  12. yimo/kit/ai/agent/__init__.py +127 -0
  13. yimo/kit/ai/agent/approval.py +66 -0
  14. yimo/kit/ai/agent/errors.py +128 -0
  15. yimo/kit/ai/agent/loop.py +643 -0
  16. yimo/kit/ai/agent/mcp.py +278 -0
  17. yimo/kit/ai/agent/registry.py +203 -0
  18. yimo/kit/ai/agent/session.py +150 -0
  19. yimo/kit/ai/agent/skill.py +370 -0
  20. yimo/kit/ai/agent/types.py +161 -0
  21. yimo/kit/ai/chat_service.py +724 -0
  22. yimo/kit/ai/decision/__init__.py +57 -0
  23. yimo/kit/ai/decision/decima.py +853 -0
  24. yimo/kit/ai/decision/laya.py +552 -0
  25. yimo/kit/ai/embedding_service.py +198 -0
  26. yimo/kit/ai/exceptions.py +109 -0
  27. yimo/kit/ai/image_service.py +84 -0
  28. yimo/kit/ai/messages.py +105 -0
  29. yimo/kit/ai/model_builder.py +121 -0
  30. yimo/kit/ai/model_client.py +62 -0
  31. yimo/kit/ai/profiles.py +577 -0
  32. yimo/kit/ai/rerank_service.py +136 -0
  33. yimo/kit/ai/runner.py +1127 -0
  34. yimo/kit/common_kit.py +221 -0
  35. yimo/kit/config/__init__.py +44 -0
  36. yimo/kit/config/kit_config.py +210 -0
  37. yimo/kit/config/log_config.py +171 -0
  38. yimo/kit/crawl/__init__.py +71 -0
  39. yimo/kit/crawl/article_io.py +325 -0
  40. yimo/kit/crawl/article_models.py +172 -0
  41. yimo/kit/crawl/deepseek_kit.py +673 -0
  42. yimo/kit/crawl/web_article_kit.py +638 -0
  43. yimo/kit/crawl/wx_article_kit.py +692 -0
  44. yimo/kit/db/__init__.py +101 -0
  45. yimo/kit/db/audit.py +625 -0
  46. yimo/kit/db/base_db_kit.py +1265 -0
  47. yimo/kit/db/crud.py +423 -0
  48. yimo/kit/db/engine.py +235 -0
  49. yimo/kit/db/exceptions.py +45 -0
  50. yimo/kit/db/models/__init__.py +33 -0
  51. yimo/kit/db/models/base.py +56 -0
  52. yimo/kit/db/mysql_kit.py +348 -0
  53. yimo/kit/db/pg_kit.py +442 -0
  54. yimo/kit/db/query.py +338 -0
  55. yimo/kit/db/session.py +85 -0
  56. yimo/kit/db/sqlite_kit.py +462 -0
  57. yimo/kit/db/transaction.py +109 -0
  58. yimo/kit/docs/__init__.py +34 -0
  59. yimo/kit/docs/anydoc_kit.py +490 -0
  60. yimo/kit/docs/docx_kit.py +895 -0
  61. yimo/kit/docs/md2doc_kit.py +1801 -0
  62. yimo/kit/docs/mineru_kit.py +1497 -0
  63. yimo/kit/docs/rc_docparser_kit.py +654 -0
  64. yimo/kit/file_kit.py +518 -0
  65. yimo/kit/license_kit.py +533 -0
  66. yimo/kit/redis_kit.py +392 -0
  67. yimo_kit-0.1.0.dist-info/METADATA +1673 -0
  68. yimo_kit-0.1.0.dist-info/RECORD +70 -0
  69. yimo_kit-0.1.0.dist-info/WHEEL +4 -0
  70. yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,1801 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-09-23
21
+ """Md2DocKit —— Markdown 渲染工具类(PiMD + fpdf2)
22
+
23
+ 支持面:GitHub-Flavored Markdown 文件 → Word(`.docx`)/ PDF / 独立 HTML。
24
+
25
+ 实现内容:
26
+ - 全部静态方法、无内部状态;PiMD 转换引擎为模块级单例(自带 MemoryCache)。
27
+ - Word 走 PiMD 引擎 + 表格撑满/全局字体后处理;PDF 与 HTML 同源解析
28
+ (markdown-it),PDF 由内置 fpdf2 渲染器生成,观感向 HTML 对齐。
29
+ - 图片:PDF 由 fpdf2 直接绘制;Word 用占位标记 + python-docx 回填真实图片;
30
+ HTML 用占位标记 + 后处理输出 `<figure><img>`。三者均以 Markdown 源文件
31
+ 所在目录为相对路径基准,缺图/越界/不支持格式回落 alt 文本(不抛异常)。
32
+ - 转换前统一改写 CJK 加粗定界符:CommonMark 定界规则下 `**加粗:**后接`
33
+ 会把星号作为字面量漏进产物。
34
+
35
+ 前提条件:
36
+ - 输入必须是 `.md` 文件路径;转换期间使用固定名临时文件
37
+ (`.{源文件名}.pimd-tmp.md`),**同一源文件的并发调用不受支持**。
38
+ - 代码块无背景填充等与 HTML 的已知差异,见对应方法说明。
39
+ - 图片仅支持本地相对路径(`images/a.png` 形式);远程 URL 在 PDF/Word
40
+ 中回落为 alt 文本(不取网),在 HTML 中直接输出 `<img src>` 交由浏览器。
41
+
42
+ 依赖:
43
+ - `pimd` + `markdown-it-py` + `fpdf2`(extra `md2doc`);
44
+ 未安装时导入报错并提示安装命令。
45
+ - 图片能力另需 Pillow(`fpdf2` 硬依赖)与 python-docx(`pimd` 硬依赖),
46
+ 均由上游保证,不单独声明;缺失时按 ImportError 降级(回落 0.6.3 行为)。
47
+ """
48
+
49
+ import importlib.util
50
+ import os
51
+ import re
52
+ import zipfile
53
+ from html import escape as _html_escape
54
+ from pathlib import Path
55
+ from typing import Any
56
+ from urllib.parse import unquote, urlsplit
57
+
58
+ try:
59
+ from fpdf import FPDF
60
+ from markdown_it import MarkdownIt
61
+ from markdown_it.token import Token
62
+ from pimd import PiMD
63
+ from pimd.exceptions import ConversionError
64
+ except ImportError as e:
65
+ raise ImportError(
66
+ 'md2doc_kit 需要可选依赖,请安装:pip install "yimo-kit[md2doc]"'
67
+ ) from e
68
+
69
+ from yimo.kit.config.log_config import get_default_logger
70
+
71
+ logger = get_default_logger(__name__)
72
+
73
+ # PiMD 转换引擎单例:内部自带 MemoryCache,按进程复用(线程安全)
74
+ _PIMD = PiMD()
75
+
76
+ # PDF 渲染解析器:与 convert_md_to_html(PiMD 内部)同为 markdown-it 解析,
77
+ # 保证 PDF 与 HTML 对同一 Markdown 的结构理解一致(GFM 表格需显式启用)
78
+ _MD_PARSER = MarkdownIt("commonmark").enable("table")
79
+
80
+
81
+ # CJK 加粗泄漏模式:闭合 ** 前为标点串、后紧跟文字(如 `**加粗:**后接`)。
82
+ # PiMD(markdown-it,CommonMark 系)同样执行定界符规则,闭合 ** 须满足
83
+ # right-flanking(不被标点前置,或被空白/标点后置),上述写法不满足,
84
+ # 星号会以字面文本进入产物。改写策略:把尾部标点串移出粗体定界符。
85
+ _CJK_BOLD_LEAK_RE = re.compile(
86
+ r"\*\*(?P<content>[^*\n]+?)(?P<punct>[^\w\s]+?)\*\*(?=\w)"
87
+ )
88
+
89
+
90
+ def _normalize_cjk_bold(markdown: str) -> str:
91
+ """规避 Markdown 引擎对中文加粗的 CommonMark 定界限制
92
+
93
+ 两类处理:
94
+ - 普通文本行:将 `**加粗:**后接` 改写为 `**加粗**:后接`(尾部标点
95
+ 移出粗体定界符),闭合 ** 后紧跟文字的泄漏场景;文本内容零增删。
96
+ - 表格块内的行:PiMD 的表格单元格以纯文本写入(不解析行内 Markdown),
97
+ `**` 定界符必然字面泄漏,直接剥除定界符保留文本(表头自带加粗
98
+ 样式,不依赖 `**`)。
99
+ 表格块按块级状态判定:仅当某行是表格行、且其下一行是 GFM 分隔行
100
+ (如 `| --- | --- |`)时才进入表格块,块内逐行延续至首个非表格行
101
+ 为止;避免把正文中的竖线(如 "支持 A | B 两种")误判为表格行而
102
+ 连带剥除其加粗定界符。
103
+ 围栏代码块与行内代码段不做处理。
104
+ """
105
+ lines = markdown.splitlines(keepends=True)
106
+ out_lines: list[str] = []
107
+ in_fence = False
108
+ fence_marker = ""
109
+ in_table = False
110
+ for idx, line in enumerate(lines):
111
+ stripped = line.lstrip()
112
+ if not in_fence and (stripped.startswith("```") or stripped.startswith("~~~")):
113
+ in_fence = True
114
+ fence_marker = stripped[:3]
115
+ in_table = False
116
+ out_lines.append(line)
117
+ continue
118
+ if in_fence:
119
+ if stripped.startswith(fence_marker):
120
+ in_fence = False
121
+ out_lines.append(line)
122
+ continue
123
+ if in_table:
124
+ # 表格块内:本行仍是表格行则继续剥除定界符,否则表格块结束
125
+ is_table = _is_table_row(line)
126
+ else:
127
+ # 表格块起点:本行是表格行且其下一行是 GFM 分隔行
128
+ is_table = (
129
+ _is_table_row(line)
130
+ and idx + 1 < len(lines)
131
+ and _is_table_delim(lines[idx + 1])
132
+ )
133
+ in_table = is_table
134
+ # 行内代码段(1~3 个反引号包裹)保护:不做处理
135
+ segments = re.split(r"(`+[^`]*`+)", line)
136
+ fixed = "".join(
137
+ (
138
+ seg
139
+ if seg.startswith("`")
140
+ else (
141
+ _strip_bold_delims(seg)
142
+ if is_table
143
+ else _CJK_BOLD_LEAK_RE.sub(r"**\g<content>**\g<punct>", seg)
144
+ )
145
+ )
146
+ for seg in segments
147
+ )
148
+ out_lines.append(fixed)
149
+ return "".join(out_lines)
150
+
151
+
152
+ def _strip_bold_delims(text: str) -> str:
153
+ """剥除加粗/斜体定界符,保留文本内容(用于不解析行内格式的表格单元格)"""
154
+ text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text)
155
+ text = re.sub(r"\*([^*]+)\*", r"\1", text)
156
+ return text
157
+
158
+
159
+ # HTML 默认排版:覆盖 PiMD 自带 HTML 样式(body `max-width: 900px` 等默认值),
160
+ # 注入方式为转换后插入 `</head>` 前(覆盖同名选择器声明);CSS 侧重中文文档宽屏阅读。
161
+ _MD_HTML_CSS = """<style>
162
+ /* 浏览器页签标题由是否注入 title 元素决定(该元素不参与页面渲染),
163
+ 本规则是覆盖 PiMD 默认样式后的兼容残留,实际不隐藏任何可见内容 */
164
+ head title {
165
+ display: none;
166
+ }
167
+ body {
168
+ max-width: 60em;
169
+ margin: 0 auto;
170
+ padding: 1em 1.5em 3em;
171
+ font-size: 16px;
172
+ line-height: 1.7;
173
+ font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
174
+ color: #1a1a1a;
175
+ background-color: #fdfdfd;
176
+ }
177
+ h1, h2, h3, h4, h5, h6 {
178
+ line-height: 1.3;
179
+ margin-top: 1.4em;
180
+ margin-bottom: 0.5em;
181
+ font-weight: 600;
182
+ overflow-wrap: anywhere;
183
+ }
184
+ h1 { font-size: 2em; border-bottom: 1px solid #e6e6e6; padding-bottom: 0.3em; }
185
+ h2 { font-size: 1.6em; border-bottom: 1px solid #e6e6e6; padding-bottom: 0.3em; }
186
+ h3 { font-size: 1.3em; }
187
+ h4, h5, h6 { font-size: 1.1em; }
188
+ table {
189
+ width: 100%;
190
+ max-width: 100%;
191
+ border-collapse: collapse;
192
+ margin: 1em 0;
193
+ font-size: 0.95em;
194
+ }
195
+ th, td {
196
+ border: 1px solid #ccc;
197
+ padding: 6px 10px;
198
+ text-align: left;
199
+ vertical-align: top;
200
+ }
201
+ th {
202
+ background-color: #f0f0f0;
203
+ font-weight: 600;
204
+ }
205
+ pre {
206
+ background-color: #f6f8fa;
207
+ border: 1px solid #e6e6e6;
208
+ border-radius: 4px;
209
+ padding: 0.8em 1em;
210
+ overflow-x: auto;
211
+ line-height: 1.5;
212
+ }
213
+ code {
214
+ font-family: "Cascadia Code", Menlo, Consolas, monospace;
215
+ font-size: 0.9em;
216
+ background-color: #f6f8fa;
217
+ border-radius: 4px;
218
+ padding: 0.1em 0.35em;
219
+ }
220
+ pre code {
221
+ background-color: transparent;
222
+ padding: 0;
223
+ }
224
+ img {
225
+ max-width: 100%;
226
+ height: auto;
227
+ }
228
+ figure.md2doc-img {
229
+ margin: 1em 0;
230
+ text-align: center;
231
+ }
232
+ @media (max-width: 720px) {
233
+ body {
234
+ padding: 0.5em 0.8em 2em;
235
+ font-size: 15px;
236
+ }
237
+ table {
238
+ display: block;
239
+ overflow-x: auto;
240
+ }
241
+ }
242
+ </style>"""
243
+
244
+
245
+ # PiMD 产出的「自动宽度」表格标记:属性顺序无关(type 与 w 的先后不影响匹配)
246
+ _TBLW_AUTO_RE = re.compile(
247
+ r'<w:tblW\b(?=[^>]*\bw:type="auto")(?=[^>]*\bw:w="0")[^>]*/>'
248
+ )
249
+
250
+
251
+ def _polish_table_layout(docx_path: Path) -> None:
252
+ """表格版式后处理:宽度撑满页宽并整体居中
253
+
254
+ 转换引擎(PiMD 底层 python-docx)写出的 `tblW type=auto`
255
+ 会使表格按内容收缩、不满页宽;将其替换为 pct 5000(100% 页宽)并
256
+ 追加居中标记(jc 紧随 tblW,符合 OOXML 元素顺序),其余包内成员
257
+ 原样重打包。无表格时为空操作。
258
+ """
259
+ with zipfile.ZipFile(docx_path) as zin:
260
+ doc_xml = zin.read("word/document.xml").decode("utf-8")
261
+ if not _TBLW_AUTO_RE.search(doc_xml):
262
+ return
263
+ polished = _TBLW_AUTO_RE.sub(
264
+ '<w:tblW w:type="pct" w:w="5000" />\n<w:jc w:val="center" />',
265
+ doc_xml,
266
+ )
267
+ tmp = docx_path.with_name(f".{docx_path.stem}.polish-tmp")
268
+ with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
269
+ for item in zin.infolist():
270
+ if item.filename == "word/document.xml":
271
+ zout.writestr(item, polished)
272
+ else:
273
+ zout.writestr(item, zin.read(item.filename))
274
+ tmp.replace(docx_path)
275
+
276
+
277
+ # 等宽样式隔离:这些 styleId 的 rFonts 属于代码块,字体后处理跳过,
278
+ # 保证代码块在全文宋体化后仍为等宽字体
279
+ _MONO_STYLE_IDS = frozenset({"CodeBlock", "MacroText", "MacroTextChar"})
280
+ # 显式字体名含此模式的样式视为等宽,同样跳过
281
+ _MONO_FONT_RE = re.compile(
282
+ r"Courier|Consolas|Menlo|Monaco|Source Code|Lucida Console", re.I
283
+ )
284
+
285
+
286
+ def _polish_docx_font(docx_path: Path, font_name: str) -> None:
287
+ """全局字体后处理:docDefaults / 主题 / 样式级 rFonts 统一为指定字体
288
+
289
+ PiMD 产物正文西文走主题 minorFont(Calibri)、标题走 majorFont,
290
+ **且每个样式自带显式 rFonts**(样式级优先级高于 docDefaults 与主题)。
291
+ 仅改写默认通道会在 Word 中仍显示 Calibri。因此此处三通道一起改写,
292
+ 使全文统一为 font_name:
293
+ - styles.xml docDefaults:主题引用 rFonts 替换为显式四项字体(兜底);
294
+ - theme1.xml:majorFont/minorFont 顶层 latin/ea/cs typeface 改写
295
+ (Heading 1~6 / Title 等走主题字体的样式兜底);
296
+ - styles.xml 各 `<w:style>` 内 rFonts:显式 Calibri 替换为 font_name,
297
+ 主题引用(majorHAnsi/majorEastAsia……)替换为显式四项 font_name。
298
+ 等宽样式(CodeBlock/MacroText 等、Courier 系字体)跳过,保持代码块
299
+ 等宽观感;run 级显式字体优先级最高,本处理不触及。
300
+ """
301
+ esc = font_name.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
302
+ with zipfile.ZipFile(docx_path) as zin:
303
+ names = zin.namelist()
304
+ patched: dict[str, str] = {}
305
+ if "word/styles.xml" in names:
306
+ xml = zin.read("word/styles.xml").decode("utf-8")
307
+
308
+ def _rewrite_rfonts(m: re.Match[str], style_id: str | None) -> str:
309
+ """单个 <w:rFonts .../> 重写:等宽样式跳过,其余统一字体
310
+
311
+ - 含主题引用(asciiTheme 等)→ 替换为显式四项字体;
312
+ - 显式字体(ascii/hAnsi/eastAsia/cs)→ 仅替换字体名,
313
+ 保留 style/val 等其他属性。
314
+ """
315
+ attrs = m.group(0)
316
+ if style_id in _MONO_STYLE_IDS or re.search(_MONO_FONT_RE, attrs):
317
+ return attrs
318
+ if "w:asciiTheme" in attrs:
319
+ return (
320
+ f'<w:rFonts w:ascii="{esc}" w:eastAsia="{esc}" '
321
+ f'w:hAnsi="{esc}" w:cs="{esc}" />'
322
+ )
323
+ for prop in ("w:ascii", "w:hAnsi", "w:eastAsia", "w:cs"):
324
+ attr_re = re.compile(rf"{re.escape(prop)}=\"[^\"]*\"")
325
+ attrs = attr_re.sub(f'{prop}="{esc}"', attrs)
326
+ return attrs
327
+
328
+ def _rewrite_segment(segment: str, style_id: str | None) -> str:
329
+ """段内全部 rFonts 统一字体(style_id 为该段所属样式,段外为 None)"""
330
+ return re.sub(
331
+ r"<w:rFonts[^>]*/>",
332
+ lambda m: _rewrite_rfonts(m, style_id),
333
+ segment,
334
+ )
335
+
336
+ # 按 <w:style>…</w:style> 分块处理:块内以该样式的 styleId 判定等宽
337
+ # 隔离,块外(docDefaults 等)按 None 处理,避免用位置反推所属样式
338
+ parts: list[str] = []
339
+ last = 0
340
+ for style_match in re.finditer(r"<w:style\b.*?</w:style>", xml, re.S):
341
+ sid_match = re.search(
342
+ r'<w:style[^>]*w:styleId="([^"]+)"', style_match.group(0)
343
+ )
344
+ sid = sid_match.group(1) if sid_match else None
345
+ parts.append(_rewrite_segment(xml[last : style_match.start()], None))
346
+ parts.append(_rewrite_segment(style_match.group(0), sid))
347
+ last = style_match.end()
348
+ parts.append(_rewrite_segment(xml[last:], None))
349
+ new = "".join(parts)
350
+ if new != xml:
351
+ patched["word/styles.xml"] = new
352
+ if "word/theme/theme1.xml" in names:
353
+ xml = zin.read("word/theme/theme1.xml").decode("utf-8")
354
+ scheme = re.search(r"<a:fontScheme.*?</a:fontScheme>", xml, re.S)
355
+ if scheme:
356
+ block = scheme.group(0)
357
+ new_block = re.sub(
358
+ r'<a:latin typeface="[^"]*"', f'<a:latin typeface="{esc}"', block
359
+ )
360
+ new_block = re.sub(
361
+ r'<a:ea typeface="[^"]*"', f'<a:ea typeface="{esc}"', new_block
362
+ )
363
+ new_block = re.sub(
364
+ r'<a:cs typeface="[^"]*"', f'<a:cs typeface="{esc}"', new_block
365
+ )
366
+ if new_block != block:
367
+ patched["word/theme/theme1.xml"] = xml.replace(block, new_block)
368
+ if not patched:
369
+ return
370
+ tmp = docx_path.with_name(f".{docx_path.stem}.font-tmp")
371
+ with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
372
+ for item in zin.infolist():
373
+ data = patched.get(item.filename)
374
+ if data is not None:
375
+ zout.writestr(item, data)
376
+ else:
377
+ zout.writestr(item, zin.read(item.filename))
378
+ tmp.replace(docx_path)
379
+
380
+
381
+ # 图片占位标记(_extract_images 可能改用备用前缀):@@MD2DOC[X]-IMG-{n}@@
382
+ _DOCX_IMG_MARK_RE = re.compile(r"@@MD2DOCX?-IMG-(\d+)@@")
383
+ # EMU ↔ mm:1mm = 36000 EMU(914400 EMU/inch ÷ 25.4)
384
+ _EMU_PER_MM = 36000.0
385
+
386
+
387
+ def _replace_marker_text(para: Any, marker: str, replacement: str) -> bool:
388
+ """把段落中的占位标记文本替换为 replacement(按 `w:t` 节点逐个替换)
389
+
390
+ 直接遍历段落 XML 内的 `<w:t>` 文本节点,而非 `para.runs`:后者不包含
391
+ `<w:hyperlink>` 内的 run,`[![图](路径)](链接)` 这类链接包裹图片的标记
392
+ 会残留在超链接里(python-docx 的既有行为)。
393
+
394
+ 标记被拆进多个文本节点(PiMD 极少出现)时退化为整段纯文本重建,字符级
395
+ 样式会丢失并记 warning。
396
+
397
+ Args:
398
+ para: python-docx 段落对象
399
+ marker: 占位标记文本
400
+ replacement: 替换文本(空串表示删除标记)
401
+
402
+ Returns:
403
+ bool: 是否找到该标记并替换成功
404
+ """
405
+ for node in para._p.iter():
406
+ if not node.tag.endswith("}t"):
407
+ continue
408
+ if node.text and marker in node.text:
409
+ node.text = node.text.replace(marker, replacement)
410
+ return True
411
+ if marker not in (para.text or ""):
412
+ return False
413
+ remaining = para.text.replace(marker, replacement)
414
+ for node in para._p.iter():
415
+ if node.tag.endswith("}t"):
416
+ node.text = ""
417
+ if remaining:
418
+ para.add_run(remaining)
419
+ logger.warning("图片占位标记跨节点拆分,已按纯文本重建段落")
420
+ return True
421
+
422
+
423
+ def _drop_paragraph(para: Any) -> None:
424
+ """从文档树中移除段落(图片标记段清理后为空时使用)"""
425
+ element = para._p
426
+ element.getparent().remove(element)
427
+
428
+
429
+ def _docx_available() -> bool:
430
+ """python-docx 是否可导入(pimd 硬依赖;缺失时 Word 图片回填整体降级)
431
+
432
+ Returns:
433
+ bool: 可用返回 True;不可用时 Word 输出保持 0.6.3 的 alt 超链接行为
434
+ """
435
+ try:
436
+ return importlib.util.find_spec("docx") is not None
437
+ except (ImportError, ValueError):
438
+ return False
439
+
440
+
441
+ def _inject_docx_images(
442
+ docx_path: Path, refs: list[tuple[str, str]], base_dir: Path
443
+ ) -> None:
444
+ """把正文中的图片占位标记替换为真实图片段落(python-docx 后处理)
445
+
446
+ PiMD(markdown-it)会把行内图片降级为「alt 文本 + 指向 src 的超链接」,
447
+ docx 内没有 `word/media/`。本函数按占位标记回填:
448
+
449
+ - 标记所在段落中的标记文本删除,全部处理完且段落为空则整段移除;
450
+ - 标记段之后依次插入居中的图片段落(同段多图保持源顺序),宽高按节
451
+ 内容区等比限幅(96dpi 基准);
452
+ - 图片不可用(缺失 / 越界 / python-docx 不支持的格式如 webp)→ 标记替换
453
+ 为 alt 文本并 warning,不抛异常(保持导出可用)。
454
+
455
+ 必须在 `_polish_table_layout` / `_polish_docx_font` 之前调用:两次后处理
456
+ 直接改写 docx 包内 XML,先插图片再 polish 才能保证二者互不覆盖。
457
+
458
+ Args:
459
+ docx_path: 待回填的 docx 路径(原地修改)
460
+ refs: `_extract_images` 返回的 (src, alt) 序列
461
+ base_dir: 相对路径基准目录(Markdown 源文件所在目录)
462
+ """
463
+ try:
464
+ from docx import Document
465
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
466
+ from docx.image.image import Image as DocxImage
467
+ from docx.shared import Mm
468
+ except ImportError as e: # python-docx 由 pimd 硬依赖提供,理论不可达
469
+ logger.warning(f"python-docx 不可用,跳过 Word 图片回填: {e}")
470
+ return
471
+
472
+ doc = Document(str(docx_path))
473
+ if not doc.sections:
474
+ return
475
+ section = doc.sections[0]
476
+ # Length 是 int 子类,减法会丢 .mm 属性,故按 EMU 换算
477
+ content_w = (
478
+ int(section.page_width) - int(section.left_margin) - int(section.right_margin)
479
+ ) / _EMU_PER_MM
480
+ content_h = (
481
+ int(section.page_height) - int(section.top_margin) - int(section.bottom_margin)
482
+ ) / _EMU_PER_MM
483
+
484
+ changed = False
485
+ for para in list(doc.paragraphs):
486
+ if not _DOCX_IMG_MARK_RE.search(para.text or ""):
487
+ continue
488
+ changed = True
489
+ # 同段多张图(`![a](x) ![b](y)`)逐个处理:锚点跟随新插入的段落,
490
+ # 保证图片顺序与源文档一致(若固定插在标记段之后顺序会反转)
491
+ anchor = para._p
492
+ while True:
493
+ match = _DOCX_IMG_MARK_RE.search(para.text or "")
494
+ if match is None:
495
+ break
496
+ marker = match.group(0)
497
+ idx = int(match.group(1))
498
+ src, alt = refs[idx] if idx < len(refs) else ("", "")
499
+
500
+ path = _resolve_local_image(src, base_dir)
501
+ fitted: tuple[float, float] | None = None
502
+ if path is not None:
503
+ try:
504
+ info = DocxImage.from_file(str(path))
505
+ fitted = _fit_size(
506
+ info.px_width, info.px_height, content_w, content_h
507
+ )
508
+ except Exception as e: # noqa: BLE001 - 格式不支持统一回落
509
+ logger.warning(f"Word 图片不可用,保留 alt 文本: {src}: {e}")
510
+ fitted = None
511
+ if fitted is None:
512
+ # 不可用:标记换成 alt 文本;替换失败须跳出,避免死循环
513
+ if not _replace_marker_text(para, marker, alt):
514
+ logger.warning(f"Word 图片标记无法清除,跳过: {marker}")
515
+ break
516
+ continue
517
+
518
+ width, _height = fitted
519
+ if not _replace_marker_text(para, marker, ""):
520
+ logger.warning(f"Word 图片标记无法清除,跳过: {marker}")
521
+ break
522
+ new_para = doc.add_paragraph()
523
+ # 先挪到锚点之后,再(必要时)删除空标记段,顺序反了会失去锚点
524
+ anchor.addnext(new_para._p)
525
+ anchor = new_para._p
526
+ new_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
527
+ new_para.paragraph_format.space_before = 0
528
+ new_para.paragraph_format.space_after = 0
529
+ new_para.add_run().add_picture(str(path), width=Mm(width))
530
+ # 全部标记处理完再判断:段落已空则删除(图片段落已插好,锚点安全)
531
+ if not (para.text or "").strip():
532
+ _drop_paragraph(para)
533
+
534
+ if changed:
535
+ doc.save(str(docx_path))
536
+
537
+
538
+ # 中文字体表(单一数据源):族名 / Windows 字体文件名 / 别名(小写)
539
+ _CN_FONT_TABLE: tuple[tuple[str, str, tuple[str, ...]], ...] = (
540
+ ("SimSun", "simsun.ttc", ("simsun", "宋体")),
541
+ ("SimHei", "simhei.ttf", ("simhei", "黑体")),
542
+ ("MicrosoftYaHei", "msyh.ttc", ("msyh", "微软雅黑")),
543
+ ("KaiTi", "simkai.ttf", ("kaiti", "楷体")),
544
+ ("FangSong", "simfang.ttf", ("fangsong", "仿宋")),
545
+ )
546
+
547
+
548
+ def _font_dir() -> Path:
549
+ """Windows 字体目录(WINDIR/Fonts)"""
550
+ return Path(os.environ.get("WINDIR", r"C:\Windows")) / "Fonts"
551
+
552
+
553
+ def _font_search_paths() -> list[str]:
554
+ """返回第一个存在的中文字体文件路径(均不存在时返回空列表)
555
+
556
+ 仅查询 Windows 字体目录下的常规中文字体(含 .ttc),供
557
+ `_fpdf_font_key` 兜底使用;正常情况返回单元素列表,调用方取第 0 项。
558
+ """
559
+ font_dir = _font_dir()
560
+ for _, filename, _ in _CN_FONT_TABLE:
561
+ fp = font_dir / filename
562
+ if fp.is_file():
563
+ return [str(fp)]
564
+ return []
565
+
566
+
567
+ def _fpdf_font_key(mainfont: str) -> tuple[str | None, str | None]:
568
+ """按 mainfont 名称匹配 fpdf2 可用的中文字体(fontfile + 注册名)
569
+
570
+ 返回 (字体文件绝对路径, fpdf2 add_font 注册名);名称先精确匹配别名,
571
+ 再做包含匹配(如 "SimSun-ExtB" 命中 SimSun),均未命中回退 SimSun。
572
+ 全部不可用时返回 (None, None)(PDF 将降级为 Helvetica,仅 ASCII 可读)。
573
+ """
574
+ lowered = mainfont.lower()
575
+ family: str | None = None
576
+ for name, _, aliases in _CN_FONT_TABLE:
577
+ if lowered in aliases:
578
+ family = name
579
+ break
580
+ if family is None:
581
+ # 包含匹配(不做反向的 lowered in alias,避免 "s" 等短名误命中)
582
+ for name, _, aliases in _CN_FONT_TABLE:
583
+ if any(alias in lowered for alias in aliases):
584
+ family = name
585
+ break
586
+ if family is None:
587
+ family = "SimSun"
588
+
589
+ font_dir = _font_dir()
590
+ for name, filename, _ in _CN_FONT_TABLE:
591
+ if name == family:
592
+ fp = font_dir / filename
593
+ if fp.is_file():
594
+ return (str(fp), family)
595
+ break
596
+ # 回退到任意已知存在的中文字体
597
+ pool = _font_search_paths()
598
+ if pool:
599
+ return (pool[0], Path(pool[0]).stem)
600
+ return (None, None)
601
+
602
+
603
+ # ---- 图片能力公共助手(PDF / Word / HTML 三格式共用)----
604
+
605
+ # 支持的图片后缀(Pillow 可读;SVG 不在此列,避免内嵌位图与外链面)
606
+ _IMAGE_SUFFIXES = frozenset({".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"})
607
+ # 图片自然尺寸统一按 96dpi 换算:fpdf2 仅在给定 w 时按 horz_dpi 反推高度,
608
+ # 与像素比、vert_dpi 均可能不一致;三格式统一基准并显式给出宽高可消除歧义。
609
+ _IMAGE_DPI = 96.0
610
+ _IMAGE_MM_PER_PX = 25.4 / _IMAGE_DPI
611
+ # Markdown 图片语法:alt 内不含 ],src 内不含括号与空白,可选 "title"
612
+ _MD_IMAGE_RE = re.compile(
613
+ r'!\[(?P<alt>[^\]\n]*)\]\((?P<src>[^()\s]*)(?:\s+"(?P<title>[^"\n]*)")?\)'
614
+ )
615
+ # Word/HTML 回填用的占位标记前缀(与原文撞车时改用备用前缀)
616
+ _MD_IMG_MARK = "@@MD2DOC-IMG-"
617
+ _MD_IMG_MARK_ALT = "@@MD2DOCX-IMG-"
618
+
619
+
620
+ def _resolve_local_image(src: str | None, base_dir: Path | None) -> Path | None:
621
+ """把 Markdown 图片 src 解析为 base_dir 子树内的本地文件路径
622
+
623
+ 仅接受本地相对路径:拒绝带 scheme 的地址(`http(s)://`、`data:`、
624
+ `file://`)、协议相对(`//host/x.png`)以及越出 base_dir 的路径
625
+ (`../`),后缀须在 `_IMAGE_SUFFIXES` 白名单内。任何不可用情况返回
626
+ None(调用方回落 alt 文本),不抛异常。
627
+
628
+ Args:
629
+ src: Markdown 图片语法中的目标地址
630
+ base_dir: 相对路径基准目录(通常为 Markdown 源文件所在目录)
631
+
632
+ Returns:
633
+ Path | None: 可读取的本地图片绝对路径;不可用返回 None
634
+ """
635
+ if not src or base_dir is None:
636
+ return None
637
+ raw = unquote(src.strip().strip("<>"))
638
+ # 剥离 query / fragment 后再判本地性(`images/a.png?t=1` 仍算本地)
639
+ raw = raw.split("#", 1)[0].split("?", 1)[0]
640
+ if not raw:
641
+ return None
642
+ parts = urlsplit(raw)
643
+ if parts.scheme or parts.netloc or raw.startswith("//"):
644
+ return None
645
+ try:
646
+ root = Path(base_dir).resolve()
647
+ path = (root / raw).resolve()
648
+ except OSError:
649
+ return None
650
+ if path.suffix.lower() not in _IMAGE_SUFFIXES:
651
+ return None
652
+ if not path.is_relative_to(root) or not path.is_file():
653
+ return None
654
+ return path
655
+
656
+
657
+ def _fit_size(
658
+ px_w: int, px_h: int, max_w: float, max_h: float
659
+ ) -> tuple[float, float] | None:
660
+ """按 96dpi 把像素尺寸换算为 mm,并用单一缩放因子同时满足宽高上限
661
+
662
+ 宽高同因子保证等比;不放大(scale ≤ 1)。宽高任一非正或上限非正时
663
+ 返回 None(调用方回落 alt 文本)。
664
+
665
+ Args:
666
+ px_w: 图片像素宽
667
+ px_h: 图片像素高
668
+ max_w: 可用宽度上限(mm)
669
+ max_h: 可用高度上限(mm)
670
+
671
+ Returns:
672
+ tuple[float, float] | None: (宽 mm, 高 mm);参数非法返回 None
673
+ """
674
+ if px_w <= 0 or px_h <= 0 or max_w <= 0 or max_h <= 0:
675
+ return None
676
+ nat_w = px_w * _IMAGE_MM_PER_PX
677
+ nat_h = px_h * _IMAGE_MM_PER_PX
678
+ scale = min(1.0, max_w / nat_w, max_h / nat_h)
679
+ return nat_w * scale, nat_h * scale
680
+
681
+
682
+ def _extract_images(markdown: str) -> tuple[str, list[tuple[str, str]]]:
683
+ """把 Markdown 图片语法替换为占位标记,供 Word / HTML 后处理回填
684
+
685
+ 返回 (改写后的 Markdown, [(src, alt), ...]),第 i 个标记为
686
+ `@@MD2DOC-IMG-{i}@@`(与原文撞车时改用 `@@MD2DOCX-IMG-{i}@@`)。
687
+
688
+ 与 `_normalize_cjk_bold` 同款状态机:围栏代码块、行内代码、GFM 表格块内
689
+ 一律不改写——代码示例中的 `![x](y)` 必须原样保留;表格单元格在 0.6.3
690
+ 中本就不解析行内 Markdown(图片语法以字面文本出现),本期维持该行为。
691
+ alt 内含 `]` 等不符合常规写法的图片语法不匹配,保持原样(即 0.6.3 的
692
+ alt 超链接降级行为),不做兜底改写。
693
+
694
+ Args:
695
+ markdown: 已完成 CJK 加粗预处理的 Markdown 文本
696
+
697
+ Returns:
698
+ tuple[str, list[tuple[str, str]]]: (改写后文本, [(src, alt), ...])
699
+ """
700
+ if "![" not in markdown:
701
+ return markdown, []
702
+
703
+ prefix = _MD_IMG_MARK
704
+ if prefix in markdown:
705
+ prefix = _MD_IMG_MARK_ALT
706
+ if prefix in markdown:
707
+ logger.warning(
708
+ "Markdown 已含图片占位标记前缀,跳过图片回填: "
709
+ f"{_MD_IMG_MARK!r} / {_MD_IMG_MARK_ALT!r}"
710
+ )
711
+ return markdown, []
712
+
713
+ refs: list[tuple[str, str]] = []
714
+ out_lines: list[str] = []
715
+ lines = markdown.splitlines(keepends=True)
716
+ in_fence = False
717
+ fence_marker = ""
718
+ in_table = False
719
+ for idx, line in enumerate(lines):
720
+ stripped = line.lstrip()
721
+ if not in_fence and (stripped.startswith("```") or stripped.startswith("~~~")):
722
+ in_fence = True
723
+ fence_marker = stripped[:3]
724
+ in_table = False
725
+ out_lines.append(line)
726
+ continue
727
+ if in_fence:
728
+ if stripped.startswith(fence_marker):
729
+ in_fence = False
730
+ out_lines.append(line)
731
+ continue
732
+ if in_table:
733
+ is_table = _is_table_row(line)
734
+ else:
735
+ is_table = (
736
+ _is_table_row(line)
737
+ and idx + 1 < len(lines)
738
+ and _is_table_delim(lines[idx + 1])
739
+ )
740
+ in_table = is_table
741
+ if is_table:
742
+ out_lines.append(line)
743
+ continue
744
+ # 行内代码段(1~3 个反引号包裹)保护:不做改写
745
+ segments = re.split(r"(`+[^`]*`+)", line)
746
+ pieces: list[str] = []
747
+ for seg in segments:
748
+ if seg.startswith("`"):
749
+ pieces.append(seg)
750
+ continue
751
+
752
+ def _sub(match: re.Match[str]) -> str:
753
+ refs.append((match.group("src"), match.group("alt")))
754
+ return f"{prefix}{len(refs) - 1}@@"
755
+
756
+ pieces.append(_MD_IMAGE_RE.sub(_sub, seg))
757
+ out_lines.append("".join(pieces))
758
+ return "".join(out_lines), refs
759
+
760
+
761
+ def _html_img_tag(src: str, alt: str) -> str:
762
+ """构造 `<img>` 标签:路径反斜杠归一为 `/`,src/alt 均做 HTML 转义"""
763
+ safe_src = _html_escape(src.replace("\\", "/"))
764
+ safe_alt = _html_escape(alt)
765
+ return f'<img src="{safe_src}" alt="{safe_alt}">'
766
+
767
+
768
+ def _inject_html_images(
769
+ html: str, refs: list[tuple[str, str]], base_dir: Path
770
+ ) -> str:
771
+ """把 HTML 中的图片占位标记替换为 `<figure><img>`(HTML 后处理)
772
+
773
+ PiMD(markdown-it)会把行内图片降级为 `<a href="src">alt</a>`,本函数按
774
+ 占位标记重建图片:
775
+
776
+ - 独立成段的标记 → `<figure class="md2doc-img"><img …></figure>`,整体
777
+ 替换 `<p>标记</p>`,避免出现 `<p><figure>` 非法嵌套;
778
+ - 段内混排(含 `[![x](y)](url)` 的链接内图片)→ 原位替换为 `<img>`;
779
+ - 本地图片不可用(缺失/越界/非白名单)→ 回落纯 alt 文本,不输出破图;
780
+ - 远程地址 → 输出 `<img src="https://…">` 交浏览器加载(服务端不取网)。
781
+
782
+ Args:
783
+ html: PiMD 转换后的完整 HTML 文本
784
+ refs: `_extract_images` 返回的 (src, alt) 序列
785
+ base_dir: 相对路径基准目录(Markdown 源文件所在目录)
786
+
787
+ Returns:
788
+ str: 替换后的 HTML 文本
789
+ """
790
+ for idx, (src, alt) in enumerate(refs):
791
+ marker = f"{_MD_IMG_MARK}{idx}@@"
792
+ if marker not in html:
793
+ marker = f"{_MD_IMG_MARK_ALT}{idx}@@"
794
+ if marker not in html:
795
+ continue
796
+ path = _resolve_local_image(src, base_dir)
797
+ parts = urlsplit(unquote(src.strip().strip("<>")))
798
+ is_remote = bool(parts.scheme or parts.netloc) or src.strip().startswith(
799
+ "//"
800
+ )
801
+ if path is not None:
802
+ rel = path.relative_to(Path(base_dir).resolve()).as_posix()
803
+ figure = (
804
+ f'<figure class="md2doc-img">{_html_img_tag(rel, alt)}</figure>'
805
+ )
806
+ inline = _html_img_tag(rel, alt)
807
+ elif is_remote:
808
+ figure = (
809
+ f'<figure class="md2doc-img">'
810
+ f"{_html_img_tag(src.strip(), alt)}</figure>"
811
+ )
812
+ inline = _html_img_tag(src.strip(), alt)
813
+ else:
814
+ figure = f"<p>{_html_escape(alt)}</p>" if alt else ""
815
+ inline = _html_escape(alt)
816
+ # 独立成段先整体替换,剩余(段内/链接内)标记再原位替换
817
+ html = re.sub(
818
+ r"<p>\s*" + re.escape(marker) + r"\s*</p>", lambda _m: figure, html
819
+ )
820
+ html = html.replace(marker, inline)
821
+ return html
822
+
823
+
824
+ class _PdfMarkdownRenderer:
825
+ """markdown-it token 流 → fpdf2 渲染器(与 convert_md_to_html 同源解析)
826
+
827
+ 与 HTML 版观感对齐:标题分级加粗、正文 11pt、表格撑满页宽表头灰底、
828
+ 引用块左侧竖线 + 灰字、行内代码灰底等宽、链接蓝色;嵌套列表逐层
829
+ 缩进(fpdf2 的 write 自动换行回到 left_margin,天然实现悬挂缩进)。
830
+ 行内样式经 pdf.write 流式切换字体渲染;表格单元格因需列内折行,
831
+ 改用 multi_cell(markdown=False)(纯文本,表头灰底深色维持加粗观感,
832
+ 规避 CJK 粗体字体未注册导致的崩溃)。
833
+ 行推进模型:fpdf2 的 write 结束后光标停在最后一行顶部(当前行高度
834
+ 未消费),凡经 write 渲染的块收尾必须 ln(整行高 + 块间隙),否则
835
+ 相邻文本行纵向重叠;multi_cell 系块(表格/代码块)收尾 y 已在块
836
+ 底部,其后 ln 仅为纯块间距。图片按块级独占一行绘制(等比限宽居中),
837
+ 块尾自行 ln(高度 + 间隙),其所在段落不再按文本行推进。
838
+
839
+ 图片仅渲染本地相对路径(基准为本 Markdown 源文件目录);缺图、越界、
840
+ 非白名单格式、远程地址一律回落为 alt 文本,保证导出可用。
841
+ """
842
+
843
+ _BODY_SIZE = 11
844
+ _TABLE_SIZE = 10
845
+ _HEADING_SIZES = {1: 18, 2: 15, 3: 13, 4: 12, 5: 12, 6: 11}
846
+ _BULLET_MARKS = ("•", "○") # GB2312 字库安全的项目符号
847
+ _QUOTE_TEXT_COLOR = (95, 95, 95)
848
+ _QUOTE_LINE_COLOR = (180, 180, 180)
849
+ _LINK_COLOR = (5, 99, 195)
850
+ _CODE_TEXT_COLOR = (51, 51, 51)
851
+ _CODE_BG_COLOR = (243, 244, 246)
852
+ _BORDER_COLOR = (204, 204, 204)
853
+ _HEAD_BG_COLOR = (240, 240, 240)
854
+ # 分页底限:与 set_auto_page_break(margin=20) 的 trigger 一致;
855
+ # 手动排版(表格/代码块)以同一阈值判断分页,避免越界
856
+ _BOTTOM_LIMIT = 20
857
+
858
+ def __init__(
859
+ self,
860
+ pdf: FPDF,
861
+ font_key: str | None,
862
+ has_cjk_font: bool,
863
+ base_dir: Path | None = None,
864
+ ) -> None:
865
+ self.pdf = pdf
866
+ self.font_key = font_key
867
+ self.has_cjk_font = has_cjk_font
868
+ # 图片相对路径基准目录;None 表示不渲染图片(等价 0.6.3 行为)
869
+ self.base_dir = base_dir
870
+ self._bold = False
871
+ self._italic = False
872
+ self._href: str | None = None
873
+ self._text_color: tuple[int, int, int] = (0, 0, 0)
874
+
875
+ # ---- 基础工具 ----
876
+
877
+ @property
878
+ def _family(self) -> str:
879
+ return self.font_key if self.has_cjk_font and self.font_key else "Helvetica"
880
+
881
+ def _style(self) -> str:
882
+ return ("B" if self._bold else "") + ("I" if self._italic else "")
883
+
884
+ def _line_h(self, size: int) -> float:
885
+ return size * 0.5
886
+
887
+ def _ensure_space(self, need: float) -> None:
888
+ """手动绘制前分页检查:剩余空间不足则换页"""
889
+ if self.pdf.get_y() + need > self.pdf.h - self._BOTTOM_LIMIT:
890
+ self.pdf.add_page()
891
+
892
+ def _avail_width(self) -> float:
893
+ """当前行可用宽度(从当前 x 到右边距)"""
894
+ return self.pdf.w - self.pdf.x - self.pdf.r_margin
895
+
896
+ # ---- 行内渲染(pdf.write 流式,样式即切即用)----
897
+
898
+ def _flow_run(self, text: str, size: int) -> None:
899
+ """流式写入文本,先在当前行剩余宽度内测宽排布;
900
+ 放不下则手动画行到左边缘(悬挂缩进),再交给 write 补齐文本。
901
+ write 对超长片段自带按词折行与翻页,二者结合避免内容越右边界。
902
+ """
903
+ if not text:
904
+ return
905
+ pdf = self.pdf
906
+ h = self._line_h(size)
907
+ while text:
908
+ pdf.set_font(self._family, self._style(), size)
909
+ # 整段宽度放得下直接整段写入(保持词间不折行)
910
+ if pdf.get_string_width(text) <= self._avail_width():
911
+ self._write_run(text, size)
912
+ return
913
+ # 找当前行能容纳的最长前缀(按字符累计宽度)
914
+ prefix = ""
915
+ width = 0.0
916
+ for ch in text:
917
+ width += pdf.get_string_width(ch)
918
+ if width > self._avail_width():
919
+ break
920
+ prefix += ch
921
+ if not prefix:
922
+ # 单个字符都放不下(极端窄列),直接交给 write 处理
923
+ self._write_run(text, size)
924
+ return
925
+ page_before = pdf.page_no()
926
+ self._write_run(prefix, size)
927
+ text = text[len(prefix) :]
928
+ if pdf.page_no() != page_before:
929
+ # writer 已触发翻页,剩余文本在新页顶部继续排
930
+ continue
931
+ pdf.ln(h)
932
+ pdf.set_x(pdf.l_margin)
933
+
934
+ def _write_run(self, text: str, size: int) -> None:
935
+ if not text:
936
+ return
937
+ pdf = self.pdf
938
+ pdf.set_font(self._family, self._style(), size)
939
+ color = self._LINK_COLOR if self._href else self._text_color
940
+ pdf.set_text_color(*color)
941
+ pdf.write(self._line_h(size), text, link=self._href or "")
942
+
943
+ def _render_code_span(self, content: str, size: int) -> None:
944
+ """行内代码:等宽小号 + 灰底(先画底色矩形再覆写文本)"""
945
+ pdf = self.pdf
946
+ code_size = max(size - 2, 8)
947
+ label = f" {content} "
948
+ pdf.set_font(self._family, "", code_size)
949
+ w = pdf.get_string_width(label)
950
+ h = self._line_h(size)
951
+ # 行内剩余宽度不足时先软换行到左边缘(保持悬挂缩进)
952
+ if w > self._avail_width():
953
+ pdf.ln(h)
954
+ pdf.set_x(pdf.l_margin)
955
+ x, y = pdf.get_x(), pdf.get_y()
956
+ pdf.set_fill_color(*self._CODE_BG_COLOR)
957
+ pdf.rect(x, y + 0.4, w + 2, h - 0.6, "F")
958
+ pdf.set_text_color(*self._CODE_TEXT_COLOR)
959
+ pdf.set_xy(x, y)
960
+ pdf.write(h, label, link=self._href or "")
961
+ pdf.set_text_color(*self._text_color)
962
+
963
+ def _render_inline(self, children: list[Token], size: int) -> bool:
964
+ """渲染行内 token 流;返回「末个有效 token 是否为块级图片」
965
+
966
+ 返回值供段落收尾判断:图片块已自行推进整行高,段落若再按文本行推进
967
+ 会多出约一个行高的空白;行内混排(文字 + 图片 + 文字)仍返回 False。
968
+
969
+ Args:
970
+ children: 行内 token 序列(paragraph/heading/list_item 内的 children)
971
+ size: 当前字号(pt)
972
+
973
+ Returns:
974
+ bool: 末个有效 token 是否为已绘制成功的块级图片
975
+ """
976
+ last_image = False
977
+ for tok in children:
978
+ t = tok.type
979
+ if t == "text":
980
+ self._flow_run(tok.content, size)
981
+ if tok.content.strip():
982
+ last_image = False
983
+ elif t == "softbreak":
984
+ self._write_run(" ", size)
985
+ last_image = False
986
+ elif t == "hardbreak":
987
+ self.pdf.ln(self._line_h(size))
988
+ self.pdf.set_x(self.pdf.l_margin)
989
+ last_image = False
990
+ elif t == "strong_open":
991
+ self._bold = True
992
+ elif t == "strong_close":
993
+ self._bold = False
994
+ elif t == "em_open":
995
+ self._italic = True
996
+ elif t == "em_close":
997
+ self._italic = False
998
+ elif t == "link_open":
999
+ self._href = tok.attrGet("href") or ""
1000
+ elif t == "link_close":
1001
+ self._href = None
1002
+ elif t == "code_inline":
1003
+ self._render_code_span(tok.content, size)
1004
+ last_image = False
1005
+ elif t == "image":
1006
+ last_image = self._render_image(tok, size)
1007
+ return last_image
1008
+
1009
+ def _render_image(self, tok: Token, size: int) -> bool:
1010
+ """块级图片:按正文可用宽限宽、等比居中绘制;不可用时回落 alt 文本
1011
+
1012
+ 图片独占一行(与 `_render_code_span` 的手动排版模型一致):当前行已有
1013
+ 内容先换行,剩余空间不足先分页,绘制后 `ln(高度 + 间隙)` 推进整行并
1014
+ 把光标复位到当前左边距(列表/引用块内自动跟随缩进)。
1015
+
1016
+ 宽高同时显式传给 fpdf2(`w`/`h`),不使用「只给 w 由 fpdf2 反推高度」
1017
+ 的方式——后者按 `horz_dpi` 换算,与像素比/`vert_dpi` 均可能不一致。
1018
+
1019
+ Args:
1020
+ tok: markdown-it 的 image token(`src` 属性 + alt 作为 content)
1021
+ size: 当前字号(pt),用于换行与回落文本排版
1022
+
1023
+ Returns:
1024
+ bool: 是否成功绘制图片(False 表示已回落为 alt 文本)
1025
+ """
1026
+ alt = tok.content or ""
1027
+ path = _resolve_local_image(tok.attrGet("src"), self.base_dir)
1028
+ if path is None:
1029
+ self._flow_run(alt, size)
1030
+ return False
1031
+ try:
1032
+ # 图片尺寸读取:Pillow 由 fpdf2 硬依赖提供,缺失时按不可用处理
1033
+ from PIL import Image
1034
+
1035
+ with Image.open(path) as image:
1036
+ px_w, px_h = image.size
1037
+ except Exception as e: # noqa: BLE001 - 缺 Pillow / 坏图统一回落
1038
+ logger.warning(f"图片不可读,回落为 alt 文本: {path.name}: {e}")
1039
+ self._flow_run(alt, size)
1040
+ return False
1041
+
1042
+ pdf = self.pdf
1043
+ avail_w = pdf.w - pdf.l_margin - pdf.r_margin
1044
+ max_h = pdf.h - pdf.t_margin - self._BOTTOM_LIMIT - 2
1045
+ fitted = _fit_size(px_w, px_h, avail_w, max_h)
1046
+ if fitted is None:
1047
+ self._flow_run(alt, size)
1048
+ return False
1049
+ width, height = fitted
1050
+
1051
+ if pdf.get_x() > pdf.l_margin:
1052
+ pdf.ln(self._line_h(size))
1053
+ self._ensure_space(height + 3)
1054
+ x = pdf.l_margin + (avail_w - width) / 2
1055
+ try:
1056
+ pdf.image(str(path), x=x, y=pdf.get_y(), w=width, h=height)
1057
+ except Exception as e: # noqa: BLE001 - 解码/格式异常统一回落
1058
+ logger.warning(f"图片渲染失败,回落为 alt 文本: {path.name}: {e}")
1059
+ self._flow_run(alt, size)
1060
+ return False
1061
+ pdf.ln(height + 3)
1062
+ return True
1063
+
1064
+ # ---- 块级渲染 ----
1065
+
1066
+ def render(self, tokens: list[Token]) -> None:
1067
+ self._render_blocks(tokens, 0)
1068
+
1069
+ def _render_blocks(
1070
+ self, tokens: list[Token], i: int, stop: str | None = None
1071
+ ) -> int:
1072
+ """顺序渲染块级 token 流;遇 stop 类型(如 blockquote_close)即返回"""
1073
+ n = len(tokens)
1074
+ while i < n:
1075
+ tok = tokens[i]
1076
+ t = tok.type
1077
+ if stop is not None and t == stop:
1078
+ return i
1079
+ if t == "paragraph_open":
1080
+ self._ensure_space(self._line_h(self._BODY_SIZE) * 2)
1081
+ ended_with_image = self._render_inline(
1082
+ tokens[i + 1].children or [], self._BODY_SIZE
1083
+ )
1084
+ # fpdf2 的 write 结束后光标停在最后一行顶部(未消费行高),
1085
+ # 须推进整行高结束该行,再加段间隙;只推进小间隙会与后文重叠。
1086
+ # 图片块已自行 ln(高度 + 间隙),此处只补段间隙,避免双倍留白。
1087
+ gap = 1.2 if ended_with_image else self._line_h(self._BODY_SIZE) + 1.2
1088
+ self.pdf.ln(gap)
1089
+ i += 3
1090
+ elif t.startswith("heading_"):
1091
+ level = int(tok.tag[1])
1092
+ self._render_heading(level, tokens[i + 1].children or [])
1093
+ i += 3
1094
+ elif t in ("bullet_list_open", "ordered_list_open"):
1095
+ i = self._render_list(tokens, i, 0)
1096
+ elif t == "blockquote_open":
1097
+ i = self._render_blockquote(tokens, i)
1098
+ elif t == "fence":
1099
+ self._render_fence(tok)
1100
+ i += 1
1101
+ elif t == "table_open":
1102
+ i = self._render_table(tokens, i)
1103
+ elif t == "hr":
1104
+ self._render_hr()
1105
+ i += 1
1106
+ else:
1107
+ i += 1
1108
+ return i
1109
+
1110
+ def _render_heading(self, level: int, children: list[Token]) -> None:
1111
+ size = self._HEADING_SIZES.get(level, self._BODY_SIZE)
1112
+ self._ensure_space(size * 1.8)
1113
+ self.pdf.ln(2)
1114
+ saved_bold = self._bold
1115
+ self._bold = True # 对齐 HTML:h1~h6 均 font-weight 600
1116
+ self._render_inline(children, size)
1117
+ self._bold = saved_bold
1118
+ self.pdf.ln(self._line_h(size) + 1.5)
1119
+
1120
+ def _render_hr(self) -> None:
1121
+ self._ensure_space(6)
1122
+ pdf = self.pdf
1123
+ pdf.set_draw_color(230, 230, 230)
1124
+ pdf.set_line_width(0.4)
1125
+ y = pdf.get_y() + 1.5
1126
+ pdf.line(pdf.l_margin, y, pdf.w - pdf.r_margin, y)
1127
+ pdf.ln(4)
1128
+
1129
+ def _render_fence(self, tok: Token) -> None:
1130
+ """代码块:等宽 9pt + 行首缩进 2mm,长行先折再逐行输出
1131
+
1132
+ 对齐 HTML 的 pre 样式中的等宽字体;**不绘制浅灰背景**(fpdf2 下
1133
+ 背景矩形需与折行、分页联动,当前版本未实现,属与 HTML 观感的已知
1134
+ 差异)。每行先按可用宽度折行成片段,再逐段 multi_cell;页底不足时
1135
+ add_page 续排(同一逻辑行的续段在新页顶部继续,代码不错位)。
1136
+ """
1137
+ pdf = self.pdf
1138
+ code_size = 9
1139
+ line_h = 5
1140
+ self._ensure_space(line_h * 2)
1141
+ pdf.ln(1)
1142
+ code_bottom = pdf.h - self._BOTTOM_LIMIT
1143
+ for cl in tok.content.rstrip("\n").splitlines():
1144
+ if not cl:
1145
+ pdf.set_x(pdf.l_margin + 2)
1146
+ pdf.ln(line_h)
1147
+ continue
1148
+ # 长行按可用宽度折成多段(一次测宽,避免 multi_cell 内部换行打乱对齐)
1149
+ chunks: list[str] = []
1150
+ rest = cl
1151
+ while rest and pdf.get_string_width(rest) > self._avail_width():
1152
+ width = 0
1153
+ split_at = len(rest)
1154
+ for idx, ch in enumerate(rest):
1155
+ width += pdf.get_string_width(ch)
1156
+ if width > self._avail_width():
1157
+ split_at = idx
1158
+ break
1159
+ chunks.append(rest[:split_at])
1160
+ rest = rest[split_at:]
1161
+ if rest:
1162
+ chunks.append(rest)
1163
+ for c in chunks:
1164
+ if pdf.get_y() + line_h > code_bottom:
1165
+ pdf.add_page()
1166
+ pdf.set_x(pdf.l_margin + 2)
1167
+ pdf.set_font(self._family, "", code_size)
1168
+ pdf.multi_cell(0, line_h, c)
1169
+ pdf.ln(3)
1170
+
1171
+ def _render_blockquote(self, tokens: list[Token], i: int) -> int:
1172
+ pdf = self.pdf
1173
+ prev_left = pdf.l_margin
1174
+ left = prev_left + 8
1175
+ start_page = pdf.page_no()
1176
+ self._ensure_space(self._line_h(self._BODY_SIZE) * 2)
1177
+ y0 = pdf.get_y()
1178
+ pdf.set_left_margin(left)
1179
+ pdf.set_x(left)
1180
+ saved_color = self._text_color
1181
+ self._text_color = self._QUOTE_TEXT_COLOR
1182
+ i = self._render_blocks(tokens, i + 1, stop="blockquote_close")
1183
+ pdf.set_left_margin(prev_left)
1184
+ self._text_color = saved_color
1185
+ y1 = pdf.get_y()
1186
+ # 左侧竖线(跨页引用仅绘制续页段,避免在旧页坐标误画)
1187
+ pdf.set_draw_color(*self._QUOTE_LINE_COLOR)
1188
+ pdf.set_line_width(0.6)
1189
+ if pdf.page_no() == start_page:
1190
+ pdf.line(left - 2.5, y0 + 0.5, left - 2.5, max(y1 - 1, y0 + 1.5))
1191
+ else:
1192
+ pdf.line(
1193
+ left - 2.5, pdf.t_margin, left - 2.5, max(y1 - 1, pdf.t_margin + 1.5)
1194
+ )
1195
+ pdf.ln(2)
1196
+ return min(i + 1, len(tokens))
1197
+
1198
+ def _render_list(self, tokens: list[Token], i: int, depth: int) -> int:
1199
+ open_tok = tokens[i]
1200
+ ordered = open_tok.type == "ordered_list_open"
1201
+ try:
1202
+ idx = int(open_tok.attrGet("start") or 1)
1203
+ except (TypeError, ValueError):
1204
+ idx = 1
1205
+ n = len(tokens)
1206
+ i += 1
1207
+ while i < n:
1208
+ tok = tokens[i]
1209
+ t = tok.type
1210
+ if t in ("bullet_list_close", "ordered_list_close"):
1211
+ return i + 1
1212
+ if t == "list_item_open":
1213
+ if ordered:
1214
+ marker = f"{idx}."
1215
+ idx += 1
1216
+ else:
1217
+ marker = self._BULLET_MARKS[depth % len(self._BULLET_MARKS)]
1218
+ i = self._render_list_item(tokens, i + 1, depth, marker)
1219
+ continue
1220
+ i += 1
1221
+ return i
1222
+
1223
+ def _render_list_item(
1224
+ self, tokens: list[Token], i: int, depth: int, marker: str
1225
+ ) -> int:
1226
+ pdf = self.pdf
1227
+ n = len(tokens)
1228
+ prev_left = pdf.l_margin
1229
+ left = prev_left + 6 * (depth + 1)
1230
+ pdf.set_left_margin(left)
1231
+ # 项目符号悬挂在缩进左侧
1232
+ pdf.set_x(left - 6)
1233
+ pdf.set_font(self._family, "", self._BODY_SIZE)
1234
+ pdf.set_text_color(*self._text_color)
1235
+ pdf.cell(
1236
+ pdf.get_string_width(marker) + 1.5, self._line_h(self._BODY_SIZE), marker
1237
+ )
1238
+ first_para = True
1239
+ while i < n and tokens[i].type != "list_item_close":
1240
+ tok = tokens[i]
1241
+ t = tok.type
1242
+ if t == "paragraph_open":
1243
+ if not first_para:
1244
+ self._ensure_space(self._line_h(self._BODY_SIZE) * 2)
1245
+ pdf.set_x(left)
1246
+ ended_with_image = self._render_inline(
1247
+ tokens[i + 1].children or [], self._BODY_SIZE
1248
+ )
1249
+ # write 后光标停在最后一行顶部:推进整行高 + 项内段间隙,
1250
+ # 保证下一列表项/段落不与本项末行重叠;图片块已自行推进,
1251
+ # 此处只补项内段间隙。
1252
+ pdf.ln(0.8 if ended_with_image else self._line_h(self._BODY_SIZE) + 0.8)
1253
+ first_para = False
1254
+ i += 3
1255
+ continue
1256
+ if t in ("bullet_list_open", "ordered_list_open"):
1257
+ pdf.ln(self._line_h(self._BODY_SIZE) * 0.3)
1258
+ i = self._render_list(tokens, i, depth + 1)
1259
+ continue
1260
+ if t == "fence":
1261
+ pdf.ln(1)
1262
+ self._render_fence(tok)
1263
+ i += 1
1264
+ continue
1265
+ if t == "blockquote_open":
1266
+ i = self._render_blockquote(tokens, i)
1267
+ continue
1268
+ i += 1
1269
+ pdf.set_left_margin(prev_left)
1270
+ # 行推进已由项内段落/嵌套块按"整行高+间隙"收尾,此处不再额外
1271
+ # 推进(原 ln(2) 在 write 行模型下是列表项纵向重叠的根因)
1272
+ return min(i + 1, n)
1273
+
1274
+ def _render_table(self, tokens: list[Token], i: int) -> int:
1275
+ """收集 thead/tbody 行列后交由 _draw_table 绘制"""
1276
+ header: list[list[Token]] = []
1277
+ body: list[list[list[Token]]] = []
1278
+ n = len(tokens)
1279
+ i += 1 # 跳过 table_open
1280
+ while i < n and tokens[i].type != "table_close":
1281
+ if tokens[i].type != "tr_open":
1282
+ i += 1
1283
+ continue
1284
+ cells: list[list[Token]] = []
1285
+ has_th = False
1286
+ i += 1
1287
+ while i < n and tokens[i].type != "tr_close":
1288
+ if tokens[i].type in ("th_open", "td_open"):
1289
+ has_th = has_th or tokens[i].type == "th_open"
1290
+ cells.append(tokens[i + 1].children or [])
1291
+ i += 3
1292
+ continue
1293
+ i += 1
1294
+ i += 1 # tr_close
1295
+ if not cells:
1296
+ continue
1297
+ if has_th and not header:
1298
+ header = cells
1299
+ else:
1300
+ body.append(cells)
1301
+ i += 1 # table_close
1302
+ self._draw_table(header, body)
1303
+ return i
1304
+
1305
+ @staticmethod
1306
+ def _inline_to_pdf_text(children: list[Token]) -> str:
1307
+ """行内 token → 纯文本(表格单元格用)
1308
+
1309
+ 仅保留文本/软换行/硬换行/行内代码/图片 alt;链接取文字、粗斜体
1310
+ 标记剥除(表头灰底深色维持加粗观感,不依赖字形切换)。返回文本
1311
+ 保证不触发 fpdf2 markdown 解析(`**` 定界符在 CJK 场景会请求
1312
+ 未注册的粗体字体名导致崩溃)。
1313
+ """
1314
+ parts: list[str] = []
1315
+ for tok in children:
1316
+ t = tok.type
1317
+ if t == "text":
1318
+ parts.append(tok.content)
1319
+ elif t == "softbreak":
1320
+ parts.append(" ")
1321
+ elif t == "hardbreak":
1322
+ parts.append("\n")
1323
+ elif t in ("code_inline", "image"):
1324
+ parts.append(tok.content or "")
1325
+ return "".join(parts).strip()
1326
+
1327
+ def _draw_table(
1328
+ self, header: list[list[Token]], body: list[list[list[Token]]]
1329
+ ) -> None:
1330
+ """自适应列宽表格:表头灰底加粗、单元格边框换行、撑满页宽
1331
+
1332
+ 列宽按内容自适应:优先给每列最长单元文本宽度,总宽不足时按比例
1333
+ 缩放,最小列宽保护;行高由 dry_run 预演得出(纯文本,markdown=False,
1334
+ 故 markdown 标记不参与折行计算),保证边框与文字不脱节;跨页时
1335
+ 新页重绘表头。
1336
+ """
1337
+ pdf = self.pdf
1338
+ if not header:
1339
+ return
1340
+ ncols = len(header)
1341
+ rows: list[tuple[bool, list[list[Token]]]] = [(True, header)]
1342
+ rows.extend((False, r) for r in body)
1343
+ # --- 列宽分配:按内容自适应(表头 + 全部数据行)---
1344
+ avail = pdf.w - pdf.l_margin - pdf.r_margin
1345
+ pdf.set_font(self._family, "", self._TABLE_SIZE)
1346
+ # 最小列宽保护:至少容纳 4 个全角字符(防长文列被压成一字一行
1347
+ # 竖排);列数过多时以页宽均分为上限
1348
+ min_col_w = min(pdf.get_string_width("中" * 4) + 2.4, avail / ncols)
1349
+ widths: list[float] = []
1350
+ for ci in range(ncols):
1351
+ max_w = min_col_w
1352
+ for is_head, row in rows:
1353
+ if ci < len(row) and row[ci]:
1354
+ marked = self._inline_to_pdf_text(row[ci])
1355
+ max_w = max(max_w, pdf.get_string_width(marked))
1356
+ widths.append(max_w)
1357
+ total_w = sum(widths)
1358
+ if total_w > avail:
1359
+ scale = avail / total_w
1360
+ widths = [w * scale for w in widths]
1361
+ else:
1362
+ # 富余量按列均摊(保持撑满页宽,列宽更均匀)
1363
+ bonus = (avail - total_w) / ncols
1364
+ widths = [w + bonus for w in widths]
1365
+ # --- 逐行绘制(跨页时新页重绘表头)---
1366
+ for is_head, row in rows:
1367
+ row = row + [[]] * (ncols - len(row))
1368
+ row_h = self._row_height(row, widths)
1369
+ # 本页放不下(且当前不在页首)→ 翻页;非表头行翻页后重绘表头
1370
+ if (
1371
+ pdf.get_y() + row_h > pdf.h - self._BOTTOM_LIMIT
1372
+ and pdf.get_y() > pdf.t_margin
1373
+ ):
1374
+ pdf.add_page()
1375
+ if not is_head:
1376
+ header_row = header + [[]] * (ncols - len(header))
1377
+ self._paint_row(
1378
+ header_row,
1379
+ widths,
1380
+ self._row_height(header_row, widths),
1381
+ is_header=True,
1382
+ )
1383
+ self._paint_row(row, widths, row_h, is_header=is_head)
1384
+ pdf.ln(3)
1385
+
1386
+ def _row_height(self, row: list[list[Token]], widths: list[float]) -> float:
1387
+ """行高预演:dry_run 按纯文本折行数 → 行高(markdown=False)"""
1388
+ pdf = self.pdf
1389
+ row_lines: list[int] = []
1390
+ for ci, cell in enumerate(row):
1391
+ pdf.set_font(self._family, "", self._TABLE_SIZE)
1392
+ out = pdf.multi_cell(
1393
+ widths[ci] - 2.4,
1394
+ 5,
1395
+ self._inline_to_pdf_text(cell),
1396
+ markdown=False,
1397
+ dry_run=True,
1398
+ output="LINES",
1399
+ )
1400
+ row_lines.append(len(out) if isinstance(out, list) else 1)
1401
+ return max(row_lines) * 5 + 2.4 if row_lines else 8
1402
+
1403
+ def _paint_row(
1404
+ self,
1405
+ row: list[list[Token]],
1406
+ widths: list[float],
1407
+ row_h: float,
1408
+ *,
1409
+ is_header: bool,
1410
+ ) -> None:
1411
+ """绘制单行:表头灰底整行填充 + 单元格边框与纯文本内容
1412
+
1413
+ 表头灰底宽度取 `sum(widths)`(列宽分配后恒等于可用页宽),无需外部
1414
+ 传入可用宽度;跨页重绘表头复用本方法。
1415
+ """
1416
+ pdf = self.pdf
1417
+ y0 = pdf.get_y()
1418
+ if is_header:
1419
+ pdf.set_fill_color(*self._HEAD_BG_COLOR)
1420
+ pdf.rect(pdf.l_margin, y0, sum(widths), row_h, "F")
1421
+ pdf.set_draw_color(*self._BORDER_COLOR)
1422
+ pdf.set_line_width(0.2)
1423
+ x0 = pdf.l_margin
1424
+ for ci, cell in enumerate(row):
1425
+ pdf.rect(x0, y0, widths[ci], row_h)
1426
+ pdf.set_xy(x0 + 1.2, y0 + 0.8)
1427
+ pdf.set_font(self._family, "", self._TABLE_SIZE)
1428
+ pdf.multi_cell(
1429
+ widths[ci] - 2.4, 5, self._inline_to_pdf_text(cell), markdown=False
1430
+ )
1431
+ x0 += widths[ci]
1432
+ pdf.set_y(y0 + row_h)
1433
+
1434
+
1435
+ def _pdf_render_markdown(
1436
+ md_text: str, dest: Path, mainfont: str, base_dir: Path | None = None
1437
+ ) -> None:
1438
+ """markdown-it token 流驱动 fpdf2 渲染 Markdown 为 PDF(与 HTML 同源解析)
1439
+
1440
+ - 解析:MarkdownIt(commonmark)+table,与 convert_md_to_html(PiMD 内部
1441
+ 同为 markdown-it)结构理解一致;支持标题、嵌套列表(有序/无序)、
1442
+ 引用块、围栏代码块、GFM 表格、分隔线,及行内粗体/斜体/行内代码/
1443
+ 链接/图片。
1444
+ - 图片:`base_dir` 为相对路径基准(调用方传 Markdown 源文件目录),
1445
+ 渲染为等比限宽居中的块级图片;缺图/越界/远程一律回落 alt 文本。
1446
+ `base_dir=None` 时不解析图片,行为与 0.6.3 完全一致。
1447
+ - 中文不可走 PiMD 自带 PDF 通道:其 PDF 引擎为回退链(docx2pdf →
1448
+ libreoffice → pandoc → weasyprint → fpdf2),末端 fpdf2 实现为
1449
+ Helvetica 文本提取,均不支持 CJK;本渲染器按 mainfont 注册系统
1450
+ CJK 字体(B/I/BI 同文件注册,未注册样式在 set_font 时直接抛错),
1451
+ 保证中文完整落盘。
1452
+ - 布局对齐 convert_md_to_html 的宽版式观感:A4 纵向、正文 11pt、
1453
+ h1~h6 分级加粗、表格撑满页宽表头灰底、引用块左竖线灰字、链接蓝色。
1454
+ """
1455
+ font_path, font_key = _fpdf_font_key(mainfont)
1456
+ if font_path is None:
1457
+ logger.warning(
1458
+ f"未找到中文字体(mainfont={mainfont}),"
1459
+ "PDF 将使用 Helvetica(仅 ASCII 可读)"
1460
+ )
1461
+
1462
+ pdf = FPDF(format="A4")
1463
+ pdf.set_auto_page_break(auto=True, margin=20)
1464
+ pdf.add_page()
1465
+ if font_path is not None:
1466
+ # Unicode 中文字体无真实粗/斜变体:B/I/BI 均注册同一字形
1467
+ for style in ("", "B", "I", "BI"):
1468
+ pdf.add_font(font_key, style, font_path)
1469
+
1470
+ tokens = _MD_PARSER.parse(md_text)
1471
+ renderer = _PdfMarkdownRenderer(
1472
+ pdf, font_key, font_path is not None, base_dir=base_dir
1473
+ )
1474
+ renderer.render(tokens)
1475
+ pdf.output(str(dest))
1476
+
1477
+
1478
+ def _is_table_row(line: str) -> bool:
1479
+ """GFM 表格行:以竖线开头/结尾,或含 ` | ` 分隔的多列(单列表格
1480
+ 仅两端各一条竖线,不能按中间竖线判定)
1481
+
1482
+ 注意:本判定对正文偏宽(正文中的竖线也可能命中),因此仅供"表格块内"
1483
+ 使用——`_normalize_cjk_bold` 先用 `_is_table_delim` 确认表格块起点,
1484
+ 块外的行一律按普通文本处理。
1485
+ """
1486
+ s = line.strip()
1487
+ if not s:
1488
+ return False
1489
+ return s.startswith("|") or s.endswith("|") or " | " in s
1490
+
1491
+
1492
+ def _is_table_delim(line: str) -> bool:
1493
+ """GFM 表格分隔行(如 `| --- | --- |`):仅由 `-`、`:`、`|` 与空白组成,
1494
+ 且同时含竖线与连字符(据此排除 setext 标题下划线与 `---` 分隔线)"""
1495
+ s = line.strip()
1496
+ if "|" not in s or "-" not in s:
1497
+ return False
1498
+ return re.fullmatch(r"[\s|:-]+", s) is not None
1499
+
1500
+
1501
+ def _resolve_md_paths(
1502
+ src_path: str | Path,
1503
+ dest_path: str | Path | None,
1504
+ suffix: str,
1505
+ ) -> tuple[Path, Path]:
1506
+ """校验 Markdown 源文件并解析目标路径(三个 convert_md_to_* 共用)
1507
+
1508
+ 目标为 None 时取源文件同目录同名的 `suffix` 文件;显式给定时 resolve 为
1509
+ 绝对路径(非严格模式,目标可不存在)并确保父目录存在。
1510
+
1511
+ Raises:
1512
+ FileNotFoundError: 源文件不存在
1513
+ ValueError: 源文件不是常规文件或扩展名不是 .md
1514
+ """
1515
+ src = Path(src_path).resolve()
1516
+ if not src.exists():
1517
+ raise FileNotFoundError(f"文件不存在: {src}")
1518
+ if not src.is_file():
1519
+ raise ValueError(f"路径不是有效文件: {src}")
1520
+ if src.suffix.lower() != ".md":
1521
+ raise ValueError(
1522
+ "源文件必须是 .md 后缀的 Markdown 文件,"
1523
+ f"当前: {src.suffix or '<无扩展名>'}"
1524
+ )
1525
+
1526
+ if dest_path is None:
1527
+ dest = src.with_suffix(suffix)
1528
+ else:
1529
+ # resolve 保证返回值兑现"绝对路径"承诺(非严格模式,目标可不存在)
1530
+ dest = Path(dest_path).resolve()
1531
+ dest.parent.mkdir(parents=True, exist_ok=True)
1532
+ return src, dest
1533
+
1534
+
1535
+ class Md2DocKit:
1536
+ """Markdown 渲染工具类,将 Markdown 转换为 Word(.docx)/PDF/HTML
1537
+
1538
+ 基于 PiMD(markdown-it 解析 + python-docx 渲染)与内嵌 fpdf2 渲染器,
1539
+ 支持 GFM 全语法:标题、列表、表格(表头样式)、代码块、链接、引用块等。
1540
+
1541
+ 使用方式:
1542
+ # 1. Markdown 转 PDF(基于本模块内嵌 fpdf2 渲染器,支持中文)
1543
+ Md2DocKit.convert_md_to_pdf("report.md") # 同目录 report.pdf
1544
+ Md2DocKit.convert_md_to_pdf("report.md", mainfont="KaiTi")
1545
+
1546
+ # 2. Markdown 转 Word(基于 PiMD 默认主题 + 表格撑满后处理)
1547
+ Md2DocKit.convert_md_to_docx("report.md") # 同目录 report.docx
1548
+ Md2DocKit.convert_md_to_docx("report.md", "out.docx", generate_toc=True)
1549
+
1550
+ # 3. Markdown 转 HTML(基于 PiMD + 宽版式样式注入)
1551
+ Md2DocKit.convert_md_to_html("report.md") # 同目录 report.html
1552
+ Md2DocKit.convert_md_to_html("report.md", title="项目报告")
1553
+
1554
+ 注意:convert_md_to_pdf 为**实验性/内部使用,不提供对外服务**(见
1555
+ convert_md_to_pdf 方法说明);需要 PDF 时优先用 convert_md_to_html
1556
+ 后在浏览器中打印/另存 PDF,或 convert_md_to_docx 后在 Word 中另存 PDF。
1557
+
1558
+ 各类文档(Office/PDF)→ Markdown 的正向解析见 yimo.kit.docs.anydoc_kit(AnyDocKit)。
1559
+ 可与 FileKit 组合使用以访问 FILE_STORAGE_ROOT 下的相对路径文件:
1560
+ full_path = FileKit.get_full_path("docs/report.md")
1561
+ Md2DocKit.convert_md_to_html(full_path)
1562
+ """
1563
+
1564
+ @staticmethod
1565
+ def convert_md_to_pdf(
1566
+ src_path: str | Path,
1567
+ dest_path: str | Path | None = None,
1568
+ *,
1569
+ mainfont: str = "SimSun",
1570
+ ) -> str:
1571
+ """将 Markdown 文件转换为 PDF 文件(基于本模块内嵌 fpdf2 渲染器)
1572
+
1573
+ ⚠️ **实验性/内部使用,不提供对外服务**:本方法效果受 fpdf2 能力
1574
+ 局限(CJK 无真实粗/斜体变体、复杂长表格视觉打折),不保证排版
1575
+ 质量,不承诺对外服务。**外部需要 PDF 时请改用以下路径**:
1576
+ - 推荐:`convert_md_to_html(...)` 后在浏览器中打印/另存 PDF;
1577
+ - 或 `convert_md_to_docx(...)` 后在 Word 中另存 PDF。
1578
+ 本方法仅供内部试验,排版效果随 fpdf2 能力浮动、波动属预期;
1579
+ 为兼容既有内部调用,方法签名保持稳定(不删参数、不改名)。
1580
+
1581
+ PiMD 内置 PDF 引擎(Helvetica 文本提取)不支持中文,故 PDF 由本
1582
+ 模块 fpdf2 渲染器直接生成:与 convert_md_to_html 同源解析
1583
+ (markdown-it token 流),渲染效果向 HTML 版对齐——支持标题、
1584
+ 嵌套列表(有序/无序)、引用块、表格(表头灰底加粗)、围栏代码块、
1585
+ 分隔线及行内粗体/斜体/行内代码/链接;按 mainfont 匹配 Windows
1586
+ 系统中文字体并注册为 unicode 子集字体,中文文档默认宋体。
1587
+ 排版默认值:A4 纵向、正文 11pt、h1~h6 分级加粗、表格撑满页宽、
1588
+ 单元格换行、多页自适应分页。
1589
+
1590
+ 图片(`![alt](相对路径)`)渲染为块级图片:相对路径以本 Markdown
1591
+ 源文件所在目录为基准,按 96dpi 还原自然尺寸后等比限宽居中,超高
1592
+ 先分页、不放大;缺图、越界路径、非图片格式、远程地址一律回落为
1593
+ alt 文本,不抛异常。表格单元格内的图片仍按 alt 文本处理。
1594
+
1595
+ 转换前自动做 CJK 加粗预处理(详见 convert_md_to_docx)。
1596
+
1597
+ Args:
1598
+ src_path: Markdown 源文件路径(支持 str 或 Path)
1599
+ dest_path: 目标 PDF 路径;None 时使用源文件名同目录加 .pdf 后缀
1600
+ mainfont: 正文字体族名,默认 SimSun(需系统已安装该字体)
1601
+
1602
+ Returns:
1603
+ str: 实际写入的 PDF 文件绝对路径
1604
+
1605
+ Raises:
1606
+ FileNotFoundError: 源文件不存在
1607
+ ValueError: 源文件不是常规文件或扩展名不是 .md
1608
+ OSError: 文件读写失败
1609
+ RuntimeError: PDF 渲染失败
1610
+
1611
+ Example:
1612
+ >>> Md2DocKit.convert_md_to_pdf("report.md") # 生成同目录 report.pdf
1613
+ >>> Md2DocKit.convert_md_to_pdf("report.md", mainfont="KaiTi")
1614
+ """
1615
+ src, dest = _resolve_md_paths(src_path, dest_path, ".pdf")
1616
+ logger.info(f"开始转换 Markdown 为 PDF: {src.name}")
1617
+
1618
+ # CJK 加粗预处理;fpdf2 渲染器直接读内存文本,无需落盘临时 md
1619
+ processed = _normalize_cjk_bold(src.read_text(encoding="utf-8"))
1620
+
1621
+ try:
1622
+ # 图片相对路径基准 = 源文件目录(与 images/ 同级导出结构天然匹配)
1623
+ _pdf_render_markdown(processed, dest, mainfont, src.parent)
1624
+ except Exception as e: # noqa: BLE001 - fpdf2 渲染异常统一包装
1625
+ logger.error(f"PDF 渲染失败: {src.name}: {e}")
1626
+ raise RuntimeError(f"PDF 渲染失败: {src.name}: {e}") from e
1627
+
1628
+ logger.info(f"✅ PDF 生成成功: {dest}")
1629
+ return str(dest)
1630
+
1631
+ @staticmethod
1632
+ def convert_md_to_html(
1633
+ src_path: str | Path,
1634
+ dest_path: str | Path | None = None,
1635
+ *,
1636
+ title: str | None = None,
1637
+ ) -> str:
1638
+ """将 Markdown 文件转换为独立 HTML 文件(基于 PiMD)
1639
+
1640
+ PiMD 输出完整 HTML5 文档(自带 <meta charset> 与默认样式),支持
1641
+ GFM 全部语法;默认不注入页面标题(PiMD 默认无 <title> 标签,源
1642
+ 文件名不会出现在头部),页面标题直接使用 Markdown 自身的一级标题,
1643
+ 也可通过 title 参数显式指定。
1644
+ 默认内嵌宽版式排版样式(_MD_HTML_CSS),替代 PiMD 自带默认样式
1645
+ (body `max-width: 900px` 等):正文容器放大至 60em 并居中,中文
1646
+ 优先字体栈(宋体系/黑体系),表格撑满页宽、表头加粗,适配宽屏阅读。
1647
+
1648
+ 图片(`![alt](相对路径)`)输出为 `<figure class="md2doc-img"><img>`:
1649
+ 本地路径以源文件所在目录为基准判定存在性,存在则输出**相对路径**
1650
+ (故 HTML 需与 `images/` 处于同一目录层级才能在浏览器中正常显示);
1651
+ 缺图/越界回落为 alt 文本(不输出破图);远程地址直接输出
1652
+ `<img src="https://…">` 交由浏览器加载(服务端不取网)。
1653
+
1654
+ 转换前自动做 CJK 加粗预处理(详见 convert_md_to_docx)。
1655
+
1656
+ Args:
1657
+ src_path: Markdown 源文件路径(支持 str 或 Path)
1658
+ dest_path: 目标 HTML 路径;None 时使用源文件名同目录加 .html 后缀
1659
+ title: 页面标题;None(默认)表示不注入标题,使用 Markdown 自身
1660
+ 一级标题;传入字符串则以此为页面标题
1661
+
1662
+ Returns:
1663
+ str: 实际写入的 HTML 文件绝对路径
1664
+
1665
+ Raises:
1666
+ FileNotFoundError: 源文件不存在
1667
+ ValueError: 源文件不是常规文件或扩展名不是 .md
1668
+ OSError: 文件读写失败
1669
+ RuntimeError: HTML 渲染失败
1670
+
1671
+ Example:
1672
+ >>> Md2DocKit.convert_md_to_html("report.md") # 生成同目录 report.html
1673
+ >>> Md2DocKit.convert_md_to_html("report.md", title="项目报告")
1674
+ """
1675
+ src, dest = _resolve_md_paths(src_path, dest_path, ".html")
1676
+ logger.info(f"开始转换 Markdown 为 HTML: {src.name}")
1677
+
1678
+ # CJK 加粗预处理;临时 md 与源文件同目录,保证相对图片路径仍然可用
1679
+ processed = _normalize_cjk_bold(src.read_text(encoding="utf-8"))
1680
+ # 图片语法先换占位标记(PiMD 会把它降级为 alt 超链接),转换后回填
1681
+ processed, img_refs = _extract_images(processed)
1682
+ tmp_md = src.with_name(f".{src.stem}.pimd-tmp.md")
1683
+ tmp_md.write_text(processed, encoding="utf-8")
1684
+
1685
+ try:
1686
+ _PIMD.convert(tmp_md, "html", str(dest))
1687
+ except ConversionError as e:
1688
+ logger.error(f"HTML 渲染失败: {src.name}: {e}")
1689
+ raise RuntimeError(f"HTML 渲染失败: {src.name}: {e}") from e
1690
+ except OSError as e: # noqa: BLE001 - 文件读写异常统一包装
1691
+ logger.error(f"HTML 渲染失败: {src.name}: {e}")
1692
+ raise RuntimeError(f"HTML 渲染失败: {src.name}: {e}") from e
1693
+ finally:
1694
+ tmp_md.unlink(missing_ok=True)
1695
+
1696
+ # 转换后注入:PiMD 输出完整 HTML5 文档(自带 <style>),在 </head>
1697
+ # 前插入 _MD_HTML_CSS 覆盖其默认窄栏与配色
1698
+ html = dest.read_text(encoding="utf-8")
1699
+ if title is not None and "<title>" not in html:
1700
+ # PiMD 默认不输出 <title>;显式传 title 时才补写,页面标题
1701
+ # 默认使用 Markdown 自身的一级标题。不依赖 <head> 字面形态,
1702
+ # 统一在 </head> 前插入(缺失 </head> 时记 warning 并跳过)
1703
+ head_close = html.find("</head>")
1704
+ if head_close == -1:
1705
+ logger.warning(f"HTML 缺少 </head>,跳过标题注入: {dest}")
1706
+ else:
1707
+ html = (
1708
+ f"{html[:head_close]}<title>{title}</title>\n"
1709
+ f"{html[head_close:]}"
1710
+ )
1711
+ html = html.replace("</head>", f"{_MD_HTML_CSS}\n</head>", 1)
1712
+ # 图片回填:把占位标记还原为 <figure><img>(缺图回落 alt 文本)
1713
+ if img_refs:
1714
+ html = _inject_html_images(html, img_refs, src.parent)
1715
+ dest.write_text(html, encoding="utf-8")
1716
+
1717
+ logger.info(f"✅ HTML 生成成功: {dest}")
1718
+ return str(dest)
1719
+
1720
+ @staticmethod
1721
+ def convert_md_to_docx(
1722
+ src_path: str | Path,
1723
+ dest_path: str | Path | None = None,
1724
+ *,
1725
+ generate_toc: bool = False,
1726
+ mainfont: str = "宋体",
1727
+ ) -> str:
1728
+ """将 Markdown 文件转换为 Word(.docx)文件(基于 PiMD)
1729
+
1730
+ 使用 PiMD(markdown-it 解析 + python-docx 渲染,CommonMark 系)
1731
+ 生成 docx,支持标题、列表、表格(表头深蓝底加粗)、代码块、链接
1732
+ 等语法;可通过 generate_toc 在文档开头插入目录。
1733
+ 全文字体统一为 mainfont(默认宋体):转换后改写 docDefaults 与
1734
+ 主题字体(正文/标题/表格全部生效),代码块保持等宽字体。
1735
+
1736
+ 图片(`![alt](相对路径)`)以内嵌图片段落回填:PiMD 会把行内图片
1737
+ 降级为「alt 文本 + 超链接」,此处按占位标记替换为真实图片并居中,
1738
+ 宽度按节内容区等比限幅(相对路径以源文件所在目录为基准);图片
1739
+ 缺失、越界或 python-docx 不支持的格式(如 webp)回落为 alt 文本。
1740
+
1741
+ 转换前自动做 CJK 加粗预处理:`**加粗:**后接` 这类闭合 ** 前为
1742
+ 全角标点的写法不满足 CommonMark 定界规则(会以字面星号进入
1743
+ Word),内部将其改写为 `**加粗**:后接`,代码块内容不受影响;
1744
+ 转换后自动做表格版式后处理(表格撑满页宽并整体居中)。
1745
+
1746
+ Args:
1747
+ src_path: Markdown 源文件路径(支持 str 或 Path)
1748
+ dest_path: 目标 Word 文件路径;None 时使用源文件名同目录加 .docx 后缀
1749
+ generate_toc: 是否在文档开头插入目录
1750
+ mainfont: 文档全局字体名(Word 字体名,如 "宋体"/"黑体"),默认宋体
1751
+
1752
+ Returns:
1753
+ str: 实际写入的 Word 文件绝对路径
1754
+
1755
+ Raises:
1756
+ FileNotFoundError: 源文件不存在
1757
+ ValueError: 源文件不是常规文件或扩展名不是 .md
1758
+ OSError: 文件读写失败
1759
+ RuntimeError: Word 渲染失败
1760
+
1761
+ Example:
1762
+ >>> Md2DocKit.convert_md_to_docx("report.md") # 生成同目录 report.docx
1763
+ >>> Md2DocKit.convert_md_to_docx("report.md", mainfont="仿宋")
1764
+ >>> Md2DocKit.convert_md_to_docx("report.md", "out.docx", generate_toc=True)
1765
+ """
1766
+ src, dest = _resolve_md_paths(src_path, dest_path, ".docx")
1767
+ logger.info(f"开始转换 Markdown 为 Word: {src.name}")
1768
+
1769
+ # CJK 加粗预处理;临时 md 与源文件同目录,保证相对图片路径仍然可用
1770
+ processed = _normalize_cjk_bold(src.read_text(encoding="utf-8"))
1771
+ # 图片语法先换占位标记(PiMD 会把它降级为 alt 超链接),转换后回填;
1772
+ # python-docx 不可用时不做标记替换,保持 0.6.3 的 alt 超链接行为
1773
+ img_refs: list[tuple[str, str]] = []
1774
+ if _docx_available():
1775
+ processed, img_refs = _extract_images(processed)
1776
+ else:
1777
+ logger.warning("python-docx 不可用,Word 输出保留 alt 文本超链接(无图片)")
1778
+ tmp_md = src.with_name(f".{src.stem}.pimd-tmp.md")
1779
+ tmp_md.write_text(processed, encoding="utf-8")
1780
+
1781
+ try:
1782
+ _PIMD.md_to_docx(str(tmp_md), str(dest), generate_toc=generate_toc)
1783
+ except ConversionError as e:
1784
+ logger.error(f"Word 渲染失败: {src.name}: {e}")
1785
+ raise RuntimeError(f"Word 渲染失败: {src.name}: {e}") from e
1786
+ except OSError as e: # noqa: BLE001 - 文件读写异常统一包装
1787
+ logger.error(f"Word 渲染失败: {src.name}: {e}")
1788
+ raise RuntimeError(f"Word 渲染失败: {src.name}: {e}") from e
1789
+ finally:
1790
+ tmp_md.unlink(missing_ok=True)
1791
+
1792
+ # 图片回填:无图片时直接跳过(避免 python-docx 往返改变无图产物)
1793
+ if img_refs:
1794
+ _inject_docx_images(dest, img_refs, src.parent)
1795
+ # 表格版式后处理:撑满页宽并整体居中
1796
+ _polish_table_layout(dest)
1797
+ # 全局字体后处理:正文/标题统一为 mainfont(代码块保持等宽)
1798
+ _polish_docx_font(dest, mainfont)
1799
+
1800
+ logger.info(f"✅ Word 生成成功: {dest}")
1801
+ return str(dest)