Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: add EPUB 3.3 and PDF rendering support with strict MiddleJson handling

myhlolicd38eb9e2ff0
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 9c9e7de2..d0c7b06a 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -1,8 +1,8 @@
# Rendering Contract
-状态: 统一入口 / Markdown / Content List V1/V2 / Structured Content / DOCX / HTML v1
+状态: 统一入口 / Markdown / Content List V1/V2 / Structured Content / DOCX / EPUB 3.3 / PDF / HTML v1
读者: render 开发者、backend 开发者、SDK 开发者
-范围: 严格 MiddleJson 到 Markdown、Content List V1/V2、Structured Content、DOCX 和 HTML 的统一消费契约
+范围: 严格 MiddleJson 到 Markdown、Content List V1/V2、Structured Content、DOCX、EPUB、PDF 和 HTML 的统一消费契约
## 统一入口
@@ -31,6 +31,8 @@ markdown = render(
| `MARKDOWN` | `MarkdownRenderOptions(mode, asset_base_url, image_renderer)` | `str` |
| `HTML` | `HtmlRenderOptions(mode, asset_base_url, standalone, document_title)` | `str` |
| `DOCX` | `DocxRenderOptions(mode, asset_resolver)` | `bytes` |
+| `EPUB` | `EpubRenderOptions(mode, title, authors, language, identifier, modified_at, asset_resolver)` | `bytes` |
+| `PDF` | `PdfRenderOptions(mode, asset_resolver, document_title)` | `bytes` |
| `STRUCTURED_CONTENT` | `StructuredContentRenderOptions(asset_base_url)` | `dict[str, Any]` |
| `CONTENT_LIST` | `ContentListRenderOptions(asset_base_url)` | `list[dict[str, Any]]` |
| `CONTENT_LIST_V2` | `ContentListV2RenderOptions(asset_base_url)` | `list[list[dict[str, Any]]]` |
@@ -39,15 +41,15 @@ markdown = render(
类型不匹配时抛出 `TypeError`,不归一化字符串格式,也不在单次调用中批量渲染。各专用
`render_*()` 函数继续保留;统一入口只负责严格校验和分发,不改变底层渲染语义或异常类型。
-所有入口均不修改传入的 `MiddleJson`。renderer 不负责把结果或图片写到文件系统;DOCX
-需要读取相对图片 sidecar 时,只能通过显式 `asset_resolver` 获取字节。
+所有入口均不修改传入的 `MiddleJson`。renderer 不负责把结果或图片写到文件系统;DOCX、
+EPUB 与 PDF 需要读取相对图片 sidecar 时,只能通过显式 `asset_resolver` 获取字节。
### 内部依赖边界
-`markdown.py`、`html.py`、`docx.py`、`content_list.py`、`content_list_v2.py` 和
+`markdown.py`、`html.py`、`docx.py`、`epub.py`、`pdf.py`、`content_list.py`、`content_list_v2.py` 和
`structured_content.py` 是稳定公共门面;实现代码位于非公共
`mineru.render._internal`。`common` 只保存跨格式 AST、解析、列表/目录语义和 render planner,
-不得依赖任一格式实现。`markdown`、`html`、`docx` 子包只能依赖 `common` 与自身模块,彼此
+不得依赖任一格式实现。各格式私有子包只能依赖 `common`、基础层与自身模块,彼此
不交叉导入。`_internal` 路径不属于 SDK 兼容承诺。
## Markdown
@@ -120,9 +122,101 @@ alt description;Chart
`RenderMode.DEFAULT` 与下文 Markdown DEFAULT 使用同一份续段/续表 planner;
`RenderMode.FULL` 保留全部页面辅助块,不跨源页合并,并在相邻 `PageInfo` 间写硬分页。
-Markdown、HTML 和 DOCX 统一使用 `RenderMode`。DOCX 是语义化可编辑输出,不承诺
+Markdown、HTML、DOCX 和 EPUB 统一使用 `RenderMode`。DOCX 是语义化可编辑输出,不承诺
复刻源 PDF/Office 的字体、分栏、断行和页数;CLI、doclib 与 v1 API 不在本契约范围。
+## 单正文 EPUB 3.3
+
+```python
+from datetime import datetime, timezone
+
+from mineru.render import EpubRenderOptions, RenderFormat, RenderMode, render
+
+epub_bytes = render(
+ middle_json,
+ RenderFormat.EPUB,
+ options=EpubRenderOptions(
+ mode=RenderMode.DEFAULT,
+ title=None,
+ authors=("Alice",),
+ language="zh-CN",
+ modified_at=datetime(2026, 1, 2, tzinfo=timezone.utc),
+ asset_resolver=lambda relative_path: (asset_dir / relative_path).read_bytes(),
+ ),
+)
+```
+
+`render_epub()` 只接受严格 `MiddleJson`,返回完整 EPUB 3.3 容器 bytes,不落盘、不读取 cwd、
+不访问网络。容器固定包含首个且不压缩的 `mimetype`、`META-INF/container.xml`、一个 OPF、
+一个 navigation document、静态 CSS、可用图片和唯一正文 `content.xhtml`。OPF spine 始终只有
+这个正文项,不按 `PageInfo` 或标题拆章,也不生成 EPUB 2 NCX、封面或 page-list。
+
+标题默认取首个非空 `doc_title`,否则回退为 `MinerU Document`;语言默认 `und`。未显式提供
+identifier 时,由完整 MiddleJson、标题、作者和语言生成稳定 UUID URN。`modified_at` 默认使用
+本次调用的 UTC 时间;显式值必须带时区,并同时控制 OPF 修改时间和 ZIP 成员时间,因此相同输入
+与固定时间可得到相同 bytes。OPF 只输出 EPUB 要求的 title、identifier、language、modified 和
+可选 creator 元数据,不把输入 EPUB 的原 OPF 元数据或 CSS 带入新容器。
+
+navigation document 优先使用第一个至少含一个真实标题目标的 `IndexBlock`,保留有效项的顺序和
+嵌套层级并丢弃悬空项;没有有效目录时按正文标题 `level` 建树;没有标题时使用书名链接到正文
+起点。标题和 `page_footnote` 获得 document-wide 唯一 id,内部 fragment 会重写到这些真实目标,
+脚注链接增加 EPUB `noteref` 语义。无包内目标的相对链接展开为普通文字,显式
+`http/https/mailto/tel` 外链继续保留。
+
+行内和行间 LaTeX 通过现有 `latex2mathml` 生成静态 Presentation MathML,不加载 MathJax;转换
+失败时保留可见 LaTeX。只有正文实际写入 MathML 时,manifest 的正文项才声明 `mathml` property。
+代码、算法、流程图和富 HTML 都使用无脚本静态表示;富 HTML 只复制 allowlist 标签和有界的
+表格/列表属性,删除活动内容、事件、来源样式及无法重写的资源。
+
+图片按 `image_path`、`image_base64`、`image_url` 的候选顺序处理。相对 `image_path` 和富 HTML
+相对 `img src` 只能经 `asset_resolver` 读取;data URI 会校验 MIME、签名和完整图片;WebP、BMP、
+TIFF 及安全 MinerU SVG fallback 规范化为 PNG,PNG/JPEG/GIF 保留,最终按内容 SHA-256 去重。
+renderer 不下载 `image_url`。路径缺失、resolver 抛错、图片损坏或远程图片都不会中断输出:图片
+主体省略,但已有结构内容、alt、caption、footnote 和识别文字继续可见,也不会生成虚构占位文案。
+
+EPUB 与 Markdown/HTML/DOCX 共用 `RenderMode` planner。DEFAULT 在单 XHTML 中形成连续阅读内容;
+FULL 仍只有一个 spine item,但为所有 `PageInfo` 保留 section、空页、页面辅助块和分页标记。
+该能力仅属于严格 `mineru.render` 公共面,不新增 ParseResult 方法,也不迁移 CLI、API、doclib 或
+parse-job `output_formats`。
+
+## MinerU PDF
+
+```python
+from mineru.render import RenderMode, render_pdf
+
+pdf_bytes = render_pdf(
+ middle_json,
+ mode=RenderMode.FULL,
+ asset_resolver=lambda relative_path: (asset_dir / relative_path).read_bytes(),
+ document_title=None,
+)
+```
+
+`render_pdf()` 只接受严格 `MiddleJson`,返回完整 PDF bytes,不写文件、不读取 cwd 且不访问网络。
+它固定使用 A4 纵向和 20 mm 页边距,是面向阅读的语义化重排输出,不承诺复刻源文件坐标、
+分栏、断行或原始物理页数。PDF 默认 `RenderMode.FULL`:保留页面辅助块与空页,在每个
+`PageInfo` 边界硬分页;一个源页内容过长时允许自然延伸到额外 PDF 页。显式 `DEFAULT` 继续使用
+共享 planner 的隐藏辅助块、续段与续表合并语义。
+
+PDF 使用 ReportLab 生成,标题、正文、表格、图片、代码、caption 与 footnote 采用 MinerU HTML
+主题的打印配色。标题与 `page_footnote` anchor 会建立 PDF destination,目录和 InlineSpan fragment
+链接可跳转到已注册目标;HTTP(S)、mailto 等外链保持可点击。Latin 使用 Helvetica/Courier,
+中文使用 `STSong-Light`,日文与韩文分别使用标准 CID 字体。
+
+行内与行间 LaTeX 通过 ZiaMath 的 inline/display 模式转换为自包含 SVG path,再由 FontTools 的
+SVG path parser 直接映射为 ReportLab 矢量路径。该转换器只接受 ZiaMath 固定输出的
+`svg/g/path/rect` 与 `M/L/Q/Z` 子集,不用于 MiddleJson 的任意 SVG。行内公式携带真实
+width/ascent/descent 参与段落换行和基线计算;行间公式居中并保留末端 `\\tag{...}` 编号。
+转换失败时,行内公式回退可见 `$...$`,行间公式依次回退现有公式图片和可见 LaTeX。
+
+图片仍按 `image_path`、`image_base64`、`image_url` 的优先级选择。相对 sidecar 只经
+`asset_resolver` 获取,远程 URL 不下载;缺失、损坏、任意外部 SVG 或其它不支持的图片输出带
+page/block 定位的浅色占位,远程 URL 同时保留可点击链接,图片错误不会中止 PDF。HTML table
+物化为支持 rowspan/colspan、嵌套表、重复表头和跨页拆分的原生 ReportLab table;结构无效时
+回退空间文本、整体图片或占位。
+
+该接口只属于严格 `mineru.render` 公共面,不新增 ParseResult 方法,也不迁移 CLI、API 或 doclib。
+
## MinerU 独立 HTML
```python
@@ -356,10 +450,10 @@ doclib 或历史扁平 `content_list.json` 产物。
`RenderMode.FULL`:
- 展示全部顶层 block。
-- 带 anchor 的 `page_footnote` 在 DEFAULT/FULL 的 Markdown/HTML/DOCX 中分别输出 span id、元素 id 和 Word bookmark。
+- 带 anchor 的 `page_footnote` 在 DEFAULT/FULL 中由 Markdown 输出 span id,HTML/EPUB 输出元素 id,DOCX 输出 Word bookmark,PDF 输出 destination。
- 只合并页内 `text/ref_text/list.continues_prev`。
- 不合并跨页 text/ref_text/list/table。
-- 每两个相邻 `PageInfo` 之间输出 `---`,空白页边界同样保留。
+- 每两个相邻 `PageInfo` 之间保留格式对应的页面边界;PDF 使用硬分页且空白页同样保留。
text 合并允许跨越任意其他 block,后一个 text 的内容被吸收到前一个 text,
后块不再在原位置输出。ref_text 与 ref list 都只跨过页面脚注与辅助块,其他语义块
diff --git a/docs/next/sdk/parser.md b/docs/next/sdk/parser.md
index 795d1b9f..e55f1259 100644
--- a/docs/next/sdk/parser.md
+++ b/docs/next/sdk/parser.md
@@ -65,7 +65,7 @@ from mineru.parser import MinerUParser
- HTML、HTM(静态源码、固定 `auto` 正文选择)
- OFD(原生固定版式文字、图片、全线表格和 bbox)
-EPUB 始终使用 `flash/txt` 并只支持整本解析。每个 `page_idx` 与 OPF spine 项一一对应;位于 spine 中的 navigation XHTML 按普通内容页解析,spine 外的 nav/NCX 不生成合成目录页。正文、列表和表格中的安全内部链接统一映射到实际标题 anchor;严格匹配单一标题的目录表格行会让相邻标题单元格继承同一跳转。单条 Footnote/Endnote 输出为带可选 canonical anchor 的 `page_footnote`,正文 `noteref` 可跨 spine 正向链接到该 anchor;脚注集合容器不会整体改型。fixed-layout/SVG 仅尽力保留 DOM 文本与包内静态图片,不执行 OCR、脚本、外部资源下载或 DRM 解密。所有非 PDF Flash 格式显式传入 `page_range` 都会返回 `page_range_invalid`。
+EPUB 始终使用 `flash/txt` 并只支持整本解析。每个 `page_idx` 与 OPF spine 项一一对应;位于 spine 中的 navigation XHTML 按普通内容页解析,spine 外的 nav/NCX 不生成合成目录页。正文、列表和表格中的安全内部链接统一映射到实际标题 anchor;严格匹配单一标题的目录表格行会让相邻标题单元格继承同一跳转。单条 Footnote/Endnote 输出为带可选 canonical anchor 的 `page_footnote`,正文 `noteref` 可跨 spine 正向链接到该 anchor;脚注集合容器不会整体改型。spine XHTML 先按严格 XML 解析;局部标签闭合错误会记录 warning,再经过禁用网络的受限 XML 安全审计与 HTML DOM 恢复。恢复后仍要求 `html` 根节点并重新执行节点数、深度预算;DTD 实体、加密、资源超限以及 OPF/container/SVG 等控制或固定版式 XML 不进入宽松回退。恢复仍失败时保留空 spine 占位。fixed-layout/SVG 仅尽力保留 DOM 文本与包内静态图片,不执行 OCR、脚本、外部资源下载或 DRM 解密。所有非 PDF Flash 格式显式传入 `page_range` 都会返回 `page_range_invalid`。
HTML 始终使用 `flash/txt` 并输出一个无 bbox 的逻辑页。解析器不执行 JavaScript 或远程资源下载;固定 `auto`
模式只在正文候选置信度和保留率均达标时裁剪导航噪声,否则保留完整 body。本地相对图片限制在源文件目录内,
diff --git a/mineru/model/flash/epub/converter.py b/mineru/model/flash/epub/converter.py
index eebe3f4f..1038c511 100644
--- a/mineru/model/flash/epub/converter.py
+++ b/mineru/model/flash/epub/converter.py
@@ -33,7 +33,10 @@ class EpubConverter:
logger.warning("Skipping unsupported EPUB spine item index={} idref={!r}", index, spine_item.idref)
continue
try:
- root = package.xml_part(spine_item.path, allow_external_doctype=True)
+ if spine_item.media_type in XHTML_MEDIA_TYPES:
+ root = package.xhtml_part(spine_item.path, allow_external_doctype=True)
+ else:
+ root = package.xml_part(spine_item.path, allow_external_doctype=True)
except (EpubEncryptedError, EpubResourceLimitError):
raise
except EpubParseError as exc:
diff --git a/mineru/model/flash/epub/package.py b/mineru/model/flash/epub/package.py
index 2c07270a..17830896 100644
--- a/mineru/model/flash/epub/package.py
+++ b/mineru/model/flash/epub/package.py
@@ -81,6 +81,29 @@ def _xml_parser() -> etree.XMLParser:
)
+def _recovering_xml_parser() -> etree.XMLParser:
+ """创建禁用实体、DTD 和网络但允许修复局部 XHTML 语法的 parser。"""
+ return etree.XMLParser(
+ resolve_entities=False,
+ load_dtd=False,
+ no_network=True,
+ recover=True,
+ remove_blank_text=False,
+ huge_tree=False,
+ )
+
+
+def _recovering_html_parser() -> etree.HTMLParser:
+ """创建禁用网络并按 HTML 空元素语义修复正文结构的 parser。"""
+ return etree.HTMLParser(
+ no_network=True,
+ recover=True,
+ remove_comments=False,
+ remove_blank_text=False,
+ huge_tree=False,
+ )
+
+
def _local_name(element: etree._Element) -> str:
"""返回 XML 元素不含命名空间的本地名。"""
return etree.QName(element).localname
@@ -245,14 +268,75 @@ class EpubPackage:
if required:
raise EpubParseError(f"Malformed EPUB package: invalid XML part {part_name!r}: {exc}") from exc
return None
+ self._validate_xml_document(root, part_name, allow_external_doctype=allow_external_doctype)
+ return root
+
+ def xhtml_part(
+ self,
+ part_name: str,
+ *,
+ required: bool = False,
+ allow_external_doctype: bool = True,
+ ) -> etree._Element | None:
+ """严格解析 spine XHTML,失败后在相同安全预算内尝试局部语法恢复。"""
+ data = self.read_part(part_name, required=required)
+ if data is None:
+ return None
+ strict_error: etree.XMLSyntaxError | ValueError | None = None
+ try:
+ root = etree.fromstring(data, parser=_xml_parser())
+ except (etree.XMLSyntaxError, ValueError) as exc:
+ strict_error = exc
+ try:
+ xml_recovery_root = etree.fromstring(data, parser=_recovering_xml_parser())
+ except (etree.XMLSyntaxError, ValueError) as recovery_exc:
+ if required:
+ raise EpubParseError(
+ f"Malformed EPUB package: invalid XHTML part {part_name!r}: {recovery_exc}"
+ ) from recovery_exc
+ return None
+ if not isinstance(xml_recovery_root.tag, str) or _local_name(xml_recovery_root).casefold() != "html":
+ if required:
+ raise EpubParseError(f"Malformed EPUB package: XHTML part {part_name!r} has no html root")
+ return None
+ self._validate_xml_document(
+ xml_recovery_root,
+ part_name,
+ allow_external_doctype=allow_external_doctype,
+ )
+ try:
+ root = etree.fromstring(data, parser=_recovering_html_parser())
+ except (etree.XMLSyntaxError, ValueError) as recovery_exc:
+ if required:
+ raise EpubParseError(
+ f"Malformed EPUB package: invalid XHTML part {part_name!r}: {recovery_exc}"
+ ) from recovery_exc
+ return None
+ if not isinstance(root.tag, str) or _local_name(root).casefold() != "html":
+ if required:
+ raise EpubParseError(f"Malformed EPUB package: XHTML part {part_name!r} has no html root")
+ return None
+ self._validate_xml_document(root, part_name, allow_external_doctype=allow_external_doctype)
+ if strict_error is not None:
+ logger.warning("Recovered malformed EPUB XHTML part path={!r}: {}", part_name, strict_error)
+ return root
+
+ @classmethod
+ def _validate_xml_document(
+ cls,
+ root: etree._Element,
+ part_name: str,
+ *,
+ allow_external_doctype: bool,
+ ) -> None:
+ """统一校验已解析 XML/XHTML 的 DTD 策略、节点数和最大深度。"""
docinfo = root.getroottree().docinfo
if docinfo.doctype:
internal_dtd = docinfo.internalDTD
has_entities = internal_dtd is not None and bool(internal_dtd.entities())
if not allow_external_doctype or has_entities:
raise EpubParseError(f"Malformed EPUB package: DTD declarations are not allowed in {part_name!r}")
- self._validate_xml_shape(root, part_name)
- return root
+ cls._validate_xml_shape(root, part_name)
@staticmethod
def _validate_xml_shape(root: etree._Element, part_name: str) -> None:
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index d1d8ddf1..0209b977 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -6,9 +6,11 @@ from .contracts import (
ContentListRenderOptions,
ContentListV2RenderOptions,
DocxRenderOptions,
+ EpubRenderOptions,
HtmlRenderOptions,
ImageRenderer,
MarkdownRenderOptions,
+ PdfRenderOptions,
RenderFormat,
RenderMode,
RenderOptions,
@@ -18,8 +20,10 @@ from .contracts import (
from .content_list import render_content_list
from .content_list_v2 import render_content_list_v2
from .docx import DocxRenderError, render_docx
+from .epub import render_epub
from .html import render_html
from .markdown import render_markdown
+from .pdf import render_pdf
from .structured_content import render_structured_content
__all__ = [
@@ -28,9 +32,11 @@ __all__ = [
"ContentListV2RenderOptions",
"DocxRenderError",
"DocxRenderOptions",
+ "EpubRenderOptions",
"HtmlRenderOptions",
"ImageRenderer",
"MarkdownRenderOptions",
+ "PdfRenderOptions",
"RenderFormat",
"RenderMode",
"RenderOptions",
@@ -40,7 +46,9 @@ __all__ = [
"render_content_list",
"render_content_list_v2",
"render_docx",
+ "render_epub",
"render_html",
"render_markdown",
+ "render_pdf",
"render_structured_content",
]
diff --git a/mineru/render/_internal/epub/__init__.py b/mineru/render/_internal/epub/__init__.py
new file mode 100644
index 00000000..e0f96917
--- /dev/null
+++ b/mineru/render/_internal/epub/__init__.py
@@ -0,0 +1,6 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""EPUB 3.3 renderer 的私有实现包。"""
+
+from .renderer import render_epub
+
+__all__ = ["render_epub"]
diff --git a/mineru/render/_internal/epub/assets.py b/mineru/render/_internal/epub/assets.py
new file mode 100644
index 00000000..e57bf0cc
--- /dev/null
+++ b/mineru/render/_internal/epub/assets.py
@@ -0,0 +1,166 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""EPUB renderer 的图片解析、规范化与包内去重。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import hashlib
+from io import BytesIO
+from pathlib import PurePosixPath
+import re
+from urllib.parse import unquote, urlsplit
+
+from PIL import Image, UnidentifiedImageError
+
+from ...contracts import AssetResolver
+from ....types import ImagePayloadBlock
+from ....utils.image_payload import (
+ extract_mineru_generated_svg_fallback,
+ normalize_image_extension,
+ parse_image_data_uri_strict,
+ validate_image_sidecar_path,
+)
+
+_SVG_START_RE = re.compile(rb"^(?:\xef\xbb\xbf)?\s*(?:<\?xml\b.*?\?>\s*)?<svg\b", re.IGNORECASE | re.DOTALL)
+_PASSTHROUGH_FORMATS = {"gif", "jpg", "png"}
+_MEDIA_TYPES = {
+ "gif": "image/gif",
+ "jpg": "image/jpeg",
+ "png": "image/png",
+}
+
+
+@dataclass(frozen=True, slots=True)
+class EpubAsset:
+ """保存一个已规范化且可写入 EPUB 的图片资源。"""
+
+ file_name: str
+ media_type: str
+ data: bytes
+
+
+class EpubAssetRegistry:
+ """按内容哈希登记 EPUB 图片,并隔离所有外部素材读取。"""
+
+ def __init__(self, asset_resolver: AssetResolver | None) -> None:
+ """保存显式 resolver,并初始化来源缓存与内容去重表。"""
+ self._asset_resolver = asset_resolver
+ self._source_cache: dict[str, str | None] = {}
+ self._assets: dict[str, EpubAsset] = {}
+
+ @property
+ def assets(self) -> tuple[EpubAsset, ...]:
+ """按稳定文件名顺序返回所有已登记包内图片。"""
+ return tuple(self._assets[name] for name in sorted(self._assets))
+
+ def resolve_block(self, block: ImagePayloadBlock) -> str | None:
+ """按 sidecar、data URI、远程 URL 优先级解析一个图片 block。"""
+ if block.image_path:
+ resolved = self._resolve_relative_path(block.image_path)
+ if resolved is not None:
+ return resolved
+ if block.image_base64:
+ resolved = self._resolve_data_uri(block.image_base64)
+ if resolved is not None:
+ return resolved
+ # EPUB 图片必须位于容器中;远程 image_url 只作为不可下载的最后候选跳过。
+ return None
+
+ def resolve_embedded_source(self, source: str) -> str | None:
+ """解析富 HTML img 的 data URI 或安全相对 sidecar,拒绝网络来源。"""
+ normalized = source.strip()
+ if not normalized:
+ return None
+ if normalized.lower().startswith("data:"):
+ return self._resolve_data_uri(normalized)
+ try:
+ parsed = urlsplit(normalized)
+ except ValueError:
+ return None
+ if parsed.scheme or parsed.netloc or parsed.query or parsed.fragment or normalized.startswith(("/", "\\")):
+ return None
+ decoded_path = unquote(parsed.path)
+ try:
+ safe_path = validate_image_sidecar_path(decoded_path)
+ except ValueError:
+ return None
+ return self._resolve_relative_path(safe_path)
+
+ def _resolve_relative_path(self, image_path: str) -> str | None:
+ """通过显式 resolver 读取相对图片,失败时返回可降级的空结果。"""
+ cache_key = f"path:{image_path}"
+ if cache_key in self._source_cache:
+ return self._source_cache[cache_key]
+ if self._asset_resolver is None:
+ self._source_cache[cache_key] = None
+ return None
+ try:
+ safe_path = validate_image_sidecar_path(image_path)
+ data = self._asset_resolver(safe_path)
+ if not isinstance(data, bytes):
+ raise TypeError("asset_resolver must return bytes")
+ declared_extension = PurePosixPath(safe_path).suffix.removeprefix(".") or None
+ href = self._register_prepared(data, declared_extension=declared_extension)
+ except Exception:
+ href = None
+ self._source_cache[cache_key] = href
+ return href
+
+ def _resolve_data_uri(self, data_uri: str) -> str | None:
+ """严格解码图片 data URI,失败时返回可降级的空结果。"""
+ cache_key = f"data:{hashlib.sha256(data_uri.encode('utf-8', errors='replace')).hexdigest()}"
+ if cache_key in self._source_cache:
+ return self._source_cache[cache_key]
+ try:
+ data, extension = parse_image_data_uri_strict(data_uri)
+ href = self._register_prepared(data, declared_extension=extension)
+ except (OSError, TypeError, ValueError):
+ href = None
+ self._source_cache[cache_key] = href
+ return href
+
+ def _register_prepared(self, data: bytes, *, declared_extension: str | None) -> str:
+ """规范化图片格式,按 SHA-256 去重并返回正文相对 href。"""
+ normalized, extension = _prepare_epub_image(data, declared_extension=declared_extension)
+ digest = hashlib.sha256(normalized).hexdigest()
+ file_name = f"{digest}.{extension}"
+ if file_name not in self._assets:
+ self._assets[file_name] = EpubAsset(
+ file_name=file_name,
+ media_type=_MEDIA_TYPES[extension],
+ data=normalized,
+ )
+ return f"../assets/{file_name}"
+
+
+def _prepare_epub_image(data: bytes, *, declared_extension: str | None) -> tuple[bytes, str]:
+ """校验图片字节,并把非 PNG/JPEG/GIF 栅格统一转为 PNG。"""
+ if not isinstance(data, bytes) or not data:
+ raise ValueError("Image payload must contain bytes")
+ expected = normalize_image_extension(declared_extension or "") or None
+ if expected == "svg" or _SVG_START_RE.match(data[:4096]) is not None:
+ if expected not in {None, "svg"}:
+ raise ValueError("Image bytes do not match the declared format")
+ fallback, _, _ = extract_mineru_generated_svg_fallback(data)
+ return _prepare_epub_image(fallback, declared_extension="png")
+
+ try:
+ with Image.open(BytesIO(data)) as image:
+ detected = normalize_image_extension(image.format or "")
+ if not detected:
+ raise ValueError("Unsupported image format")
+ image.load()
+ if expected is not None and expected != detected:
+ raise ValueError("Image bytes do not match the declared format")
+ if detected in _PASSTHROUGH_FORMATS:
+ return data, detected
+ has_alpha = "A" in image.getbands() or (image.mode == "P" and "transparency" in image.info)
+ converted = image.convert("RGBA" if has_alpha else "RGB")
+ output = BytesIO()
+ converted.save(output, format="PNG")
+ return output.getvalue(), "png"
+ except (UnidentifiedImageError, OSError, ValueError) as exc:
+ raise ValueError("Invalid or unsupported image payload") from exc
+
+
+__all__ = ["EpubAsset", "EpubAssetRegistry"]
diff --git a/mineru/render/_internal/epub/package.py b/mineru/render/_internal/epub/package.py
new file mode 100644
index 00000000..4ddb3e71
--- /dev/null
+++ b/mineru/render/_internal/epub/package.py
@@ -0,0 +1,250 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""EPUB 3.3 的元数据 XML、导航文档与确定性 OCF 打包。"""
+
+from __future__ import annotations
+
+import calendar
+from dataclasses import dataclass, field
+from datetime import datetime
+from io import BytesIO
+from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo
+
+from lxml import etree
+
+from .assets import EpubAsset
+
+_CONTAINER_NS = "urn:oasis:names:tc:opendocument:xmlns:container"
+_DC_NS = "http://purl.org/dc/elements/1.1/"
+_EPUB_NS = "http://www.idpf.org/2007/ops"
+_OPF_NS = "http://www.idpf.org/2007/opf"
+_XHTML_NS = "http://www.w3.org/1999/xhtml"
+_XML_NS = "http://www.w3.org/XML/1998/namespace"
+_EPUB_MIME = b"application/epub+zip"
+_CONTENT_PATH = "EPUB/text/content.xhtml"
+_STYLE_PATH = "EPUB/styles/mineru.css"
+
+
+@dataclass(frozen=True, slots=True)
+class EpubMetadata:
+ """保存 package document 所需的规范化书籍元数据。"""
+
+ title: str
+ authors: tuple[str, ...]
+ language: str
+ identifier: str
+ modified_at: datetime
+
+
+@dataclass(slots=True)
+class NavigationItem:
+ """保存 EPUB toc nav 中一个可链接的层级条目。"""
+
+ title: str
+ href: str
+ children: list[NavigationItem] = field(default_factory=list)
+
+
+def build_epub_package(
+ *,
+ metadata: EpubMetadata,
+ content_xhtml: bytes,
+ navigation: list[NavigationItem],
+ stylesheet: bytes,
+ assets: tuple[EpubAsset, ...],
+ has_mathml: bool,
+) -> bytes:
+ """在内存中按固定成员顺序构造完整 EPUB 3.3 容器。"""
+ container_xml = _build_container_xml()
+ navigation_xhtml = _build_navigation_xhtml(metadata, navigation)
+ package_document = _build_package_document(metadata, assets, has_mathml=has_mathml)
+ output = BytesIO()
+ with ZipFile(output, "w", compression=ZIP_DEFLATED, compresslevel=9) as archive:
+ _write_member(archive, "mimetype", _EPUB_MIME, metadata.modified_at, compression=ZIP_STORED)
+ _write_member(archive, "META-INF/container.xml", container_xml, metadata.modified_at)
+ _write_member(archive, "EPUB/package.opf", package_document, metadata.modified_at)
+ _write_member(archive, "EPUB/nav.xhtml", navigation_xhtml, metadata.modified_at)
+ _write_member(archive, _CONTENT_PATH, content_xhtml, metadata.modified_at)
+ _write_member(archive, _STYLE_PATH, stylesheet, metadata.modified_at)
+ for asset in assets:
+ _write_member(archive, f"EPUB/assets/{asset.file_name}", asset.data, metadata.modified_at)
+ return output.getvalue()
+
+
+def _build_container_xml() -> bytes:
+ """生成指向唯一 OPF package document 的 container.xml。"""
+ root = etree.Element(f"{{{_CONTAINER_NS}}}container", nsmap={None: _CONTAINER_NS}, version="1.0")
+ rootfiles = etree.SubElement(root, f"{{{_CONTAINER_NS}}}rootfiles")
+ etree.SubElement(
+ rootfiles,
+ f"{{{_CONTAINER_NS}}}rootfile",
+ attrib={
+ "full-path": "EPUB/package.opf",
+ "media-type": "application/oebps-package+xml",
+ },
+ )
+ return _serialize_xml(root)
+
+
+def _build_package_document(metadata: EpubMetadata, assets: tuple[EpubAsset, ...], *, has_mathml: bool) -> bytes:
+ """生成包含必需元数据、完整 manifest 与单正文 spine 的 OPF。"""
+ root = etree.Element(
+ f"{{{_OPF_NS}}}package",
+ nsmap={None: _OPF_NS, "dc": _DC_NS},
+ attrib={
+ "version": "3.0",
+ "unique-identifier": "pub-id",
+ f"{{{_XML_NS}}}lang": metadata.language,
+ },
+ )
+ metadata_element = etree.SubElement(root, f"{{{_OPF_NS}}}metadata")
+ identifier = etree.SubElement(metadata_element, f"{{{_DC_NS}}}identifier", id="pub-id")
+ identifier.text = metadata.identifier
+ title = etree.SubElement(metadata_element, f"{{{_DC_NS}}}title")
+ title.text = metadata.title
+ language = etree.SubElement(metadata_element, f"{{{_DC_NS}}}language")
+ language.text = metadata.language
+ for author in metadata.authors:
+ creator = etree.SubElement(metadata_element, f"{{{_DC_NS}}}creator")
+ creator.text = author
+ modified = etree.SubElement(metadata_element, f"{{{_OPF_NS}}}meta", property="dcterms:modified")
+ modified.text = metadata.modified_at.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ manifest = etree.SubElement(root, f"{{{_OPF_NS}}}manifest")
+ etree.SubElement(
+ manifest,
+ f"{{{_OPF_NS}}}item",
+ id="nav",
+ href="nav.xhtml",
+ attrib={"media-type": "application/xhtml+xml", "properties": "nav"},
+ )
+ content_attributes = {
+ "id": "content",
+ "href": "text/content.xhtml",
+ "media-type": "application/xhtml+xml",
+ }
+ if has_mathml:
+ content_attributes["properties"] = "mathml"
+ etree.SubElement(manifest, f"{{{_OPF_NS}}}item", attrib=content_attributes)
+ etree.SubElement(
+ manifest,
+ f"{{{_OPF_NS}}}item",
+ id="style",
+ href="styles/mineru.css",
+ attrib={"media-type": "text/css"},
+ )
+ for position, asset in enumerate(assets, start=1):
+ etree.SubElement(
+ manifest,
+ f"{{{_OPF_NS}}}item",
+ id=f"asset-{position}",
+ href=f"assets/{asset.file_name}",
+ attrib={"media-type": asset.media_type},
+ )
+ spine = etree.SubElement(root, f"{{{_OPF_NS}}}spine")
+ etree.SubElement(spine, f"{{{_OPF_NS}}}itemref", idref="content")
+ return _serialize_xml(root)
+
+
+def _build_navigation_xhtml(metadata: EpubMetadata, navigation: list[NavigationItem]) -> bytes:
+ """生成恰含一个 toc nav 和一个 landmarks nav 的 EPUB 导航文档。"""
+ root = etree.Element(
+ f"{{{_XHTML_NS}}}html",
+ nsmap={None: _XHTML_NS, "epub": _EPUB_NS},
+ attrib={f"{{{_XML_NS}}}lang": metadata.language, "lang": metadata.language},
+ )
+ head = etree.SubElement(root, f"{{{_XHTML_NS}}}head")
+ etree.SubElement(head, f"{{{_XHTML_NS}}}meta", charset="utf-8")
+ title = etree.SubElement(head, f"{{{_XHTML_NS}}}title")
+ title.text = f"{metadata.title} — Table of Contents"
+ etree.SubElement(
+ head,
+ f"{{{_XHTML_NS}}}link",
+ rel="stylesheet",
+ href="styles/mineru.css",
+ type="text/css",
+ )
+ body = etree.SubElement(root, f"{{{_XHTML_NS}}}body")
+ toc = etree.SubElement(
+ body,
+ f"{{{_XHTML_NS}}}nav",
+ id="toc",
+ role="doc-toc",
+ attrib={f"{{{_EPUB_NS}}}type": "toc"},
+ )
+ heading = etree.SubElement(toc, f"{{{_XHTML_NS}}}h1")
+ heading.text = "Table of Contents"
+ ordered = etree.SubElement(toc, f"{{{_XHTML_NS}}}ol")
+ for item in navigation:
+ _append_navigation_item(ordered, item)
+
+ landmarks = etree.SubElement(
+ body,
+ f"{{{_XHTML_NS}}}nav",
+ id="landmarks",
+ hidden="hidden",
+ attrib={f"{{{_EPUB_NS}}}type": "landmarks"},
+ )
+ landmarks_heading = etree.SubElement(landmarks, f"{{{_XHTML_NS}}}h2")
+ landmarks_heading.text = "Landmarks"
+ landmarks_list = etree.SubElement(landmarks, f"{{{_XHTML_NS}}}ol")
+ item = etree.SubElement(landmarks_list, f"{{{_XHTML_NS}}}li")
+ link = etree.SubElement(
+ item,
+ f"{{{_XHTML_NS}}}a",
+ href="text/content.xhtml#content-start",
+ attrib={f"{{{_EPUB_NS}}}type": "bodymatter"},
+ )
+ link.text = "Start of Content"
+ return _serialize_xml(root, doctype="<!DOCTYPE html>")
+
+
+def _append_navigation_item(parent: etree._Element, item: NavigationItem) -> None:
+ """递归把一个导航条目及其子项写入有序列表。"""
+ entry = etree.SubElement(parent, f"{{{_XHTML_NS}}}li")
+ link = etree.SubElement(entry, f"{{{_XHTML_NS}}}a", href=item.href)
+ link.text = item.title
+ if item.children:
+ nested = etree.SubElement(entry, f"{{{_XHTML_NS}}}ol")
+ for child in item.children:
+ _append_navigation_item(nested, child)
+
+
+def _serialize_xml(root: etree._Element, *, doctype: str | None = None) -> bytes:
+ """以 UTF-8 XML 声明和稳定缩进序列化一个 EPUB XML 文档。"""
+ etree.indent(root, space=" ")
+ return etree.tostring(
+ root,
+ encoding="utf-8",
+ xml_declaration=True,
+ doctype=doctype,
+ pretty_print=True,
+ )
+
+
+def _write_member(
+ archive: ZipFile,
+ name: str,
+ data: bytes,
+ modified_at: datetime,
+ *,
+ compression: int = ZIP_DEFLATED,
+) -> None:
+ """用固定权限、无 extra 字段和规范时间写入一个 OCF ZIP 成员。"""
+ info = ZipInfo(name, date_time=_zip_datetime(modified_at))
+ info.compress_type = compression
+ info.create_system = 3
+ info.external_attr = 0o100644 << 16
+ info.extra = b""
+ info.comment = b""
+ archive.writestr(info, data)
+
+
+def _zip_datetime(modified_at: datetime) -> tuple[int, int, int, int, int, int]:
+ """把 UTC 修改时间约束到 ZIP DOS 时间范围并截断到双秒。"""
+ year = min(max(modified_at.year, 1980), 2107)
+ day = min(modified_at.day, calendar.monthrange(year, modified_at.month)[1])
+ second = modified_at.second - modified_at.second % 2
+ return year, modified_at.month, day, modified_at.hour, modified_at.minute, second
+
+
+__all__ = ["EpubMetadata", "NavigationItem", "build_epub_package"]
diff --git a/mineru/render/_internal/epub/renderer.py b/mineru/render/_internal/epub/renderer.py
new file mode 100644
index 00000000..32d4462f
--- /dev/null
+++ b/mineru/render/_internal/epub/renderer.py
@@ -0,0 +1,1177 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到单正文 EPUB 3.3 的静态 XHTML renderer。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timezone
+import hashlib
+import json
+from functools import lru_cache
+from importlib import resources
+import re
+from urllib.parse import quote, unquote, urlsplit
+from uuid import NAMESPACE_URL, uuid5
+
+from bs4 import BeautifulSoup, NavigableString, Tag
+from bs4.element import Comment, Doctype, ProcessingInstruction
+from latex2mathml.converter import convert as latex_to_mathml
+from lxml import etree
+
+from ....backend.postprocess.inline import inline_plain_text, join_inline_spans, normalize_inline_spans
+from ....types import (
+ PAGE_AUXILIARY_BLOCK_TYPES,
+ RAW_ALGORITHM,
+ AlgorithmBodyBlock,
+ BlockBase,
+ BlockType,
+ ChartAnnotationBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeAnnotationBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ CodeInlineSpan,
+ DocTitleBlock,
+ EquationBlock,
+ EquationInlineSpan,
+ HyperlinkSpan,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ IndexBlock,
+ InlineSpan,
+ ListBlock,
+ MiddleJson,
+ PageAuxTextBlock,
+ PageFootnoteBlock,
+ ParagraphTitleBlock,
+ RefTextBlock,
+ TableAnnotationBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+ TextSpan,
+ TitleBlockBase,
+)
+from ...contracts import AssetResolver, EpubRenderOptions, RenderMode
+from ..common.index import strip_index_page_tail
+from ..common.list_items import ListItem, parse_list_item_marker, reference_list_needs_bullets
+from ..common.planner import PlannedBlock, build_render_plan
+from .assets import EpubAssetRegistry
+from .package import EpubMetadata, NavigationItem, build_epub_package
+
+_EPUB_NS = "http://www.idpf.org/2007/ops"
+_MATHML_NS = "http://www.w3.org/1998/Math/MathML"
+_XHTML_NS = "http://www.w3.org/1999/xhtml"
+_XML_NS = "http://www.w3.org/XML/1998/namespace"
+_STYLE_RESOURCE_NAME = "mineru.css"
+_INVALID_XML_TEXT_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]")
+_MARKUP_TOKEN_RE = re.compile(
+ r"<\s*(?P<closing>/)?\s*(?P<name>[A-Za-z][A-Za-z0-9:-]*)\b(?P<attrs>[^>]*)>",
+ re.DOTALL,
+)
+_SAFE_LANGUAGE_RE = re.compile(r"[a-z0-9][a-z0-9-]{0,31}\Z")
+_ALLOWED_MARKUP_TAGS = {
+ "a",
+ "b",
+ "blockquote",
+ "br",
+ "caption",
+ "code",
+ "col",
+ "colgroup",
+ "details",
+ "div",
+ "em",
+ "eq",
+ "i",
+ "img",
+ "kbd",
+ "li",
+ "mark",
+ "ol",
+ "p",
+ "pre",
+ "s",
+ "span",
+ "strong",
+ "sub",
+ "summary",
+ "summary",
+ "sup",
+ "table",
+ "tbody",
+ "td",
+ "tfoot",
+ "th",
+ "thead",
+ "tr",
+ "u",
+ "ul",
+}
+_DROP_CONTENT_TAGS = {
+ "audio",
+ "button",
+ "canvas",
+ "embed",
+ "form",
+ "head",
+ "iframe",
+ "input",
+ "math",
+ "noscript",
+ "object",
+ "script",
+ "select",
+ "style",
+ "svg",
+ "template",
+ "textarea",
+ "video",
+}
+_SOURCE_MARKUP_TAGS = _ALLOWED_MARKUP_TAGS | _DROP_CONTENT_TAGS
+_VOID_MARKUP_TAGS = {"br", "col", "img"}
+_PHRASING_MARKUP_TAGS = {
+ "a",
+ "b",
+ "code",
+ "em",
+ "i",
+ "kbd",
+ "mark",
+ "p",
+ "s",
+ "span",
+ "strong",
+ "sub",
+ "sup",
+ "u",
+}
+_BLOCK_MARKUP_TAGS = {"blockquote", "details", "div", "ol", "p", "pre", "table", "ul"}
+_TABLE_PARENT_RULES = {
+ "caption": {"table"},
+ "col": {"colgroup"},
+ "colgroup": {"table"},
+ "tbody": {"table"},
+ "td": {"tr"},
+ "tfoot": {"table"},
+ "th": {"tr"},
+ "thead": {"table"},
+ "tr": {"table", "tbody", "tfoot", "thead"},
+}
+
+
+@dataclass(frozen=True, slots=True)
+class _TitleTarget:
+ """保存正文标题的可见文本、层级与 XHTML 目标。"""
+
+ title: str
+ level: int
+ target_id: str
+
+
+class _AnchorRegistry:
+ """为正文标题和页面脚注分配文档级唯一 XHTML id。"""
+
+ def __init__(self, middle_json: MiddleJson) -> None:
+ """按页面与 block 顺序建立目标、来源 anchor 和标题索引。"""
+ self._block_targets: dict[tuple[int, int, str], str] = {}
+ self._anchor_targets: dict[str, str] = {}
+ self._footnote_targets: set[str] = set()
+ self.title_targets: list[_TitleTarget] = []
+ used_ids: set[str] = {"content-start"}
+ heading_position = 0
+ footnote_position = 0
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if isinstance(block, TitleBlockBase):
+ visible = inline_plain_text(block.content).strip()
+ if not visible:
+ continue
+ heading_position += 1
+ target_id = _allocate_target_id(
+ block.anchor,
+ fallback=f"heading-{heading_position}",
+ used_ids=used_ids,
+ )
+ self.title_targets.append(_TitleTarget(visible, block.level, target_id))
+ elif isinstance(block, PageFootnoteBlock):
+ visible = inline_plain_text(block.content).strip()
+ if not visible:
+ continue
+ footnote_position += 1
+ target_id = _allocate_target_id(
+ block.anchor,
+ fallback=f"footnote-{footnote_position}",
+ used_ids=used_ids,
+ )
+ self._footnote_targets.add(target_id)
+ else:
+ continue
+ assert block.index is not None
+ self._block_targets[(page.page_idx, block.index, str(block.type))] = target_id
+ anchor_key = _anchor_key(block.anchor)
+ if anchor_key and anchor_key not in self._anchor_targets:
+ self._anchor_targets[anchor_key] = target_id
+
+ def target_for_block(self, page_idx: int, block: BlockBase) -> str | None:
+ """按来源页、index 和类型返回标题或脚注的唯一目标。"""
+ if block.index is None:
+ return None
+ return self._block_targets.get((page_idx, block.index, str(block.type)))
+
+ def target_for_anchor(self, anchor: str | None) -> str | None:
+ """按 producer anchor 返回首次匹配的正文目标。"""
+ return self._anchor_targets.get(_anchor_key(anchor))
+
+ def is_footnote_target(self, target_id: str) -> bool:
+ """判断目标是否对应页面脚注,以便标注 noteref 语义。"""
+ return target_id in self._footnote_targets
+
+
+class _EpubXhtmlRenderer:
+ """维护单个 EPUB 正文的锚点、素材与 MathML 状态。"""
+
+ def __init__(
+ self,
+ middle_json: MiddleJson,
+ *,
+ mode: RenderMode,
+ metadata: EpubMetadata,
+ assets: EpubAssetRegistry,
+ anchors: _AnchorRegistry,
+ ) -> None:
+ """保存严格输入和已规范化的调用状态。"""
+ self.middle_json = middle_json
+ self.mode = mode
+ self.metadata = metadata
+ self.assets = assets
+ self.anchors = anchors
+ self.has_mathml = False
+
+ def render(self) -> bytes:
+ """把完整 render plan 写成一个无脚本 XHTML content document。"""
+ root = etree.Element(
+ _xhtml("html"),
+ nsmap={None: _XHTML_NS, "epub": _EPUB_NS},
+ attrib={f"{{{_XML_NS}}}lang": self.metadata.language, "lang": self.metadata.language},
+ )
+ head = etree.SubElement(root, _xhtml("head"))
+ etree.SubElement(head, _xhtml("meta"), charset="utf-8")
+ title = etree.SubElement(head, _xhtml("title"))
+ title.text = self.metadata.title
+ etree.SubElement(
+ head,
+ _xhtml("link"),
+ rel="stylesheet",
+ href="../styles/mineru.css",
+ type="text/css",
+ )
+ body = etree.SubElement(root, _xhtml("body"), attrib={"class": "mineru-epub-body"})
+ article = etree.SubElement(
+ body,
+ _xhtml("article"),
+ id="content-start",
+ attrib={"class": f"mineru-document mineru-document--{self.mode.value}"},
+ )
+ planned_pages = build_render_plan(self.middle_json, self.mode)
+ if self.mode is RenderMode.FULL:
+ self._render_full_pages(article, planned_pages)
+ else:
+ self._render_default_pages(article, planned_pages)
+ return etree.tostring(
+ root,
+ encoding="utf-8",
+ xml_declaration=True,
+ doctype="<!DOCTYPE html>",
+ )
+
+ def _render_default_pages(self, parent: etree._Element, pages: list[list[PlannedBlock]]) -> None:
+ """把 DEFAULT 计划展平到单个连续阅读容器。"""
+ for page in pages:
+ for planned in page:
+ rendered = self._render_planned_block(planned)
+ if rendered is not None:
+ parent.append(rendered)
+
+ def _render_full_pages(self, parent: etree._Element, pages: list[list[PlannedBlock]]) -> None:
+ """在单正文中保留所有 PageInfo section 与相邻分页标记。"""
+ for position, page in enumerate(pages):
+ page_idx = page[0].page_idx if page else self.middle_json.pages[position].page_idx
+ section = etree.SubElement(
+ parent,
+ _xhtml("section"),
+ attrib={"class": "mineru-page", "data-page-idx": str(page_idx)},
+ )
+ for planned in page:
+ rendered = self._render_planned_block(planned)
+ if rendered is not None:
+ section.append(rendered)
+ if position + 1 < len(pages):
+ etree.SubElement(parent, _xhtml("hr"), attrib={"class": "mineru-page-break"})
+
+ def _render_planned_block(self, planned: PlannedBlock) -> etree._Element | None:
+ """过滤计划块、分派具体类型并追加稳定来源属性。"""
+ if planned.removed:
+ return None
+ block = planned.block
+ if self.mode is RenderMode.DEFAULT and block.type in PAGE_AUXILIARY_BLOCK_TYPES:
+ return None
+ content = self._render_block_content(planned)
+ if content is None:
+ return None
+ wrapper = etree.Element(
+ _xhtml("div"),
+ attrib={
+ "class": "mineru-block",
+ "data-page-idx": str(planned.page_idx),
+ "data-block-type": str(block.type),
+ },
+ )
+ if block.index is not None:
+ wrapper.set("data-block-index", str(block.index))
+ wrapper.append(content)
+ return wrapper
+
+ def _render_block_content(self, planned: PlannedBlock) -> etree._Element | None:
+ """把一个具体 PageBlock 映射为静态 XHTML 元素。"""
+ block = planned.block
+ if isinstance(block, (TextBlock, RefTextBlock)):
+ content = join_inline_spans(planned.text_contents or [block.content])
+ paragraph = etree.Element(
+ _xhtml("p"),
+ attrib={"class": "mineru-ref-text" if isinstance(block, RefTextBlock) else "mineru-text"},
+ )
+ self._append_inline_spans(paragraph, content)
+ return paragraph if _has_visible_content(paragraph) else None
+ if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
+ return self._render_title(planned.page_idx, block)
+ if isinstance(block, PageFootnoteBlock):
+ return self._render_page_footnote(planned.page_idx, block)
+ if isinstance(block, PageAuxTextBlock):
+ element = etree.Element(
+ _xhtml("aside"),
+ attrib={"class": f"mineru-page-aux mineru-page-aux--{str(block.type).replace('_', '-')}"},
+ )
+ self._append_inline_spans(element, block.content)
+ return element if _has_visible_content(element) else None
+ if isinstance(block, EquationBlock):
+ return self._render_equation(block)
+ if isinstance(block, ListBlock):
+ return self._render_list(block)
+ if isinstance(block, IndexBlock):
+ return self._render_index(block)
+ if isinstance(block, ImageBlock):
+ return self._render_image_block(block)
+ if isinstance(block, TableBlock):
+ return self._render_table_block(block)
+ if isinstance(block, ChartBlock):
+ return self._render_chart_block(block)
+ if isinstance(block, CodeBlock):
+ return self._render_code_block(block)
+ raise TypeError(f"Unsupported PageBlock type: {type(block).__name__}")
+
+ def _render_title(self, page_idx: int, block: TitleBlockBase) -> etree._Element | None:
+ """渲染带文档级唯一 id 的 h1-h6 标题。"""
+ if not inline_plain_text(block.content).strip():
+ return None
+ level = min(max(block.level, 1), 6)
+ heading = etree.Element(_xhtml(f"h{level}"), attrib={"class": f"mineru-heading mineru-heading--{level}"})
+ target_id = self.anchors.target_for_block(page_idx, block)
+ if target_id:
+ heading.set("id", target_id)
+ self._append_inline_spans(heading, block.content)
+ return heading
+
+ def _render_page_footnote(self, page_idx: int, block: PageFootnoteBlock) -> etree._Element | None:
+ """把页面脚注保留为 EPUB footnote aside。"""
+ footnote = etree.Element(
+ _xhtml("aside"),
+ attrib={"class": "mineru-page-footnote", f"{{{_EPUB_NS}}}type": "footnote", "role": "doc-footnote"},
+ )
+ target_id = self.anchors.target_for_block(page_idx, block)
+ if target_id:
+ footnote.set("id", target_id)
+ self._append_inline_spans(footnote, block.content)
+ return footnote if _has_visible_content(footnote) else None
+
+ def _render_equation(self, block: EquationBlock) -> etree._Element | None:
+ """优先渲染行间 MathML,空公式时才尝试包内图片。"""
+ container = etree.Element(_xhtml("div"), attrib={"class": "mineru-equation"})
+ if block.content.strip():
+ self._append_math(container, block.content, display="block")
+ elif source := self.assets.resolve_block(block):
+ etree.SubElement(container, _xhtml("img"), src=source, alt="formula")
+ return container if _has_visible_content(container) else None
+
+ def _render_list(self, block: ListBlock) -> etree._Element | None:
+ """按共享 marker 语义递归渲染原生有序、无序或显式 marker 列表。"""
+ parsed_leaves = [
+ parse_list_item_marker(child.content)
+ for child in block.content
+ if not isinstance(child, ListBlock) and inline_plain_text(child.content).strip()
+ ]
+ add_reference_bullets = reference_list_needs_bullets(block)
+ container_tag, list_type, class_name = _classify_list(parsed_leaves, add_reference_bullets)
+ container = etree.Element(_xhtml(container_tag), attrib={"class": f"mineru-list {class_name}"})
+ if list_type:
+ container.set("type", list_type)
+ if container_tag == "ol" and parsed_leaves and parsed_leaves[0].value not in (None, 1):
+ container.set("start", str(parsed_leaves[0].value))
+ expected_value: int | None = None
+ last_item: etree._Element | None = None
+ for child in block.content:
+ if isinstance(child, ListBlock):
+ nested = self._render_list(child)
+ if nested is None:
+ continue
+ if last_item is None:
+ last_item = etree.SubElement(container, _xhtml("li"), attrib={"class": "mineru-list-item--orphan"})
+ last_item.append(nested)
+ continue
+ parsed = parse_list_item_marker(child.content)
+ item_content, marker = _list_item_content(
+ parsed,
+ add_reference_bullets,
+ explicit_markers=class_name == "mineru-list--explicit",
+ )
+ item = etree.SubElement(container, _xhtml("li"))
+ if class_name == "mineru-list--explicit":
+ item.set("class", "mineru-list-item--explicit")
+ if container_tag == "ol" and parsed.kind == "ordered" and parsed.value is not None:
+ if expected_value is None:
+ expected_value = parsed.value
+ if parsed.value != expected_value:
+ item.set("value", str(parsed.value))
+ expected_value = parsed.value + 1
+ if marker or class_name == "mineru-list--explicit":
+ marker_element = etree.SubElement(item, _xhtml("span"), attrib={"class": "mineru-list-marker"})
+ marker_element.text = marker or ""
+ content_element = etree.SubElement(item, _xhtml("span"), attrib={"class": "mineru-list-content"})
+ self._append_inline_spans(content_element, item_content)
+ last_item = item
+ return container if len(container) else None
+
+ def _render_index(self, block: IndexBlock) -> etree._Element | None:
+ """把源目录保留为正文内导航,并只链接到真实正文目标。"""
+ navigation = etree.Element(_xhtml("nav"), attrib={"class": "mineru-index", "aria-label": "Table of contents"})
+ listing = etree.SubElement(navigation, _xhtml("ul"))
+ self._append_index_children(listing, block)
+ return navigation if len(listing) else None
+
+ def _append_index_children(self, parent: etree._Element, block: IndexBlock) -> None:
+ """递归渲染 IndexBlock,并把孤立嵌套目录提升到当前层级。"""
+ last_item: etree._Element | None = None
+ for child in block.content:
+ if isinstance(child, IndexBlock):
+ nested = etree.Element(_xhtml("ul"))
+ self._append_index_children(nested, child)
+ if not len(nested):
+ continue
+ if last_item is None:
+ last_item = etree.SubElement(parent, _xhtml("li"), attrib={"class": "mineru-list-item--orphan"})
+ last_item.append(nested)
+ continue
+ content = strip_index_page_tail(child.content)
+ if not inline_plain_text(content).strip():
+ continue
+ item = etree.SubElement(parent, _xhtml("li"))
+ target = self.anchors.target_for_anchor(child.anchor) if isinstance(child, TitleBlockBase) else None
+ inline_parent = item
+ if target:
+ inline_parent = etree.SubElement(item, _xhtml("a"), href=f"#{quote(target, safe='-._~')}")
+ self._append_inline_spans(inline_parent, content)
+ last_item = item
+
+ def _render_image_block(self, block: ImageBlock) -> etree._Element | None:
+ """按子块顺序渲染图片主体及其标题、脚注。"""
+ figure = etree.Element(_xhtml("figure"), attrib={"class": "mineru-figure mineru-figure--image"})
+ for child in block.content:
+ rendered = (
+ self._render_image_body(block, child) if isinstance(child, ImageBodyBlock) else self._render_annotation(child)
+ )
+ if rendered is not None:
+ figure.append(rendered)
+ return figure if len(figure) else None
+
+ def _render_image_body(self, parent: ImageBlock, block: ImageBodyBlock) -> etree._Element | None:
+ """渲染包内图片,并在缺图时保留已有结构或可见文字。"""
+ container = etree.Element(_xhtml("div"), attrib={"class": "mineru-visual-body mineru-visual-body--image"})
+ source = self.assets.resolve_block(block)
+ if source:
+ alt = _plain_content_text(block.content) or parent.sub_type or "image"
+ etree.SubElement(container, _xhtml("img"), src=source, alt=alt, attrib={"class": "mineru-image"})
+ if block.content.strip():
+ content = etree.Element(_xhtml("div"), attrib={"class": "mineru-image-content"})
+ self._append_rich_or_text(content, block.content)
+ if _has_visible_content(content):
+ container.append(content)
+ return container if _has_visible_content(container) else None
+
+ def _render_table_block(self, block: TableBlock) -> etree._Element | None:
+ """按子块顺序渲染结构表格、图片回退及说明。"""
+ figure = etree.Element(_xhtml("figure"), attrib={"class": "mineru-figure mineru-figure--table"})
+ for child in block.content:
+ rendered = self._render_table_body(child) if isinstance(child, TableBodyBlock) else self._render_annotation(child)
+ if rendered is not None:
+ figure.append(rendered)
+ return figure if len(figure) else None
+
+ def _render_table_body(self, block: TableBodyBlock) -> etree._Element | None:
+ """优先输出安全结构内容,无内容时尝试整体表格图片。"""
+ container = etree.Element(_xhtml("div"), attrib={"class": "mineru-visual-body mineru-visual-body--table"})
+ if block.content.strip():
+ if _is_supported_markup(block.content):
+ self._append_markup(container, block.content)
+ else:
+ pre = etree.SubElement(container, _xhtml("pre"), attrib={"class": "mineru-table-text"})
+ pre.text = _normalize_xml_text(block.content)
+ if not _has_visible_content(container) and (source := self.assets.resolve_block(block)):
+ etree.SubElement(container, _xhtml("img"), src=source, alt="table", attrib={"class": "mineru-table-image"})
+ return container if _has_visible_content(container) else None
+
+ def _render_chart_block(self, block: ChartBlock) -> etree._Element | None:
+ """按子块顺序渲染图表图片、结构内容及说明。"""
+ figure = etree.Element(_xhtml("figure"), attrib={"class": "mineru-figure mineru-figure--chart"})
+ for child in block.content:
+ rendered = (
+ self._render_chart_body(block, child) if isinstance(child, ChartBodyBlock) else self._render_annotation(child)
+ )
+ if rendered is not None:
+ figure.append(rendered)
+ return figure if len(figure) else None
+
+ def _render_chart_body(self, parent: ChartBlock, block: ChartBodyBlock) -> etree._Element | None:
+ """渲染包内图表图片,并始终保留并存结构内容。"""
+ container = etree.Element(_xhtml("div"), attrib={"class": "mineru-visual-body mineru-visual-body--chart"})
+ if source := self.assets.resolve_block(block):
+ etree.SubElement(
+ container,
+ _xhtml("img"),
+ src=source,
+ alt=parent.sub_type or "chart",
+ attrib={"class": "mineru-chart-image"},
+ )
+ if block.content.strip():
+ content = etree.Element(_xhtml("div"), attrib={"class": "mineru-chart-content"})
+ self._append_rich_or_text(content, block.content, preformatted=True)
+ if _has_visible_content(content):
+ container.append(content)
+ return container if _has_visible_content(container) else None
+
+ def _render_code_block(self, block: CodeBlock) -> etree._Element | None:
+ """按子块顺序渲染静态代码、算法及其说明。"""
+ figure = etree.Element(_xhtml("figure"), attrib={"class": "mineru-figure mineru-figure--code"})
+ for child in block.content:
+ if isinstance(child, (CodeBodyBlock, AlgorithmBodyBlock)):
+ rendered = self._render_code_body(block, child)
+ else:
+ rendered = self._render_annotation(child)
+ if rendered is not None:
+ figure.append(rendered)
+ return figure if len(figure) else None
+
+ def _render_code_body(self, parent: CodeBlock, block: CodeBodyBlock | AlgorithmBodyBlock) -> etree._Element:
+ """代码使用 pre/code,算法使用保留换行的结构化 Span。"""
+ container = etree.Element(_xhtml("div"), attrib={"class": "mineru-visual-body mineru-visual-body--code"})
+ if parent.sub_type == BlockType.CODE:
+ if not isinstance(block, CodeBodyBlock):
+ raise TypeError("code subtype requires CodeBodyBlock")
+ pre = etree.SubElement(container, _xhtml("pre"), attrib={"class": "mineru-code"})
+ code = etree.SubElement(pre, _xhtml("code"))
+ language = _normalize_code_language(parent.guess_lang)
+ if language:
+ code.set("class", f"language-{language}")
+ code.text = _normalize_xml_text(block.content)
+ return container
+ if parent.sub_type == RAW_ALGORITHM:
+ if not isinstance(block, AlgorithmBodyBlock):
+ raise TypeError("algorithm subtype requires AlgorithmBodyBlock")
+ algorithm = etree.SubElement(container, _xhtml("div"), attrib={"class": "mineru-algorithm"})
+ self._append_inline_spans(algorithm, block.content, preserve_newlines=True, separate_adjacent_math=True)
+ return container
+ raise ValueError(f"Unsupported code subtype: {parent.sub_type}")
+
+ def _render_annotation(
+ self,
+ block: ImageAnnotationBlock | TableAnnotationBlock | ChartAnnotationBlock | CodeAnnotationBlock,
+ ) -> etree._Element | None:
+ """按 caption 或 footnote 语义渲染视觉说明。"""
+ role = "mineru-caption" if str(block.type).endswith("caption") else "mineru-footnote"
+ annotation = etree.Element(
+ _xhtml("p"),
+ attrib={"class": f"{role} {role}--{str(block.type).replace('_', '-')}"},
+ )
+ self._append_inline_spans(annotation, block.content)
+ return annotation if _has_visible_content(annotation) else None
+
+ def _append_inline_spans(
+ self,
+ parent: etree._Element,
+ spans: list[InlineSpan],
+ *,
+ preserve_newlines: bool = False,
+ separate_adjacent_math: bool = False,
+ ) -> None:
+ """按结构化 Span 顺序向 XHTML mixed content 追加安全节点。"""
+ previous_was_math = False
+ for span in spans:
+ current_is_math = isinstance(span, EquationInlineSpan)
+ if separate_adjacent_math and previous_was_math and current_is_math:
+ _append_text(parent, " ", preserve_newlines=True)
+ self._append_inline_span(parent, span, preserve_newlines=preserve_newlines)
+ previous_was_math = current_is_math
+
+ def _append_inline_span(self, parent: etree._Element, span: InlineSpan, *, preserve_newlines: bool) -> None:
+ """把单个 Text/Code/Equation/Hyperlink Span 追加到父节点。"""
+ if isinstance(span, TextSpan):
+ target = _append_text_style_container(parent, span)
+ _append_text(target, span.content, preserve_newlines=preserve_newlines)
+ return
+ if isinstance(span, CodeInlineSpan):
+ code = etree.SubElement(parent, _xhtml("code"))
+ _append_text(code, span.content, preserve_newlines=preserve_newlines)
+ return
+ if isinstance(span, EquationInlineSpan):
+ self._append_math(parent, span.content, display="inline")
+ return
+ if isinstance(span, HyperlinkSpan):
+ href, target_id = self._resolve_link(span.url)
+ link_parent = parent
+ if href:
+ link_parent = etree.SubElement(parent, _xhtml("a"), href=href)
+ if target_id and self.anchors.is_footnote_target(target_id):
+ link_parent.set(f"{{{_EPUB_NS}}}type", "noteref")
+ link_parent.set("role", "doc-noteref")
+ self._append_inline_spans(link_parent, list(span.content), preserve_newlines=preserve_newlines)
+ return
+ raise TypeError(f"Unsupported inline span: {type(span).__name__}")
+
+ def _append_math(self, parent: etree._Element, latex: str, *, display: str) -> None:
+ """追加 Presentation MathML,并在转换失败时显示原始 LaTeX。"""
+ normalized = latex.strip()
+ if not normalized:
+ return
+ try:
+ markup = latex_to_mathml(normalized, display=display)
+ parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True, recover=False, huge_tree=False)
+ math = etree.fromstring(markup.encode("utf-8"), parser=parser)
+ if math.tag != f"{{{_MATHML_NS}}}math":
+ raise ValueError("latex2mathml did not return a MathML root")
+ except Exception:
+ fallback = etree.SubElement(
+ parent,
+ _xhtml("code"),
+ attrib={"class": f"mineru-latex-fallback mineru-latex-fallback--{display}"},
+ )
+ fallback.text = _normalize_xml_text(normalized)
+ return
+ parent.append(math)
+ self.has_mathml = True
+
+ def _append_rich_or_text(self, parent: etree._Element, content: str, *, preformatted: bool = False) -> None:
+ """识别安全富 HTML,否则按普通文本或预格式文本输出。"""
+ if _is_supported_markup(content):
+ self._append_markup(parent, content)
+ return
+ if preformatted:
+ pre = etree.SubElement(parent, _xhtml("pre"))
+ pre.text = _normalize_xml_text(content)
+ else:
+ _append_text(parent, content)
+
+ def _append_markup(self, parent: etree._Element, markup: str) -> None:
+ """通过 EPUB 专用 allowlist 把不可信 HTML 转为安全 XHTML 节点。"""
+ soup = BeautifulSoup(_normalize_xml_text(markup), "html.parser")
+ for child in list(soup.contents):
+ self._append_soup_node(parent, child)
+
+ def _append_soup_node(self, parent: etree._Element, node: object) -> None:
+ """递归复制一个 BeautifulSoup 节点,仅创建允许的 XHTML 结构。"""
+ if isinstance(node, (Comment, Doctype, ProcessingInstruction)):
+ return
+ if isinstance(node, NavigableString):
+ _append_text(parent, str(node), preserve_newlines=True)
+ return
+ if not isinstance(node, Tag):
+ return
+ name = (node.name or "").lower()
+ if name in _DROP_CONTENT_TAGS:
+ return
+ if name not in _ALLOWED_MARKUP_TAGS:
+ for child in list(node.children):
+ self._append_soup_node(parent, child)
+ return
+ parent_name = etree.QName(parent).localname
+ if name in _TABLE_PARENT_RULES and parent_name not in _TABLE_PARENT_RULES[name]:
+ for child in list(node.children):
+ self._append_soup_node(parent, child)
+ return
+ if parent_name in _PHRASING_MARKUP_TAGS and name in _BLOCK_MARKUP_TAGS:
+ for child in list(node.children):
+ self._append_soup_node(parent, child)
+ return
+ if name == "a" and parent_name == "a":
+ for child in list(node.children):
+ self._append_soup_node(parent, child)
+ return
+ if name == "li" and parent_name not in {"ol", "ul"}:
+ if parent_name in _PHRASING_MARKUP_TAGS:
+ for child in list(node.children):
+ self._append_soup_node(parent, child)
+ return
+ listing = etree.SubElement(parent, _xhtml("ul"))
+ item = etree.SubElement(listing, _xhtml("li"), attrib=_safe_markup_attributes(name, node))
+ for child in list(node.children):
+ self._append_soup_node(item, child)
+ return
+ if name in {"ol", "ul"}:
+ listing = etree.SubElement(parent, _xhtml(name), attrib=_safe_markup_attributes(name, node))
+ for child in list(node.children):
+ if isinstance(child, NavigableString) and not str(child).strip():
+ continue
+ if isinstance(child, Tag) and (child.name or "").lower() == "li":
+ self._append_soup_node(listing, child)
+ continue
+ item = etree.SubElement(listing, _xhtml("li"))
+ self._append_soup_node(item, child)
+ return
+ if name == "eq":
+ self._append_math(parent, node.get_text(), display="inline")
+ return
+ if name == "img":
+ source = self.assets.resolve_embedded_source(_attribute_text(node.get("src")))
+ alt = _attribute_text(node.get("alt"))
+ if source:
+ image = etree.SubElement(parent, _xhtml("img"), src=source, alt=_normalize_xml_text(alt))
+ title = _attribute_text(node.get("title"))
+ if title:
+ image.set("title", _normalize_xml_text(title))
+ elif alt:
+ _append_text(parent, alt)
+ return
+ if name == "a":
+ href, target_id = self._resolve_link(_attribute_text(node.get("href")))
+ target_parent = parent
+ if href:
+ target_parent = etree.SubElement(parent, _xhtml("a"), href=href)
+ title = _attribute_text(node.get("title"))
+ if title:
+ target_parent.set("title", _normalize_xml_text(title))
+ if target_id and self.anchors.is_footnote_target(target_id):
+ target_parent.set(f"{{{_EPUB_NS}}}type", "noteref")
+ target_parent.set("role", "doc-noteref")
+ for child in list(node.children):
+ self._append_soup_node(target_parent, child)
+ return
+ attributes = _safe_markup_attributes(name, node)
+ if name == "colgroup" and any(isinstance(child, Tag) and child.name == "col" for child in node.children):
+ attributes.pop("span", None)
+ element = etree.SubElement(parent, _xhtml(name), attrib=attributes)
+ if name not in _VOID_MARKUP_TAGS:
+ for child in list(node.children):
+ self._append_soup_node(element, child)
+
+ def _resolve_link(self, url: str) -> tuple[str | None, str | None]:
+ """保留安全外链或已登记 fragment,删除无包内目标的相对链接。"""
+ normalized = _normalize_xml_text(url).strip()
+ if not normalized or normalized.startswith(("//", "\\")):
+ return None, None
+ if normalized.startswith("#"):
+ target = self.anchors.target_for_anchor(unquote(normalized[1:]))
+ if target:
+ return f"#{quote(target, safe='-._~')}", target
+ return None, None
+ try:
+ parsed = urlsplit(normalized)
+ _ = parsed.port
+ except ValueError:
+ return None, None
+ scheme = parsed.scheme.casefold()
+ if scheme in {"http", "https"}:
+ if not parsed.netloc or parsed.hostname is None or parsed.username is not None or parsed.password is not None:
+ return None, None
+ elif scheme in {"mailto", "tel"}:
+ if not parsed.path:
+ return None, None
+ else:
+ return None, None
+ return quote(normalized, safe="/:#?&=%@+~,;!$'*-._"), None
+
+
+def render_epub(
+ middle_json: MiddleJson,
+ *,
+ mode: RenderMode = RenderMode.DEFAULT,
+ title: str | None = None,
+ authors: tuple[str, ...] = (),
+ language: str = "und",
+ identifier: str | None = None,
+ modified_at: datetime | None = None,
+ asset_resolver: AssetResolver | None = None,
+) -> bytes:
+ """把严格 MiddleJson 无副作用地渲染为单正文 EPUB 3.3 字节。"""
+ if not isinstance(middle_json, MiddleJson):
+ raise TypeError("render_epub expects a MiddleJson instance")
+ options = EpubRenderOptions(
+ mode=mode,
+ title=title,
+ authors=authors,
+ language=language,
+ identifier=identifier,
+ modified_at=modified_at,
+ asset_resolver=asset_resolver,
+ )
+ resolved_title = _resolve_document_title(middle_json, options.title)
+ resolved_authors = tuple(_normalize_xml_text(author).strip() for author in options.authors)
+ resolved_language = options.language.strip()
+ resolved_identifier = (
+ options.identifier.strip()
+ if options.identifier
+ else _stable_identifier(
+ middle_json,
+ title=resolved_title,
+ authors=resolved_authors,
+ language=resolved_language,
+ )
+ )
+ resolved_modified = (options.modified_at or datetime.now(timezone.utc)).astimezone(timezone.utc).replace(microsecond=0)
+ if resolved_modified.year < 1000:
+ raise ValueError("modified_at UTC year must use four digits")
+ metadata = EpubMetadata(
+ title=resolved_title,
+ authors=resolved_authors,
+ language=resolved_language,
+ identifier=_normalize_xml_text(resolved_identifier),
+ modified_at=resolved_modified,
+ )
+ anchors = _AnchorRegistry(middle_json)
+ assets = EpubAssetRegistry(options.asset_resolver)
+ renderer = _EpubXhtmlRenderer(
+ middle_json,
+ mode=options.mode,
+ metadata=metadata,
+ assets=assets,
+ anchors=anchors,
+ )
+ content_xhtml = renderer.render()
+ navigation = _build_navigation(middle_json, anchors, resolved_title)
+ return build_epub_package(
+ metadata=metadata,
+ content_xhtml=content_xhtml,
+ navigation=navigation,
+ stylesheet=_load_epub_stylesheet(),
+ assets=assets.assets,
+ has_mathml=renderer.has_mathml,
+ )
+
+
+def _build_navigation(middle_json: MiddleJson, anchors: _AnchorRegistry, document_title: str) -> list[NavigationItem]:
+ """优先使用有效 IndexBlock,否则按标题层级或正文起点生成 toc。"""
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if not isinstance(block, IndexBlock):
+ continue
+ items = _navigation_from_index(block, anchors)
+ if items:
+ return items
+ if anchors.title_targets:
+ roots: list[NavigationItem] = []
+ stack: list[tuple[int, NavigationItem]] = []
+ for target in anchors.title_targets:
+ item = NavigationItem(
+ title=target.title,
+ href=f"text/content.xhtml#{quote(target.target_id, safe='-._~')}",
+ )
+ while stack and stack[-1][0] >= target.level:
+ stack.pop()
+ if stack:
+ stack[-1][1].children.append(item)
+ else:
+ roots.append(item)
+ stack.append((target.level, item))
+ return roots
+ return [NavigationItem(title=document_title, href="text/content.xhtml#content-start")]
+
+
+def _navigation_from_index(block: IndexBlock, anchors: _AnchorRegistry) -> list[NavigationItem]:
+ """从一个 IndexBlock 提取仅包含真实标题目标的层级导航。"""
+ result: list[NavigationItem] = []
+ last_item: NavigationItem | None = None
+ for child in block.content:
+ if isinstance(child, IndexBlock):
+ nested = _navigation_from_index(child, anchors)
+ if last_item is not None:
+ last_item.children.extend(nested)
+ else:
+ result.extend(nested)
+ continue
+ if not isinstance(child, TitleBlockBase):
+ continue
+ target = anchors.target_for_anchor(child.anchor)
+ title = inline_plain_text(strip_index_page_tail(child.content)).strip()
+ if not target or not title:
+ continue
+ last_item = NavigationItem(
+ title=title,
+ href=f"text/content.xhtml#{quote(target, safe='-._~')}",
+ )
+ result.append(last_item)
+ return result
+
+
+def _classify_list(items: list[ListItem], add_reference_bullets: bool) -> tuple[str, str | None, str]:
+ """根据直属 marker 选择原生列表类型或显式 marker 模式。"""
+ if add_reference_bullets:
+ return "ul", None, "mineru-list--reference"
+ if items and all(item.kind == "unordered" for item in items):
+ return "ul", None, "mineru-list--unordered"
+ if items and all(item.kind == "ordered" for item in items):
+ styles = {item.ordered_style for item in items}
+ if len(styles) == 1:
+ list_type = {
+ "lower-alpha": "a",
+ "upper-alpha": "A",
+ "lower-roman": "i",
+ "upper-roman": "I",
+ }.get(next(iter(styles)) or "")
+ return "ol", list_type, "mineru-list--ordered"
+ if items and all(item.kind == "none" for item in items):
+ return "ul", None, "mineru-list--unmarked"
+ return "ul", None, "mineru-list--explicit"
+
+
+def _list_item_content(
+ item: ListItem,
+ add_reference_bullets: bool,
+ *,
+ explicit_markers: bool,
+) -> tuple[list[InlineSpan], str | None]:
+ """决定列表项应剥离、保留还是显式显示源 marker。"""
+ if add_reference_bullets:
+ if item.kind == "unordered":
+ return item.body, None
+ prefix = f"{item.leading}{item.marker or ''}{item.separator}"
+ original = normalize_inline_spans([TextSpan(type="text", content=prefix), *item.body]) if prefix else item.body
+ return original, None
+ if explicit_markers:
+ return item.body, item.marker
+ if item.kind in {"unordered", "ordered"}:
+ return item.body, None
+ return item.body, item.marker
+
+
+def _append_text_style_container(parent: etree._Element, span: TextSpan) -> etree._Element:
+ """按固定样式顺序创建 TextSpan 的 XHTML 包装节点。"""
+ target = parent
+ if _needs_whitespace_preservation(span.content):
+ target = etree.SubElement(target, _xhtml("span"), attrib={"class": "mineru-preserve-whitespace"})
+ wrappers: list[tuple[str, dict[str, str]]] = []
+ if "emphasis" in span.styles:
+ wrappers.append(("span", {"class": "mineru-text-emphasis"}))
+ if "strikethrough" in span.styles:
+ wrappers.append(("s", {}))
+ if "italic" in span.styles:
+ wrappers.append(("em", {}))
+ if "bold" in span.styles:
+ wrappers.append(("strong", {}))
+ if "underline" in span.styles:
+ wrappers.append(("u", {}))
+ if "superscript" in span.styles:
+ wrappers.append(("sup", {}))
+ elif "subscript" in span.styles:
+ wrappers.append(("sub", {}))
+ for tag, attributes in wrappers:
+ target = etree.SubElement(target, _xhtml(tag), attrib=attributes)
+ return target
+
+
+def _append_text(parent: etree._Element, content: str, *, preserve_newlines: bool = False) -> None:
+ """向 mixed content 追加安全文本,并按需把换行转换为 br。"""
+ normalized = _normalize_xml_text(content).replace("\r\n", "\n").replace("\r", "\n")
+ if preserve_newlines:
+ _append_raw_text(parent, normalized)
+ return
+ parts = normalized.split("\n")
+ for position, part in enumerate(parts):
+ if position:
+ parent.append(etree.Element(_xhtml("br")))
+ _append_raw_text(parent, part)
+
+
+def _append_raw_text(parent: etree._Element, content: str) -> None:
+ """在不破坏既有子节点 tail 的前提下追加一段普通文本。"""
+ if not content:
+ return
+ if len(parent):
+ child = parent[-1]
+ child.tail = f"{child.tail or ''}{content}"
+ else:
+ parent.text = f"{parent.text or ''}{content}"
+
+
+def _safe_markup_attributes(name: str, tag: Tag) -> dict[str, str]:
+ """只保留表格和列表语义需要的有界属性。"""
+ attributes: dict[str, str] = {}
+ if name in {"td", "th"}:
+ for attribute in ("colspan", "rowspan"):
+ if value := _bounded_integer(_attribute_text(tag.get(attribute)), minimum=1, maximum=1000):
+ attributes[attribute] = value
+ scope = _attribute_text(tag.get("scope"))
+ if name == "th" and scope in {"col", "colgroup", "row", "rowgroup"}:
+ attributes["scope"] = scope
+ elif name in {"col", "colgroup"}:
+ if value := _bounded_integer(_attribute_text(tag.get("span")), minimum=1, maximum=1000):
+ attributes["span"] = value
+ elif name == "ol":
+ if value := _bounded_integer(_attribute_text(tag.get("start")), minimum=-1_000_000, maximum=1_000_000):
+ attributes["start"] = value
+ elif name == "li":
+ if value := _bounded_integer(_attribute_text(tag.get("value")), minimum=-1_000_000, maximum=1_000_000):
+ attributes["value"] = value
+ return attributes
+
+
+def _bounded_integer(value: str, *, minimum: int, maximum: int) -> str | None:
+ """把十进制属性约束到 EPUB renderer 支持的闭区间。"""
+ if re.fullmatch(r"[+-]?\d+", value) is None:
+ return None
+ number = int(value)
+ return str(number) if minimum <= number <= maximum else None
+
+
+def _attribute_text(value: object) -> str:
+ """把 BeautifulSoup 属性值稳定转换为普通字符串。"""
+ if value is None:
+ return ""
+ if isinstance(value, list):
+ return " ".join(str(item) for item in value)
+ return str(value)
+
+
+def _is_supported_markup(content: str) -> bool:
+ """仅把白名单或需整段删除的活动标签识别为富 HTML。"""
+ if "<" not in content or ">" not in content:
+ return False
+ tokens = list(_MARKUP_TOKEN_RE.finditer(content))
+ closing_names = {
+ match.group("name").lower()
+ for match in tokens
+ if match.group("closing") and match.group("name").lower() in _SOURCE_MARKUP_TAGS
+ }
+ for match in tokens:
+ if match.group("closing"):
+ continue
+ name = match.group("name").lower()
+ if name not in _SOURCE_MARKUP_TAGS:
+ continue
+ if name in _VOID_MARKUP_TAGS or name in closing_names:
+ return True
+ if name in {"img", "embed"} and re.search(r"\bsrc\s*=", match.group("attrs"), re.IGNORECASE):
+ return True
+ return False
+
+
+def _resolve_document_title(middle_json: MiddleJson, explicit_title: str | None) -> str:
+ """按显式值、首个文档标题和固定回退值解析书名。"""
+ if explicit_title:
+ return _normalize_xml_text(explicit_title).strip()
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if isinstance(block, DocTitleBlock):
+ title = _normalize_xml_text(inline_plain_text(block.content)).strip()
+ if title:
+ return title
+ return "MinerU Document"
+
+
+def _stable_identifier(middle_json: MiddleJson, *, title: str, authors: tuple[str, ...], language: str) -> str:
+ """由规范化 MiddleJson 和不随渲染时间变化的元数据生成稳定 UUID URN。"""
+ seed = json.dumps(
+ {
+ "middle_json": middle_json.model_dump(mode="json"),
+ "title": title,
+ "authors": authors,
+ "language": language,
+ },
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ digest = hashlib.sha256(seed).hexdigest()
+ return f"urn:uuid:{uuid5(NAMESPACE_URL, digest)}"
+
+
+def _allocate_target_id(anchor: str | None, *, fallback: str, used_ids: set[str]) -> str:
+ """从 producer anchor 或固定回退值分配无空白且不碰撞的 id。"""
+ base = _safe_id_base(_anchor_key(anchor)) or fallback
+ candidate = base
+ suffix = 2
+ while candidate in used_ids:
+ candidate = f"{base}-{suffix}"
+ suffix += 1
+ used_ids.add(candidate)
+ return candidate
+
+
+def _safe_id_base(value: str) -> str:
+ """把 anchor 归一化为适合 XHTML fragment 的稳定 id 基值。"""
+ normalized = _normalize_xml_text(value).strip()
+ normalized = re.sub(r"\s+", "-", normalized)
+ normalized = re.sub(r"[^\w.:-]+", "-", normalized, flags=re.UNICODE).strip("-")
+ return normalized
+
+
+def _anchor_key(anchor: str | None) -> str:
+ """保留 producer anchor 身份,仅去除首尾空白。"""
+ return (anchor or "").strip()
+
+
+def _plain_content_text(content: str) -> str:
+ """从 body 内容提取图片 alt 所需的可见纯文本。"""
+ if not content:
+ return ""
+ if _is_supported_markup(content):
+ return BeautifulSoup(content, "html.parser").get_text(" ", strip=True)
+ return _normalize_xml_text(content).strip()
+
+
+def _normalize_code_language(language: str | None) -> str | None:
+ """把代码语言限制为不会构造危险 class token 的短名称。"""
+ normalized = (language or "").strip().lower().replace("_", "-")
+ return normalized if _SAFE_LANGUAGE_RE.fullmatch(normalized) else None
+
+
+def _normalize_xml_text(content: str) -> str:
+ """替换 XML 1.0 禁止的控制字符和孤立 surrogate。"""
+ return _INVALID_XML_TEXT_RE.sub("\ufffd", content)
+
+
+def _needs_whitespace_preservation(content: str) -> bool:
+ """判断文本是否含有 XHTML 默认会折叠的有效空白。"""
+ return bool(content and (content != content.strip(" \t\n") or " " in content or "\t" in content or "\n" in content))
+
+
+def _has_visible_content(element: etree._Element) -> bool:
+ """判断元素是否包含可见文本或媒体、结构子节点。"""
+ if element.text and element.text.strip():
+ return True
+ if len(element):
+ return True
+ return False
+
+
+def _xhtml(tag: str) -> str:
+ """返回 XHTML namespace 下的 Clark notation 标签名。"""
+ return f"{{{_XHTML_NS}}}{tag}"
+
+
+@lru_cache(maxsize=1)
+def _load_epub_stylesheet() -> bytes:
+ """读取随包分发的静态 EPUB 样式表并缓存字节。"""
+ root = resources.files("mineru").joinpath("resources", "epub")
+ return root.joinpath(_STYLE_RESOURCE_NAME).read_bytes()
+
+
+__all__ = ["render_epub"]
diff --git a/mineru/render/_internal/pdf/__init__.py b/mineru/render/_internal/pdf/__init__.py
new file mode 100644
index 00000000..f6dc1375
--- /dev/null
+++ b/mineru/render/_internal/pdf/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""PDF 私有渲染实现。"""
+
+__all__: list[str] = []
diff --git a/mineru/render/_internal/pdf/assets.py b/mineru/render/_internal/pdf/assets.py
new file mode 100644
index 00000000..7c280910
--- /dev/null
+++ b/mineru/render/_internal/pdf/assets.py
@@ -0,0 +1,190 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""PDF renderer 的离线图片解析、签名校验与格式准备。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from io import BytesIO
+from pathlib import PurePosixPath
+import re
+from urllib.parse import urlsplit
+
+from PIL import Image, UnidentifiedImageError
+
+from ...contracts import AssetResolver
+from ....types import ImagePayloadBlock
+from ....utils.image_payload import (
+ extract_mineru_generated_svg_fallback,
+ parse_image_data_uri_strict,
+ validate_image_sidecar_path,
+)
+
+_PIL_FORMAT_EXTENSIONS = {
+ "BMP": "bmp",
+ "GIF": "gif",
+ "JPEG": "jpg",
+ "PNG": "png",
+ "TIFF": "tiff",
+ "WEBP": "webp",
+}
+_EXTENSION_ALIASES = {"jpeg": "jpg", "jpe": "jpg", "tif": "tiff"}
+_SVG_START_RE = re.compile(rb"^(?:\xef\xbb\xbf)?\s*(?:<\?xml\b.*?\?>\s*)?<svg\b", re.IGNORECASE | re.DOTALL)
+
+
+class PdfAssetError(ValueError):
+ """表示 PDF renderer 无法离线安全加载或识别图片素材。"""
+
+
+@dataclass(frozen=True, slots=True)
+class PreparedImage:
+ """保存可直接交给 ReportLab 的图片字节与像素尺寸。"""
+
+ data: bytes
+ extension: str
+ width_px: int
+ height_px: int
+
+
+def prepare_block_image(
+ block: ImagePayloadBlock,
+ asset_resolver: AssetResolver | None = None,
+) -> PreparedImage:
+ """按 sidecar、data URI 的固定优先级加载一个图片载荷 block。"""
+ if not isinstance(block, ImagePayloadBlock):
+ raise TypeError("block must be an ImagePayloadBlock")
+ if block.image_path is not None:
+ return _prepare_relative_asset(block.image_path, asset_resolver)
+ if block.image_base64 is not None:
+ return _prepare_data_uri(block.image_base64)
+ if block.image_url is not None:
+ raise PdfAssetError(f"Remote image is not downloaded: {block.image_url}")
+ raise PdfAssetError("Image block does not contain an image source")
+
+
+def prepare_html_image(
+ source: str,
+ asset_resolver: AssetResolver | None = None,
+) -> PreparedImage:
+ """从 HTML img 的 data URI 或安全相对 sidecar 加载图片。"""
+ if not isinstance(source, str):
+ raise TypeError("HTML image source must be a string")
+ normalized = source.strip()
+ if not normalized:
+ raise PdfAssetError("HTML image source must not be empty")
+ if normalized.lower().startswith("data:"):
+ if not normalized.lower().startswith("data:image/"):
+ raise PdfAssetError("Only image data URIs are supported")
+ return _prepare_data_uri(normalized)
+ parsed = urlsplit(normalized)
+ if parsed.scheme or parsed.netloc:
+ raise PdfAssetError(f"Remote HTML image is not downloaded: {normalized}")
+ return _prepare_relative_asset(normalized, asset_resolver)
+
+
+def prepare_image_bytes(data: bytes, *, declared_extension: str | None = None) -> PreparedImage:
+ """严格解码图片字节,并把 WebP 与安全 SVG fallback 转成 PNG。"""
+ if not isinstance(data, bytes):
+ raise PdfAssetError("Image resolver must return bytes")
+ if not data:
+ raise PdfAssetError("Image payload must not be empty")
+ expected_extension = _normalize_extension(declared_extension)
+ if expected_extension == "svg" or _looks_like_svg(data):
+ try:
+ fallback, logical_width, logical_height = extract_mineru_generated_svg_fallback(data)
+ except ValueError as exc:
+ raise PdfAssetError("SVG images require a validated MinerU PNG fallback") from exc
+ prepared = prepare_image_bytes(fallback, declared_extension="png")
+ return PreparedImage(
+ data=prepared.data,
+ extension="png",
+ width_px=logical_width,
+ height_px=logical_height,
+ )
+ try:
+ with Image.open(BytesIO(data)) as image:
+ detected_extension = _PIL_FORMAT_EXTENSIONS.get((image.format or "").upper())
+ if detected_extension is None:
+ raise PdfAssetError(f"Unsupported image format: {image.format or 'unknown'}")
+ width_px, height_px = image.size
+ image.load()
+ if expected_extension is not None and expected_extension != detected_extension:
+ raise PdfAssetError(
+ f"Image bytes do not match declared format: expected {expected_extension}, detected {detected_extension}"
+ )
+ if detected_extension == "webp":
+ return _convert_webp_to_png(image, width_px, height_px)
+ except PdfAssetError:
+ raise
+ except (UnidentifiedImageError, OSError, ValueError) as exc:
+ raise PdfAssetError("Invalid or corrupted image payload") from exc
+ return PreparedImage(
+ data=data,
+ extension=detected_extension,
+ width_px=width_px,
+ height_px=height_px,
+ )
+
+
+def _prepare_data_uri(data_uri: str) -> PreparedImage:
+ """严格解析图片 data URI 并校验 MIME、签名与完整载荷。"""
+ try:
+ data, extension = parse_image_data_uri_strict(data_uri)
+ except ValueError as exc:
+ raise PdfAssetError(str(exc)) from exc
+ return prepare_image_bytes(data, declared_extension=extension)
+
+
+def _prepare_relative_asset(image_path: str, asset_resolver: AssetResolver | None) -> PreparedImage:
+ """校验相对 sidecar 路径,并仅通过显式 resolver 获取字节。"""
+ parsed = urlsplit(image_path)
+ if parsed.scheme or parsed.netloc:
+ raise PdfAssetError(f"Remote or scheme-based image source is not supported: {image_path}")
+ try:
+ safe_path = validate_image_sidecar_path(image_path)
+ except ValueError as exc:
+ raise PdfAssetError(str(exc)) from exc
+ if asset_resolver is None:
+ raise PdfAssetError(f"asset_resolver is required for image_path: {safe_path}")
+ try:
+ data = asset_resolver(safe_path)
+ except Exception as exc:
+ raise PdfAssetError(f"Failed to resolve image asset: {safe_path}") from exc
+ extension = PurePosixPath(safe_path).suffix.removeprefix(".") or None
+ return prepare_image_bytes(data, declared_extension=extension)
+
+
+def _normalize_extension(extension: str | None) -> str | None:
+ """规范化可识别扩展名,未知扩展不作为签名声明。"""
+ if extension is None:
+ return None
+ normalized = extension.lower().lstrip(".").split("+", 1)[0]
+ normalized = _EXTENSION_ALIASES.get(normalized, normalized)
+ if normalized == "svg":
+ return normalized
+ return normalized if normalized in set(_PIL_FORMAT_EXTENSIONS.values()) else None
+
+
+def _looks_like_svg(data: bytes) -> bool:
+ """识别带可选 BOM 与 XML 声明的 SVG 字节。"""
+ return _SVG_START_RE.match(data[:4096]) is not None
+
+
+def _convert_webp_to_png(image: Image.Image, width_px: int, height_px: int) -> PreparedImage:
+ """在内存中把已解码 WebP 转成 ReportLab 可稳定读取的 PNG。"""
+ output = BytesIO()
+ image.save(output, format="PNG")
+ return PreparedImage(
+ data=output.getvalue(),
+ extension="png",
+ width_px=width_px,
+ height_px=height_px,
+ )
+
+
+__all__ = [
+ "PdfAssetError",
+ "PreparedImage",
+ "prepare_block_image",
+ "prepare_html_image",
+ "prepare_image_bytes",
+]
diff --git a/mineru/render/_internal/pdf/formula.py b/mineru/render/_internal/pdf/formula.py
new file mode 100644
index 00000000..08cb996a
--- /dev/null
+++ b/mineru/render/_internal/pdf/formula.py
@@ -0,0 +1,416 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""ZiaMath LaTeX 到受控 ReportLab 矢量路径的转换。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+from threading import RLock
+from typing import Any
+from xml.etree import ElementTree
+
+from fontTools.pens.basePen import BasePen
+from fontTools.svgLib.path import parse_path
+from reportlab.graphics.shapes import Drawing, Group, Path, Rect
+from reportlab.lib.colors import Color, toColor
+from reportlab.platypus import Flowable
+import ziamath
+
+MAX_FORMULA_CHARACTERS = 20_000
+MAX_CACHED_FORMULAS = 512
+_MAX_SVG_NODES = 20_000
+_MAX_SVG_PATH_CHARACTERS = 20_000_000
+_SVG_NAMESPACE = "http://www.w3.org/2000/svg"
+_ZIAMATH_LOCK = RLock()
+_SVG_PATH_COMMAND_RE = re.compile(r"[A-DF-Za-df-z]")
+
+
+class PdfFormulaError(ValueError):
+ """表示 LaTeX 或 ZiaMath SVG 无法安全转换为 PDF 矢量对象。"""
+
+
+@dataclass(frozen=True, slots=True)
+class FormulaVector:
+ """保存一个公式的 ReportLab Drawing 与基线几何。"""
+
+ drawing: Drawing
+ width: float
+ height: float
+ ascent: float
+ descent: float
+
+ def scaled(self, factor: float) -> FormulaVector:
+ """返回仅调整展示几何、不复制 Drawing 的等比公式对象。"""
+ return FormulaVector(
+ drawing=self.drawing,
+ width=self.width * factor,
+ height=self.height * factor,
+ ascent=self.ascent * factor,
+ descent=self.descent * factor,
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class InlineFormulaImage:
+ """作为 ReportLab Paragraph 行内图片占位的矢量公式代理。"""
+
+ vector: FormulaVector
+
+
+class FormulaRenderer:
+ """维护单份 PDF 文档内有界且无跨文档状态的公式缓存。"""
+
+ def __init__(self) -> None:
+ """初始化最多缓存 512 个唯一公式的文档级缓存。"""
+ self._cache: dict[tuple[str, bool, float, str], FormulaVector] = {}
+
+ def render(
+ self,
+ latex: str,
+ *,
+ inline: bool,
+ font_size: float,
+ color: str = "#1f2937",
+ ) -> FormulaVector:
+ """把一个裸 LaTeX 公式转换为行内或行间矢量对象。"""
+ if not isinstance(latex, str) or not latex.strip():
+ raise PdfFormulaError("formula must contain non-blank LaTeX")
+ if not isinstance(font_size, (int, float)) or isinstance(font_size, bool) or font_size <= 0:
+ raise PdfFormulaError("font_size must be a positive number")
+
+ key = (latex, inline, float(font_size), color)
+ if len(latex) <= MAX_FORMULA_CHARACTERS and key in self._cache:
+ return self._cache[key]
+
+ vector = _render_ziamath_formula(latex, inline=inline, font_size=float(font_size), color=color)
+ if len(latex) <= MAX_FORMULA_CHARACTERS and len(self._cache) < MAX_CACHED_FORMULAS:
+ self._cache[key] = vector
+ return vector
+
+
+class DisplayFormulaFlowable(Flowable):
+ """在可用行宽内居中绘制公式,并把可选编号贴到右边界。"""
+
+ def __init__(self, formula: FormulaVector, tag: FormulaVector | None = None) -> None:
+ """保存公式、可选编号以及延迟到 wrap 阶段计算的缩放参数。"""
+ super().__init__()
+ self.formula = formula
+ self.tag = tag
+ self._available_width = formula.width
+ self._formula_scale = 1.0
+ self._tag_scale = 1.0
+ self.width = formula.width
+ self.height = formula.height
+
+ def wrap(self, avail_width: float, _avail_height: float) -> tuple[float, float]:
+ """按正文宽度缩放主公式和编号,避免二者重叠或水平裁切。"""
+ self._available_width = max(1.0, avail_width)
+ tag_width = self.tag.width if self.tag is not None else 0.0
+ tag_gap = 10.0 if self.tag is not None else 0.0
+ main_limit = self._available_width if self.tag is None else max(1.0, self._available_width - tag_width - tag_gap)
+ self._formula_scale = min(1.0, main_limit / max(self.formula.width, 1.0))
+ if self.tag is not None and tag_width > self._available_width * 0.25:
+ self._tag_scale = min(1.0, self._available_width * 0.25 / max(tag_width, 1.0))
+ main_limit = max(1.0, self._available_width - tag_width * self._tag_scale - tag_gap)
+ self._formula_scale = min(self._formula_scale, main_limit / max(self.formula.width, 1.0))
+ formula_height = self.formula.height * self._formula_scale
+ tag_height = self.tag.height * self._tag_scale if self.tag is not None else 0.0
+ self.width = self._available_width
+ self.height = max(formula_height, tag_height, 1.0)
+ return self.width, self.height
+
+ def draw(self) -> None:
+ """把缩放后的主公式居中,并在同一垂直中心绘制右侧编号。"""
+ formula_width = self.formula.width * self._formula_scale
+ formula_height = self.formula.height * self._formula_scale
+ formula_x = max(0.0, (self._available_width - formula_width) / 2)
+ formula_y = max(0.0, (self.height - formula_height) / 2)
+ _draw_vector(self.canv, self.formula, formula_x, formula_y, self._formula_scale)
+ if self.tag is not None:
+ tag_width = self.tag.width * self._tag_scale
+ tag_height = self.tag.height * self._tag_scale
+ tag_x = max(0.0, self._available_width - tag_width)
+ tag_y = max(0.0, (self.height - tag_height) / 2)
+ _draw_vector(self.canv, self.tag, tag_x, tag_y, self._tag_scale)
+
+
+class _ReportLabPathPen(BasePen):
+ """把 FontTools SVG path 回调写入 ReportLab Path。"""
+
+ def __init__(self) -> None:
+ """创建不依赖 glyphSet 的空 ReportLab 路径。"""
+ super().__init__(None)
+ self.path = Path()
+
+ def _moveTo(self, point: tuple[float, float]) -> None:
+ """把 SVG move 命令写入目标路径。"""
+ self.path.moveTo(*point)
+
+ def _lineTo(self, point: tuple[float, float]) -> None:
+ """把 SVG line 命令写入目标路径。"""
+ self.path.lineTo(*point)
+
+ def _curveToOne(
+ self,
+ point1: tuple[float, float],
+ point2: tuple[float, float],
+ point3: tuple[float, float],
+ ) -> None:
+ """把三次曲线写入目标路径,二次曲线由 BasePen 自动转换。"""
+ self.path.curveTo(*point1, *point2, *point3)
+
+ def _closePath(self) -> None:
+ """闭合当前 ReportLab 子路径。"""
+ self.path.closePath()
+
+ def _endPath(self) -> None:
+ """结束不闭合的 SVG 子路径。"""
+
+
+def split_formula_tag(content: str) -> tuple[str, str | None]:
+ """剥离公式末尾括号平衡的 ``\\tag{...}``,并返回正文与编号。"""
+ stripped_end = len(content.rstrip())
+ if stripped_end == 0 or content[stripped_end - 1] != "}":
+ return content, None
+ search_end = stripped_end
+ while (tag_start := content.rfind(r"\tag", 0, search_end)) >= 0:
+ if not _is_escaped_character(content, tag_start):
+ opening_brace = _find_tag_opening_brace(content, tag_start, stripped_end)
+ if opening_brace is not None:
+ closing_brace = _find_balanced_closing_brace(content, opening_brace, stripped_end)
+ if closing_brace == stripped_end - 1:
+ return content[:tag_start].rstrip(), content[opening_brace + 1 : closing_brace].strip()
+ search_end = tag_start
+ return content, None
+
+
+def draw_inline_formula(
+ canvas: Any,
+ image: InlineFormulaImage,
+ x: float,
+ y: float,
+ width: float,
+ height: float,
+) -> tuple[float, float]:
+ """由自定义 Canvas 在 Paragraph 计算的位置绘制一个行内矢量公式。"""
+ vector = image.vector
+ scale = min(width / max(vector.width, 1.0), height / max(vector.height, 1.0))
+ _draw_vector(canvas, vector, x, y, scale)
+ return width, height
+
+
+def _render_ziamath_formula(latex: str, *, inline: bool, font_size: float, color: str) -> FormulaVector:
+ """在全局锁内临时关闭 SVG2 symbols,并转换单个 ZiaMath 结果。"""
+ try:
+ with _ZIAMATH_LOCK:
+ previous_svg2 = ziamath.config.svg2
+ ziamath.config.svg2 = False
+ try:
+ formula = ziamath.Latex(latex, inline=inline, size=font_size, color=color, margin=0)
+ root = formula.svgxml()
+ finally:
+ ziamath.config.svg2 = previous_svg2
+ return _svg_root_to_vector(root)
+ except PdfFormulaError:
+ raise
+ except Exception as exc:
+ raise PdfFormulaError(f"LaTeX formula cannot be rendered: {_formula_preview(latex)!r}") from exc
+
+
+def _svg_root_to_vector(root: ElementTree.Element) -> FormulaVector:
+ """把 ZiaMath 的固定 SVG 子集转换为坐标已翻转的 ReportLab Drawing。"""
+ namespace = root.get("xmlns") if root.tag == "svg" else root.tag.removeprefix("{").split("}", 1)[0]
+ if _local_name(root.tag) != "svg" or namespace != _SVG_NAMESPACE:
+ raise PdfFormulaError("ZiaMath output must contain an SVG root")
+ view_box = _parse_number_list(root.get("viewBox"), count=4, field="viewBox")
+ min_x, min_y, width, height = view_box
+ if width <= 0 or height <= 0:
+ raise PdfFormulaError("ZiaMath SVG dimensions must be positive")
+ drawing = Drawing(width, height)
+ root_group = Group()
+ root_group.transform = (1, 0, 0, -1, -min_x, min_y + height)
+ node_counter = [0]
+ path_budget = [0]
+ for child in root:
+ _append_svg_element(
+ root_group,
+ child,
+ inherited={},
+ node_counter=node_counter,
+ path_budget=path_budget,
+ )
+ drawing.add(root_group)
+ ascent = max(0.0, -min_y)
+ descent = max(0.0, min_y + height)
+ return FormulaVector(drawing=drawing, width=width, height=height, ascent=ascent, descent=descent)
+
+
+def _append_svg_element(
+ parent: Group,
+ element: ElementTree.Element,
+ *,
+ inherited: dict[str, str],
+ node_counter: list[int],
+ path_budget: list[int],
+) -> None:
+ """递归转换 ZiaMath 允许的 group、path 与 rect 节点。"""
+ node_counter[0] += 1
+ if node_counter[0] > _MAX_SVG_NODES:
+ raise PdfFormulaError("ZiaMath SVG exceeds its node limit")
+ tag = _local_name(element.tag)
+ if tag == "g":
+ _reject_unknown_attributes(element, {"fill", "stroke", "stroke-width"})
+ group_style = {**inherited, **element.attrib}
+ group = Group()
+ for child in element:
+ _append_svg_element(
+ group,
+ child,
+ inherited=group_style,
+ node_counter=node_counter,
+ path_budget=path_budget,
+ )
+ parent.add(group)
+ return
+ if tag == "path":
+ _reject_unknown_attributes(element, {"d", "fill", "stroke", "stroke-width"})
+ path_data = element.get("d", "")
+ path_budget[0] += len(path_data)
+ if not path_data or path_budget[0] > _MAX_SVG_PATH_CHARACTERS:
+ raise PdfFormulaError("ZiaMath SVG path data is empty or exceeds its limit")
+ commands = set(_SVG_PATH_COMMAND_RE.findall(path_data))
+ if not commands.issubset({"M", "L", "Q", "Z"}):
+ raise PdfFormulaError(f"Unsupported ZiaMath SVG path commands: {', '.join(sorted(commands))}")
+ pen = _ReportLabPathPen()
+ try:
+ parse_path(path_data, pen)
+ except Exception as exc:
+ raise PdfFormulaError("ZiaMath SVG path data is invalid") from exc
+ _apply_paint(pen.path, element.attrib, inherited)
+ parent.add(pen.path)
+ return
+ if tag == "rect":
+ _reject_unknown_attributes(element, {"x", "y", "width", "height", "fill", "stroke", "stroke-width"})
+ x, y, width, height = (_parse_number(element.get(name, "0"), field=name) for name in ("x", "y", "width", "height"))
+ if width < 0 or height < 0:
+ raise PdfFormulaError("ZiaMath SVG rect dimensions must not be negative")
+ rectangle = Rect(x, y, width, height)
+ _apply_paint(rectangle, element.attrib, inherited)
+ parent.add(rectangle)
+ return
+ raise PdfFormulaError(f"Unsupported ZiaMath SVG element: {tag}")
+
+
+def _apply_paint(shape: Any, attributes: dict[str, str], inherited: dict[str, str]) -> None:
+ """把受控 SVG fill、stroke 与 stroke-width 映射到 ReportLab shape。"""
+ fill = attributes.get("fill", inherited.get("fill", "black"))
+ stroke = attributes.get("stroke", inherited.get("stroke", "none"))
+ shape.fillColor = _parse_color(fill)
+ shape.strokeColor = _parse_color(stroke)
+ stroke_width = attributes.get("stroke-width", inherited.get("stroke-width", "1"))
+ shape.strokeWidth = _parse_number(stroke_width, field="stroke-width")
+
+
+def _parse_color(value: str) -> Color | None:
+ """解析 ZiaMath 生成的静态颜色,none 映射为透明。"""
+ if value.strip().casefold() == "none":
+ return None
+ try:
+ return toColor(value)
+ except Exception as exc:
+ raise PdfFormulaError(f"Unsupported ZiaMath SVG color: {value!r}") from exc
+
+
+def _parse_number(value: str, *, field: str) -> float:
+ """严格读取不含 CSS 单位的有限 SVG 数值。"""
+ try:
+ number = float(value)
+ except (TypeError, ValueError) as exc:
+ raise PdfFormulaError(f"Invalid ZiaMath SVG {field}: {value!r}") from exc
+ if number != number or number in (float("inf"), float("-inf")):
+ raise PdfFormulaError(f"Invalid ZiaMath SVG {field}: {value!r}")
+ return number
+
+
+def _parse_number_list(value: str | None, *, count: int, field: str) -> tuple[float, ...]:
+ """读取固定长度的空白或逗号分隔 SVG 数值列表。"""
+ if value is None:
+ raise PdfFormulaError(f"ZiaMath SVG is missing {field}")
+ values = tuple(_parse_number(item, field=field) for item in value.replace(",", " ").split())
+ if len(values) != count:
+ raise PdfFormulaError(f"ZiaMath SVG {field} must contain {count} numbers")
+ return values
+
+
+def _reject_unknown_attributes(element: ElementTree.Element, allowed: set[str]) -> None:
+ """拒绝 ZiaMath 固定子集之外的 SVG 属性。"""
+ unexpected = set(element.attrib) - allowed
+ if unexpected:
+ raise PdfFormulaError(f"Unsupported ZiaMath SVG attributes: {', '.join(sorted(unexpected))}")
+
+
+def _local_name(tag: str) -> str:
+ """返回可带 XML namespace 的元素本地名称。"""
+ return tag.rsplit("}", 1)[-1]
+
+
+def _formula_preview(latex: str) -> str:
+ """为告警生成有界 LaTeX 摘要,避免超长公式污染日志。"""
+ return latex if len(latex) <= 200 else f"{latex[:197]}..."
+
+
+def _draw_vector(canvas: Any, vector: FormulaVector, x: float, y: float, scale: float) -> None:
+ """在 canvas 上按给定位置和比例绘制公式 Drawing。"""
+ canvas.saveState()
+ try:
+ canvas.translate(x, y)
+ canvas.scale(scale, scale)
+ vector.drawing.drawOn(canvas, 0, 0)
+ finally:
+ canvas.restoreState()
+
+
+def _find_tag_opening_brace(content: str, tag_start: int, content_end: int) -> int | None:
+ """查找 tag 命令允许空白后的左花括号。"""
+ cursor = tag_start + len(r"\tag")
+ while cursor < content_end and content[cursor].isspace():
+ cursor += 1
+ return cursor if cursor < content_end and content[cursor] == "{" else None
+
+
+def _find_balanced_closing_brace(content: str, opening_brace: int, content_end: int) -> int | None:
+ """查找与 tag 左花括号配对的右花括号,并忽略转义花括号。"""
+ depth = 0
+ for cursor in range(opening_brace, content_end):
+ character = content[cursor]
+ if character not in "{}" or _is_escaped_character(content, cursor):
+ continue
+ depth += 1 if character == "{" else -1
+ if depth == 0:
+ return cursor
+ if depth < 0:
+ return None
+ return None
+
+
+def _is_escaped_character(content: str, position: int) -> bool:
+ """判断指定字符前是否存在奇数个连续反斜杠。"""
+ preceding_backslashes = 0
+ cursor = position - 1
+ while cursor >= 0 and content[cursor] == "\\":
+ preceding_backslashes += 1
+ cursor -= 1
+ return preceding_backslashes % 2 == 1
+
+
+__all__ = [
+ "DisplayFormulaFlowable",
+ "FormulaRenderer",
+ "FormulaVector",
+ "InlineFormulaImage",
+ "MAX_CACHED_FORMULAS",
+ "MAX_FORMULA_CHARACTERS",
+ "PdfFormulaError",
+ "draw_inline_formula",
+ "split_formula_tag",
+]
diff --git a/mineru/render/_internal/pdf/inline.py b/mineru/render/_internal/pdf/inline.py
new file mode 100644
index 00000000..9c84df21
--- /dev/null
+++ b/mineru/render/_internal/pdf/inline.py
@@ -0,0 +1,340 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""Middle JSON InlineSpan 到 ReportLab Paragraph fragment 的转换。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from hashlib import sha1
+import html
+import re
+from typing import Iterable
+
+from loguru import logger
+from reportlab.lib.abag import ABag
+from reportlab.lib.styles import ParagraphStyle
+from reportlab.platypus import Paragraph
+from reportlab.platypus.paraparser import ParaParser
+
+from ....types import CodeInlineSpan, EquationInlineSpan, HyperlinkSpan, InlineSpan, TextSpan
+from .formula import FormulaRenderer, InlineFormulaImage, PdfFormulaError
+from .styles import ACCENT_COLOR, HAN_FONT, JAPANESE_FONT, KOREAN_FONT, MONO_FONT
+
+_BOOKMARK_SAFE_RE = re.compile(r"[^A-Za-z0-9_]+")
+_BOOKMARK_MAX_LENGTH = 80
+_FORMULA_SOURCE_PREFIX = "mineru-formula:"
+_INVALID_TEXT_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]")
+
+
+class PdfAnchorRegistry:
+ """把 MiddleJson anchor 映射为稳定唯一的 PDF destination 名称。"""
+
+ def __init__(self, anchors: Iterable[str]) -> None:
+ """预注册全部可见标题与页面脚注 anchor。"""
+ self._names: dict[str, str] = {}
+ self._attached: set[str] = set()
+ self._used_names: set[str] = set()
+ for anchor in anchors:
+ normalized = anchor.strip()
+ if normalized and normalized not in self._names:
+ self._names[normalized] = self._allocate_name(normalized)
+
+ def resolve(self, anchor: str | None) -> str | None:
+ """解析已注册 anchor,空值或未知值返回 None。"""
+ normalized = (anchor or "").strip()
+ return self._names.get(normalized) if normalized else None
+
+ def attach_markup(self, anchor: str | None) -> str:
+ """返回首个目标的 Paragraph anchor 标签,重复目标仅记录告警。"""
+ normalized = (anchor or "").strip()
+ name = self.resolve(normalized)
+ if name is None:
+ return ""
+ if normalized in self._attached:
+ logger.warning("Duplicate PDF anchor ignored: {}", normalized)
+ return ""
+ self._attached.add(normalized)
+ return f'<a name="{html.escape(name, quote=True)}"/>'
+
+ def _allocate_name(self, anchor: str) -> str:
+ """为原始 anchor 分配合法 ASCII destination,并稳定处理碰撞。"""
+ base = _BOOKMARK_SAFE_RE.sub("_", anchor).strip("_")
+ if not base or not base[0].isalpha():
+ base = f"b_{base}"
+ candidate = base[:_BOOKMARK_MAX_LENGTH]
+ if candidate not in self._used_names:
+ self._used_names.add(candidate)
+ return candidate
+ digest = sha1(anchor.encode("utf-8")).hexdigest()[:10]
+ prefix_length = _BOOKMARK_MAX_LENGTH - len(digest) - 1
+ candidate = f"{base[:prefix_length]}_{digest}"
+ ordinal = 1
+ while candidate in self._used_names:
+ suffix = f"_{ordinal}"
+ candidate = f"{candidate[: _BOOKMARK_MAX_LENGTH - len(suffix)]}{suffix}"
+ ordinal += 1
+ self._used_names.add(candidate)
+ return candidate
+
+
+@dataclass(slots=True)
+class PdfInlineContext:
+ """保存一份 PDF 文档共享的公式、anchor 与定位状态。"""
+
+ formulas: FormulaRenderer
+ anchors: PdfAnchorRegistry
+ formula_images: dict[str, InlineFormulaImage] = field(default_factory=dict)
+ next_formula_id: int = 0
+
+ def location(self, page_idx: int, block_index: int | None, block_type: str) -> str:
+ """返回稳定的 page/block 告警定位文本。"""
+ return f"page_idx={page_idx}, block_index={block_index}, block_type={block_type}"
+
+ def register_formula(self, image: InlineFormulaImage) -> str:
+ """注册一个 Paragraph 可引用的行内公式代理并返回内部 token。"""
+ token = f"{_FORMULA_SOURCE_PREFIX}{self.next_formula_id}"
+ self.next_formula_id += 1
+ self.formula_images[token] = image
+ return token
+
+
+class _PdfParaParser(ParaParser):
+ """让 ReportLab Paragraph 接受不经 ImageReader 的行内公式 token。"""
+
+ def __init__(self, formula_images: dict[str, InlineFormulaImage]) -> None:
+ """保存当前文档的公式代理映射。"""
+ super().__init__()
+ self._formula_images = formula_images
+
+ def end_img(self) -> None:
+ """把 mineru-formula token 解析为带基线几何的矢量图片 fragment。"""
+ frag = self._stack[-1]
+ if not getattr(frag, "_selfClosingTag", ""):
+ raise ValueError("Parser failure in <img/>")
+ source = str(getattr(frag, "src", ""))
+ image = self._formula_images.get(source)
+ if image is None:
+ raise ValueError(f"Unknown PDF inline formula token: {source}")
+ vector = image.vector
+ definition = frag.cbDefn = ABag()
+ definition.kind = "img"
+ definition.src = source
+ definition.image = image
+ definition.width = vector.width
+ definition.height = vector.height
+ definition.valign = -vector.descent
+ del frag._selfClosingTag
+ self.handle_data("")
+ self._pop("img")
+
+
+def build_pdf_paragraph(
+ spans: list[InlineSpan],
+ style: ParagraphStyle,
+ *,
+ context: PdfInlineContext,
+ page_idx: int,
+ block_index: int | None,
+ block_type: str,
+ max_width: float,
+ anchor: str | None = None,
+ preserve_newlines: bool = False,
+) -> Paragraph:
+ """把完整 InlineSpan 列表构造成支持矢量公式与链接的 Paragraph。"""
+ markup = context.anchors.attach_markup(anchor)
+ markup += render_pdf_inline_markup(
+ spans,
+ context=context,
+ page_idx=page_idx,
+ block_index=block_index,
+ block_type=block_type,
+ font_size=style.fontSize,
+ max_width=max_width,
+ preserve_newlines=preserve_newlines,
+ )
+ parser = _PdfParaParser(context.formula_images)
+ parsed_style, fragments, bullet_fragments = parser.parse(markup or "&#8203;", style)
+ bullet_text = None
+ if bullet_fragments:
+ bullet_text = "".join(getattr(fragment, "text", "") for fragment in bullet_fragments)
+ return Paragraph("", parsed_style, bulletText=bullet_text, frags=fragments)
+
+
+def render_pdf_inline_markup(
+ spans: list[InlineSpan],
+ *,
+ context: PdfInlineContext,
+ page_idx: int,
+ block_index: int | None,
+ block_type: str,
+ font_size: float,
+ max_width: float,
+ preserve_newlines: bool = False,
+) -> str:
+ """把行内 Span 转成仅包含 renderer 生成标签的安全 Paragraph markup。"""
+ return "".join(
+ _render_span(
+ span,
+ context=context,
+ page_idx=page_idx,
+ block_index=block_index,
+ block_type=block_type,
+ font_size=font_size,
+ max_width=max_width,
+ preserve_newlines=preserve_newlines,
+ )
+ for span in spans
+ )
+
+
+def render_plain_text_markup(text: str, *, preserve_newlines: bool = False) -> str:
+ """转义普通文本,并按字符脚本显式选择 Latin 或中日韩字体。"""
+ normalized = _INVALID_TEXT_RE.sub("\ufffd", text)
+ if not normalized:
+ return ""
+ segments: list[str] = []
+ current_font: str | None = None
+ current_text: list[str] = []
+
+ def flush() -> None:
+ """把当前同字体字符片段编码为 Paragraph markup。"""
+ if not current_text:
+ return
+ escaped = html.escape("".join(current_text), quote=False)
+ if preserve_newlines:
+ escaped = escaped.replace("\n", "<br/>")
+ else:
+ escaped = escaped.replace("\n", " ")
+ if current_font is None:
+ segments.append(escaped)
+ else:
+ segments.append(f'<font name="{current_font}">{escaped}</font>')
+ current_text.clear()
+
+ for character in normalized:
+ font = _font_for_character(character)
+ if font != current_font:
+ flush()
+ current_font = font
+ current_text.append(character)
+ flush()
+ return "".join(segments)
+
+
+def _render_span(
+ span: InlineSpan,
+ *,
+ context: PdfInlineContext,
+ page_idx: int,
+ block_index: int | None,
+ block_type: str,
+ font_size: float,
+ max_width: float,
+ preserve_newlines: bool,
+) -> str:
+ """按 InlineSpan discriminator 输出单个安全 Paragraph 片段。"""
+ if isinstance(span, TextSpan):
+ markup = render_plain_text_markup(span.content, preserve_newlines=preserve_newlines)
+ return _apply_text_styles(markup, tuple(span.styles))
+ if isinstance(span, CodeInlineSpan):
+ markup = render_plain_text_markup(span.content, preserve_newlines=preserve_newlines)
+ return f'<font name="{MONO_FONT}" size="{max(6.0, font_size * 0.9):.3f}">{markup}</font>'
+ if isinstance(span, EquationInlineSpan):
+ try:
+ vector = context.formulas.render(span.content, inline=True, font_size=font_size)
+ if vector.width > max_width > 0:
+ vector = vector.scaled(max_width / vector.width)
+ token = context.register_formula(InlineFormulaImage(vector))
+ return (
+ f'<img src="{token}" width="{vector.width:.3f}" height="{vector.height:.3f}" valign="{-vector.descent:.3f}"/>'
+ )
+ except PdfFormulaError as exc:
+ logger.warning(
+ "PDF inline formula fallback: {} ({})",
+ exc,
+ context.location(page_idx, block_index, block_type),
+ )
+ fallback = render_plain_text_markup(f"${span.content}$", preserve_newlines=preserve_newlines)
+ return f'<font name="{MONO_FONT}" color="#6b7280">{fallback}</font>'
+ if isinstance(span, HyperlinkSpan):
+ child_markup = "".join(
+ _render_span(
+ child,
+ context=context,
+ page_idx=page_idx,
+ block_index=block_index,
+ block_type=block_type,
+ font_size=font_size,
+ max_width=max_width,
+ preserve_newlines=preserve_newlines,
+ )
+ for child in span.content
+ )
+ target = _resolve_link_target(span.url, context.anchors)
+ if target is None:
+ if span.url.startswith("#"):
+ logger.warning(
+ "Unmatched PDF internal link: {} ({})",
+ span.url,
+ context.location(page_idx, block_index, block_type),
+ )
+ return child_markup
+ return f'<a href="{html.escape(target, quote=True)}" color="{ACCENT_COLOR.hexval()}" underline="1">{child_markup}</a>'
+ raise TypeError(f"Unsupported InlineSpan type: {type(span).__name__}")
+
+
+def _apply_text_styles(markup: str, styles: tuple[str, ...]) -> str:
+ """按固定顺序把 MiddleJson 文本样式映射到 Paragraph 标签。"""
+ if not markup:
+ return ""
+ tags: list[str] = []
+ if "bold" in styles:
+ tags.append("b")
+ if "italic" in styles:
+ tags.append("i")
+ if "underline" in styles or "emphasis" in styles:
+ tags.append("u")
+ if "strikethrough" in styles:
+ tags.append("strike")
+ if "superscript" in styles:
+ tags.append("super")
+ elif "subscript" in styles:
+ tags.append("sub")
+ for tag in tags:
+ markup = f"<{tag}>{markup}</{tag}>"
+ return markup
+
+
+def _resolve_link_target(url: str, anchors: PdfAnchorRegistry) -> str | None:
+ """把 fragment 映射为 PDF destination,其他安全 URL 原样保留。"""
+ if url.startswith("#"):
+ destination = anchors.resolve(url[1:])
+ return f"#{destination}" if destination is not None else None
+ return url or None
+
+
+def _font_for_character(character: str) -> str | None:
+ """按 Unicode 区段为中日韩及其它非 Latin 字符选择标准 CID 字体。"""
+ codepoint = ord(character)
+ if 0x3040 <= codepoint <= 0x30FF or 0x31F0 <= codepoint <= 0x31FF or 0xFF66 <= codepoint <= 0xFF9D:
+ return JAPANESE_FONT
+ if 0x1100 <= codepoint <= 0x11FF or 0x3130 <= codepoint <= 0x318F or 0xAC00 <= codepoint <= 0xD7AF:
+ return KOREAN_FONT
+ if (
+ 0x2E80 <= codepoint <= 0x303F
+ or 0x3400 <= codepoint <= 0x4DBF
+ or 0x4E00 <= codepoint <= 0x9FFF
+ or 0xF900 <= codepoint <= 0xFAFF
+ or 0xFF00 <= codepoint <= 0xFF65
+ or codepoint >= 0x10000
+ ):
+ return HAN_FONT
+ return None
+
+
+__all__ = [
+ "PdfAnchorRegistry",
+ "PdfInlineContext",
+ "build_pdf_paragraph",
+ "render_pdf_inline_markup",
+ "render_plain_text_markup",
+]
diff --git a/mineru/render/_internal/pdf/renderer.py b/mineru/render/_internal/pdf/renderer.py
new file mode 100644
index 00000000..1b09c650
--- /dev/null
+++ b/mineru/render/_internal/pdf/renderer.py
@@ -0,0 +1,755 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到 ReportLab PDF bytes 的公共渲染实现。"""
+
+from __future__ import annotations
+
+from functools import partial
+import html
+from io import BytesIO
+import re
+from typing import Any, Iterable
+
+from bs4 import BeautifulSoup
+from loguru import logger
+from reportlab.lib.pagesizes import A4
+from reportlab.lib.styles import ParagraphStyle
+from reportlab.lib.units import mm
+from reportlab.pdfgen.canvas import Canvas
+from reportlab.platypus import (
+ Flowable,
+ Image as ReportLabImage,
+ PageBreak,
+ Paragraph,
+ SimpleDocTemplate,
+ Spacer,
+ Table,
+ TableStyle,
+)
+
+from ....backend.postprocess.inline import inline_plain_text, join_inline_spans
+from ..common.index import strip_index_page_tail
+from ..common.list_items import parse_list_item_marker, reference_list_needs_bullets
+from ..common.planner import PlannedBlock, build_render_plan
+from ...contracts import AssetResolver, RenderMode
+from ....types import (
+ PAGE_AUXILIARY_BLOCK_TYPES,
+ RAW_ALGORITHM,
+ AlgorithmBodyBlock,
+ BlockBase,
+ BlockType,
+ ChartAnnotationBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeAnnotationBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ DocTitleBlock,
+ EquationBlock,
+ HyperlinkSpan,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ ImagePayloadBlock,
+ IndexBlock,
+ InlineSpan,
+ ListBlock,
+ MiddleJson,
+ NonLinkInlineSpan,
+ PageAuxTextBlock,
+ PageFootnoteBlock,
+ ParagraphTitleBlock,
+ RefTextBlock,
+ TableAnnotationBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+ TextSpan,
+ TitleBlockBase,
+)
+from .assets import PdfAssetError, PreparedImage, prepare_block_image, prepare_html_image
+from .formula import (
+ DisplayFormulaFlowable,
+ FormulaRenderer,
+ InlineFormulaImage,
+ PdfFormulaError,
+ draw_inline_formula,
+ split_formula_tag,
+)
+from .inline import PdfAnchorRegistry, PdfInlineContext, build_pdf_paragraph, render_plain_text_markup
+from .styles import (
+ BORDER_COLOR,
+ PAGE_MARGIN,
+ SURFACE_COLOR,
+ build_pdf_styles,
+)
+from .table import PdfTableError, build_pdf_tables
+
+_HTML_TABLE_RE = re.compile(r"<table\b", re.IGNORECASE)
+_INVALID_METADATA_TEXT_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff\ufffe\uffff]")
+_VISIBLE_HTML_TAGS = (
+ "a",
+ "b",
+ "blockquote",
+ "br",
+ "code",
+ "div",
+ "em",
+ "eq",
+ "i",
+ "li",
+ "ol",
+ "p",
+ "pre",
+ "span",
+ "strong",
+ "sub",
+ "sup",
+ "table",
+ "u",
+ "ul",
+)
+_MAX_PLACEHOLDER_TEXT = 320
+_MIN_IMAGE_WIDTH = 5 * mm
+_PLACEHOLDER_HEIGHT = 18 * mm
+
+
+class _PdfCanvas(Canvas):
+ """提供确定性 metadata 与行内 ZiaMath 矢量绘制的 ReportLab Canvas。"""
+
+ def __init__(self, filename: Any, *args: Any, document_title: str, **kwargs: Any) -> None:
+ """创建启用压缩和 invariant 的 PDF canvas,并写入稳定 metadata。"""
+ kwargs.setdefault("pageCompression", 1)
+ kwargs["invariant"] = 1
+ super().__init__(filename, *args, **kwargs)
+ self.setTitle(document_title)
+ self.setAuthor("MinerU")
+ self.setCreator("MinerU PDF Renderer")
+ self.setSubject("Semantic document rendering from MiddleJson")
+ self.setKeywords("MinerU, MiddleJson, PDF")
+
+ def drawImage(
+ self,
+ image: Any,
+ x: float,
+ y: float,
+ width: float | None = None,
+ height: float | None = None,
+ mask: Any = None,
+ preserveAspectRatio: bool = False,
+ anchor: str = "c",
+ anchorAtXY: bool = False,
+ showBoundary: bool = False,
+ ) -> Any:
+ """识别 Paragraph 传入的公式代理,否则沿用标准 raster 图片行为。"""
+ if isinstance(image, InlineFormulaImage):
+ resolved_width = image.vector.width if width is None else float(width)
+ resolved_height = image.vector.height if height is None else float(height)
+ return draw_inline_formula(self, image, x, y, resolved_width, resolved_height)
+ return super().drawImage(
+ image,
+ x,
+ y,
+ width,
+ height,
+ mask=mask,
+ preserveAspectRatio=preserveAspectRatio,
+ anchor=anchor,
+ anchorAtXY=anchorAtXY,
+ showBoundary=showBoundary,
+ )
+
+
+class _PdfRenderer:
+ """维护一次 MiddleJson 到 PDF 渲染所需的样式、公式与素材状态。"""
+
+ def __init__(
+ self,
+ middle_json: MiddleJson,
+ *,
+ mode: RenderMode,
+ asset_resolver: AssetResolver | None,
+ document_title: str | None,
+ ) -> None:
+ """保存严格输入,并预注册标题及页面脚注 anchor。"""
+ self.middle_json = middle_json
+ self.mode = mode
+ self.asset_resolver = asset_resolver
+ self.document_title = _resolve_document_title(middle_json, document_title)
+ self.styles = build_pdf_styles()
+ self.available_width = A4[0] - 2 * PAGE_MARGIN
+ self.available_height = A4[1] - 2 * PAGE_MARGIN
+ self.inline_context = PdfInlineContext(
+ formulas=FormulaRenderer(),
+ anchors=PdfAnchorRegistry(_iter_document_anchors(middle_json)),
+ )
+
+ def render(self) -> bytes:
+ """构造逐页 story,并将确定性 ReportLab 文档序列化为 bytes。"""
+ story: list[Flowable] = []
+ planned_pages = build_render_plan(self.middle_json, self.mode)
+ for page_position, planned_blocks in enumerate(planned_pages):
+ if self.mode is RenderMode.FULL and page_position > 0:
+ story.append(PageBreak())
+ rendered_count = 0
+ for planned in planned_blocks:
+ if planned.removed:
+ continue
+ if self.mode is RenderMode.DEFAULT and planned.block.type in PAGE_AUXILIARY_BLOCK_TYPES:
+ continue
+ rendered = self._render_planned_block(planned)
+ story.extend(rendered)
+ rendered_count += len(rendered)
+ if self.mode is RenderMode.FULL and rendered_count == 0:
+ story.append(Spacer(1, 1))
+ if not story:
+ story.append(Spacer(1, 1))
+
+ output = BytesIO()
+ document = SimpleDocTemplate(
+ output,
+ pagesize=A4,
+ leftMargin=PAGE_MARGIN,
+ rightMargin=PAGE_MARGIN,
+ topMargin=PAGE_MARGIN,
+ bottomMargin=PAGE_MARGIN,
+ title=self.document_title,
+ author="MinerU",
+ creator="MinerU PDF Renderer",
+ subject="Semantic document rendering from MiddleJson",
+ keywords="MinerU, MiddleJson, PDF",
+ invariant=1,
+ pageCompression=1,
+ )
+ document.build(
+ story,
+ canvasmaker=partial(_PdfCanvas, document_title=self.document_title),
+ )
+ return output.getvalue()
+
+ def _render_planned_block(self, planned: PlannedBlock) -> list[Flowable]:
+ """按严格 PageBlock 具体类型分派 PDF Flowable visitor。"""
+ block = planned.block
+ if isinstance(block, (TextBlock, RefTextBlock)):
+ spans = join_inline_spans(planned.text_contents or [block.content])
+ return [self._paragraph(spans, self.styles.body, planned.page_idx, block)]
+ if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
+ return [
+ self._paragraph(
+ block.content,
+ self.styles.heading(block.level),
+ planned.page_idx,
+ block,
+ anchor=block.anchor,
+ )
+ ]
+ if isinstance(block, PageFootnoteBlock):
+ return [
+ self._paragraph(
+ block.content,
+ self.styles.footnote,
+ planned.page_idx,
+ block,
+ anchor=block.anchor,
+ )
+ ]
+ if isinstance(block, PageAuxTextBlock):
+ return [self._paragraph(block.content, self.styles.auxiliary, planned.page_idx, block)]
+ if isinstance(block, EquationBlock):
+ return self._render_equation(block, planned.page_idx)
+ if isinstance(block, ListBlock):
+ return self._render_list(block, planned.page_idx, depth=0)
+ if isinstance(block, IndexBlock):
+ return self._render_index(block, planned.page_idx, depth=0)
+ if isinstance(block, ImageBlock):
+ return self._render_image_block(block, planned.page_idx)
+ if isinstance(block, TableBlock):
+ return self._render_table_block(block, planned.page_idx)
+ if isinstance(block, ChartBlock):
+ return self._render_chart_block(block, planned.page_idx)
+ if isinstance(block, CodeBlock):
+ return self._render_code_block(block, planned.page_idx)
+ raise TypeError(f"Unsupported PageBlock type: {type(block).__name__}")
+
+ def _paragraph(
+ self,
+ spans: list[InlineSpan],
+ style: ParagraphStyle,
+ page_idx: int,
+ block: BlockBase,
+ *,
+ anchor: str | None = None,
+ preserve_newlines: bool = False,
+ max_width: float | None = None,
+ ) -> Paragraph:
+ """为当前 block 构造带定位、anchor 与矢量公式的 Paragraph。"""
+ return build_pdf_paragraph(
+ spans,
+ style,
+ context=self.inline_context,
+ page_idx=page_idx,
+ block_index=block.index,
+ block_type=str(block.type),
+ max_width=self.available_width if max_width is None else max_width,
+ anchor=anchor,
+ preserve_newlines=preserve_newlines,
+ )
+
+ def _render_equation(self, block: EquationBlock, page_idx: int) -> list[Flowable]:
+ """优先输出 ZiaMath display 矢量,失败后使用图片、LaTeX 或占位。"""
+ content = block.content.strip()
+ if content:
+ formula, tag = split_formula_tag(content)
+ try:
+ vector = self.inline_context.formulas.render(formula or content, inline=False, font_size=14)
+ tag_vector = None
+ if tag:
+ tag_vector = self.inline_context.formulas.render(f"({tag})", inline=True, font_size=9)
+ flowable = DisplayFormulaFlowable(vector, tag_vector)
+ flowable.spaceBefore = 5
+ flowable.spaceAfter = 7
+ return [flowable]
+ except PdfFormulaError as exc:
+ logger.warning("PDF display formula fallback: {} ({})", exc, self._location(page_idx, block))
+ if _has_image_payload(block):
+ image = self._try_prepared_block_image(block, page_idx)
+ if image is not None:
+ return [self._prepared_image_flowable(image, block)]
+ if content:
+ return [
+ self._paragraph(
+ [TextSpan(type="text", content=content)],
+ self.styles.formula_fallback,
+ page_idx,
+ block,
+ preserve_newlines=True,
+ )
+ ]
+ return [self._placeholder("formula unavailable", block=block, page_idx=page_idx)]
+
+ def _render_list(self, block: ListBlock, page_idx: int, *, depth: int) -> list[Flowable]:
+ """保留 producer marker,以缩进和悬挂缩进表达递归列表。"""
+ rendered: list[Flowable] = []
+ add_reference_bullets = reference_list_needs_bullets(block)
+ for child in block.content:
+ if isinstance(child, ListBlock):
+ rendered.extend(self._render_list(child, page_idx, depth=depth + 1))
+ continue
+ spans = list(child.content)
+ parsed = parse_list_item_marker(spans)
+ if add_reference_bullets and parsed.marker is None and inline_plain_text(spans).strip():
+ spans = [TextSpan(type="text", content="- "), *spans]
+ parsed = parse_list_item_marker(spans)
+ style = ParagraphStyle(
+ f"MinerU PDF List {depth} {len(rendered)}",
+ parent=self.styles.body,
+ leftIndent=(depth + (1 if parsed.marker else 0)) * 14,
+ firstLineIndent=-14 if parsed.marker else 0,
+ spaceAfter=3,
+ )
+ rendered.append(self._paragraph(spans, style, page_idx, child))
+ return rendered
+
+ def _render_index(self, block: IndexBlock, page_idx: int, *, depth: int) -> list[Flowable]:
+ """递归输出目录叶子,并把已注册标题 anchor 写成内部链接。"""
+ rendered: list[Flowable] = []
+ for child in block.content:
+ if isinstance(child, IndexBlock):
+ rendered.extend(self._render_index(child, page_idx, depth=depth + 1))
+ continue
+ content = strip_index_page_tail(child.content)
+ if not content:
+ continue
+ spans: list[InlineSpan] = [TextSpan(type="text", content="• ")]
+ if isinstance(child, TitleBlockBase) and child.anchor:
+ link_content = _flatten_non_link_spans(content)
+ if link_content:
+ spans.append(HyperlinkSpan(type="hyperlink", url=f"#{child.anchor}", content=link_content))
+ else:
+ spans.extend(content)
+ style = ParagraphStyle(
+ f"MinerU PDF Index {depth} {len(rendered)}",
+ parent=self.styles.body,
+ leftIndent=(depth + 1) * 14,
+ firstLineIndent=-10,
+ spaceAfter=3,
+ )
+ rendered.append(self._paragraph(spans, style, page_idx, child))
+ return rendered
+
+ def _render_image_block(self, block: ImageBlock, page_idx: int) -> list[Flowable]:
+ """按原始子块顺序输出图片主体、宽松占位与说明。"""
+ rendered: list[Flowable] = []
+ for child in block.content:
+ if isinstance(child, ImageBodyBlock):
+ alt_text = _plain_html_text(child.content) or block.sub_type or "image"
+ flowable, succeeded = self._image_or_placeholder(child, page_idx=page_idx, alt_text=alt_text)
+ rendered.append(flowable)
+ if not succeeded and child.content.strip():
+ rendered.append(
+ self._paragraph(
+ [TextSpan(type="text", content=_plain_html_text(child.content))],
+ self.styles.footnote,
+ page_idx,
+ child,
+ )
+ )
+ elif isinstance(child, ImageAnnotationBlock):
+ rendered.append(self._render_annotation(child, page_idx))
+ else:
+ raise TypeError(f"Unsupported image child: {type(child).__name__}")
+ return rendered
+
+ def _render_table_block(self, block: TableBlock, page_idx: int) -> list[Flowable]:
+ """优先输出原生 HTML table,再回退空间文本、图片或占位。"""
+ rendered: list[Flowable] = []
+ for child in block.content:
+ if isinstance(child, TableBodyBlock):
+ content = child.content.strip()
+ if content and _HTML_TABLE_RE.search(content):
+ try:
+ rendered.extend(self._html_tables(content, page_idx=page_idx, block=child))
+ continue
+ except PdfTableError as exc:
+ logger.warning("PDF HTML table fallback: {} ({})", exc, self._location(page_idx, child))
+ if _has_image_payload(child):
+ image = self._try_prepared_block_image(child, page_idx)
+ if image is not None:
+ rendered.append(self._prepared_image_flowable(image, child))
+ continue
+ plain = _plain_html_text(content)
+ if plain:
+ rendered.append(self._preformatted(plain, page_idx, child, self.styles.spatial_table))
+ rendered.append(self._placeholder("table unavailable", block=child, page_idx=page_idx))
+ elif content:
+ rendered.append(self._preformatted(child.content, page_idx, child, self.styles.spatial_table))
+ else:
+ flowable, _succeeded = self._image_or_placeholder(child, page_idx=page_idx, alt_text="table")
+ rendered.append(flowable)
+ elif isinstance(child, TableAnnotationBlock):
+ rendered.append(self._render_annotation(child, page_idx))
+ else:
+ raise TypeError(f"Unsupported table child: {type(child).__name__}")
+ return rendered
+
+ def _render_chart_block(self, block: ChartBlock, page_idx: int) -> list[Flowable]:
+ """输出 chart 图片或占位,并继续保留可物化的结构化内容。"""
+ rendered: list[Flowable] = []
+ for child in block.content:
+ if isinstance(child, ChartBodyBlock):
+ has_image = _has_image_payload(child)
+ image_succeeded = False
+ if has_image:
+ flowable, image_succeeded = self._image_or_placeholder(
+ child,
+ page_idx=page_idx,
+ alt_text=block.sub_type or "chart",
+ )
+ rendered.append(flowable)
+ content = child.content.strip()
+ if content and _HTML_TABLE_RE.search(content):
+ try:
+ rendered.extend(self._html_tables(content, page_idx=page_idx, block=child))
+ except PdfTableError as exc:
+ logger.warning("PDF chart table omitted: {} ({})", exc, self._location(page_idx, child))
+ if not image_succeeded:
+ rendered.append(self._preformatted(_plain_html_text(content), page_idx, child, self.styles.body))
+ elif content and not image_succeeded:
+ rendered.append(
+ self._paragraph(
+ [TextSpan(type="text", content=_plain_html_text(content))],
+ self.styles.body,
+ page_idx,
+ child,
+ )
+ )
+ elif not has_image and not content:
+ rendered.append(self._placeholder("chart unavailable", block=child, page_idx=page_idx))
+ elif isinstance(child, ChartAnnotationBlock):
+ rendered.append(self._render_annotation(child, page_idx))
+ else:
+ raise TypeError(f"Unsupported chart child: {type(child).__name__}")
+ return rendered
+
+ def _render_code_block(self, block: CodeBlock, page_idx: int) -> list[Flowable]:
+ """使用等宽浅色块输出代码或带矢量公式的算法正文。"""
+ rendered: list[Flowable] = []
+ for child in block.content:
+ if isinstance(child, CodeBodyBlock):
+ if block.sub_type != BlockType.CODE:
+ raise TypeError("code_body requires code subtype")
+ rendered.append(
+ self._paragraph(
+ [TextSpan(type="text", content=child.content or " ")],
+ self.styles.code,
+ page_idx,
+ child,
+ preserve_newlines=True,
+ )
+ )
+ elif isinstance(child, AlgorithmBodyBlock):
+ if block.sub_type != RAW_ALGORITHM:
+ raise TypeError("algorithm_body requires algorithm subtype")
+ rendered.append(
+ self._paragraph(
+ child.content,
+ self.styles.code,
+ page_idx,
+ child,
+ preserve_newlines=True,
+ )
+ )
+ elif isinstance(child, CodeAnnotationBlock):
+ rendered.append(self._render_annotation(child, page_idx))
+ else:
+ raise TypeError(f"Unsupported code child: {type(child).__name__}")
+ return rendered
+
+ def _render_annotation(
+ self,
+ block: ImageAnnotationBlock | TableAnnotationBlock | ChartAnnotationBlock | CodeAnnotationBlock,
+ page_idx: int,
+ ) -> Paragraph:
+ """根据 caption/footnote discriminator 选择弱化说明样式。"""
+ style = self.styles.caption if str(block.type).endswith("caption") else self.styles.footnote
+ return self._paragraph(block.content, style, page_idx, block)
+
+ def _preformatted(
+ self,
+ content: str,
+ page_idx: int,
+ block: BlockBase,
+ style: ParagraphStyle,
+ ) -> Paragraph:
+ """把需要保留换行和空白的普通字符串写为 Paragraph。"""
+ return self._paragraph(
+ [TextSpan(type="text", content=content or " ")],
+ style,
+ page_idx,
+ block,
+ preserve_newlines=True,
+ )
+
+ def _html_tables(self, content: str, *, page_idx: int, block: BlockBase) -> list[Table]:
+ """使用当前 block 上下文把 HTML table 物化为 ReportLab 表格。"""
+
+ def build_paragraph(spans: list[InlineSpan], style: object, max_width: float) -> Paragraph:
+ """为表格单元格构造支持公式和链接的 Paragraph。"""
+ if not isinstance(style, ParagraphStyle):
+ raise TypeError("PDF table paragraph style must be a ParagraphStyle")
+ return self._paragraph(
+ spans,
+ style,
+ page_idx,
+ block,
+ preserve_newlines=True,
+ max_width=max_width,
+ )
+
+ def build_image(source: str, max_width: float, alt_text: str) -> Flowable:
+ """为表格单元格构造离线图片或宽松占位。"""
+ try:
+ prepared = prepare_html_image(source, self.asset_resolver)
+ except PdfAssetError as exc:
+ logger.warning("PDF table image placeholder: {} ({})", exc, self._location(page_idx, block))
+ return self._placeholder(
+ f"image unavailable: {alt_text}",
+ block=block,
+ page_idx=page_idx,
+ width=max_width,
+ url=source if _is_remote_url(source) else None,
+ )
+ return self._prepared_image_flowable(prepared, None, max_width=max_width)
+
+ return list(
+ build_pdf_tables(
+ content,
+ available_width=self.available_width,
+ styles=self.styles,
+ build_paragraph=build_paragraph,
+ build_image=build_image,
+ )
+ )
+
+ def _image_or_placeholder(
+ self,
+ block: ImagePayloadBlock,
+ *,
+ page_idx: int,
+ alt_text: str,
+ ) -> tuple[Flowable, bool]:
+ """加载 block 图片;任何离线失败都转换为可见占位而不抛出。"""
+ prepared = self._try_prepared_block_image(block, page_idx)
+ if prepared is not None:
+ return self._prepared_image_flowable(prepared, block), True
+ remote_url = block.image_url if block.image_path is None and block.image_base64 is None else None
+ return (
+ self._placeholder(
+ f"image unavailable: {alt_text}",
+ block=block,
+ page_idx=page_idx,
+ url=remote_url,
+ ),
+ False,
+ )
+
+ def _try_prepared_block_image(self, block: ImagePayloadBlock, page_idx: int) -> PreparedImage | None:
+ """尝试离线准备图片并把所有素材错误降级为 warning。"""
+ try:
+ return prepare_block_image(block, self.asset_resolver)
+ except PdfAssetError as exc:
+ logger.warning("PDF image placeholder: {} ({})", exc, self._location(page_idx, block))
+ return None
+
+ def _prepared_image_flowable(
+ self,
+ prepared: PreparedImage,
+ block: ImagePayloadBlock | None,
+ *,
+ max_width: float | None = None,
+ ) -> ReportLabImage:
+ """按自然尺寸或 bbox 宽度限制图片,并保持宽高比和左对齐。"""
+ available_width = self.available_width if max_width is None else max(1.0, max_width)
+ natural_width = prepared.width_px / 96 * 72
+ desired_width = natural_width
+ if block is not None and block.bbox is not None:
+ desired_width = available_width * (block.bbox[2] - block.bbox[0])
+ desired_width = max(min(_MIN_IMAGE_WIDTH, available_width), min(desired_width, available_width))
+ desired_height = desired_width * prepared.height_px / max(prepared.width_px, 1)
+ max_height = self.available_height
+ if desired_height > max_height:
+ scale = max_height / desired_height
+ desired_width *= scale
+ desired_height *= scale
+ image = ReportLabImage(BytesIO(prepared.data), width=desired_width, height=desired_height)
+ image.hAlign = "LEFT"
+ image.spaceBefore = 5
+ image.spaceAfter = 5
+ return image
+
+ def _placeholder(
+ self,
+ label: str,
+ *,
+ block: BlockBase,
+ page_idx: int,
+ width: float | None = None,
+ url: str | None = None,
+ ) -> Table:
+ """创建带浅色边框、可选远程链接和定位文本的稳定占位框。"""
+ normalized = re.sub(r"\s+", " ", label).strip()[:_MAX_PLACEHOLDER_TEXT] or "content unavailable"
+ markup = render_plain_text_markup(normalized)
+ if url:
+ markup += f'<br/><a href="{html.escape(url, quote=True)}" color="#0b6fc2">{html.escape(url)}</a>'
+ location = self._location(page_idx, block)
+ markup += f'<br/><font size="7" color="#6b7280">{html.escape(location)}</font>'
+ paragraph = Paragraph(markup, self.styles.placeholder)
+ target_width = self.available_width if width is None else max(1.0, min(width, self.available_width))
+ table = Table([[paragraph]], colWidths=[target_width], rowHeights=[_PLACEHOLDER_HEIGHT], hAlign="LEFT")
+ table.setStyle(
+ TableStyle(
+ [
+ ("BACKGROUND", (0, 0), (-1, -1), SURFACE_COLOR),
+ ("BOX", (0, 0), (-1, -1), 0.6, BORDER_COLOR),
+ ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
+ ("LEFTPADDING", (0, 0), (-1, -1), 8),
+ ("RIGHTPADDING", (0, 0), (-1, -1), 8),
+ ("TOPPADDING", (0, 0), (-1, -1), 6),
+ ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
+ ]
+ )
+ )
+ table.spaceBefore = 5
+ table.spaceAfter = 5
+ return table
+
+ @staticmethod
+ def _location(page_idx: int, block: BlockBase) -> str:
+ """返回 PDF 告警与占位使用的稳定 page/block 定位。"""
+ return f"page_idx={page_idx}, block_index={block.index}, block_type={block.type}"
+
+
+def render_pdf(
+ middle_json: MiddleJson,
+ *,
+ mode: RenderMode = RenderMode.FULL,
+ asset_resolver: AssetResolver | None = None,
+ document_title: str | None = None,
+) -> bytes:
+ """把严格 MiddleJson 无副作用地渲染为完整 PDF bytes。"""
+ if not isinstance(middle_json, MiddleJson):
+ raise TypeError("render_pdf expects a MiddleJson instance")
+ if not isinstance(mode, RenderMode):
+ raise TypeError("mode must be a RenderMode value")
+ if asset_resolver is not None and not callable(asset_resolver):
+ raise TypeError("asset_resolver must be callable or None")
+ if document_title is not None and not isinstance(document_title, str):
+ raise TypeError("document_title must be a string or None")
+ return _PdfRenderer(
+ middle_json,
+ mode=mode,
+ asset_resolver=asset_resolver,
+ document_title=document_title,
+ ).render()
+
+
+def _resolve_document_title(middle_json: MiddleJson, explicit: str | None) -> str:
+ """按显式标题、首个文档标题和固定回退的顺序生成 metadata title。"""
+ if explicit is not None:
+ normalized = re.sub(r"\s+", " ", _INVALID_METADATA_TEXT_RE.sub("\ufffd", explicit)).strip()
+ return normalized or "MinerU Document"
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if isinstance(block, DocTitleBlock):
+ normalized = re.sub(
+ r"\s+",
+ " ",
+ _INVALID_METADATA_TEXT_RE.sub("\ufffd", inline_plain_text(block.content)),
+ ).strip()
+ if normalized:
+ return normalized
+ return "MinerU Document"
+
+
+def _iter_document_anchors(middle_json: MiddleJson) -> Iterable[str]:
+ """按文档顺序枚举标题和页面脚注的非空 anchor。"""
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if isinstance(block, TitleBlockBase) and block.anchor:
+ yield block.anchor
+ elif isinstance(block, PageFootnoteBlock) and block.anchor:
+ yield block.anchor
+
+
+def _plain_html_text(content: str) -> str:
+ """把视觉 body 的 HTML 或普通字符串压缩为可见文本。"""
+ if not content:
+ return ""
+ soup = BeautifulSoup(content, "html.parser")
+ if soup.find(_VISIBLE_HTML_TAGS) is None:
+ return re.sub(r"[ \t]+", " ", content).strip()
+ return re.sub(r"[ \t]+", " ", soup.get_text("\n")).strip()
+
+
+def _flatten_non_link_spans(spans: list[InlineSpan]) -> list[NonLinkInlineSpan]:
+ """递归移除已有 hyperlink 包装,供目录目标建立单层内部链接。"""
+ flattened: list[NonLinkInlineSpan] = []
+ for span in spans:
+ if isinstance(span, HyperlinkSpan):
+ flattened.extend(span.content)
+ else:
+ flattened.append(span)
+ return flattened
+
+
+def _has_image_payload(block: ImagePayloadBlock) -> bool:
+ """判断统一图片载荷是否声明 sidecar、data URI 或远程 URL。"""
+ return block.image_path is not None or block.image_base64 is not None or block.image_url is not None
+
+
+def _is_remote_url(source: str) -> bool:
+ """判断图片 source 是否是不会被 PDF renderer 下载的 HTTP(S) URL。"""
+ normalized = source.strip().casefold()
+ return normalized.startswith("http://") or normalized.startswith("https://")
+
+
+__all__ = ["render_pdf"]
diff --git a/mineru/render/_internal/pdf/styles.py b/mineru/render/_internal/pdf/styles.py
new file mode 100644
index 00000000..8db20b44
--- /dev/null
+++ b/mineru/render/_internal/pdf/styles.py
@@ -0,0 +1,202 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""PDF renderer 的页面几何、字体与 MinerU 打印样式。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from threading import RLock
+
+from reportlab.lib import colors
+from reportlab.lib.enums import TA_CENTER, TA_LEFT
+from reportlab.lib.styles import ParagraphStyle
+from reportlab.lib.units import mm
+from reportlab.pdfbase import cidfonts, pdfmetrics
+
+PAGE_MARGIN = 20 * mm
+BODY_FONT = "Helvetica"
+BODY_BOLD_FONT = "Helvetica-Bold"
+MONO_FONT = "Courier"
+HAN_FONT = "STSong-Light"
+JAPANESE_FONT = "HeiseiMin-W3"
+KOREAN_FONT = "HYSMyeongJo-Medium"
+
+ACCENT_COLOR = colors.HexColor("#0b6fc2")
+BACKGROUND_COLOR = colors.HexColor("#ffffff")
+BORDER_COLOR = colors.HexColor("#d1d5db")
+MUTED_COLOR = colors.HexColor("#6b7280")
+SURFACE_COLOR = colors.HexColor("#f8fafc")
+TEXT_COLOR = colors.HexColor("#1f2937")
+
+_FONT_LOCK = RLock()
+_HEADING_SIZES = (20.0, 16.0, 14.0, 12.0, 11.0, 10.0)
+
+
+@dataclass(frozen=True, slots=True)
+class PdfStyleSet:
+ """保存 PDF renderer 使用的全部稳定段落样式。"""
+
+ body: ParagraphStyle
+ headings: tuple[ParagraphStyle, ...]
+ caption: ParagraphStyle
+ footnote: ParagraphStyle
+ auxiliary: ParagraphStyle
+ code: ParagraphStyle
+ spatial_table: ParagraphStyle
+ formula_fallback: ParagraphStyle
+ placeholder: ParagraphStyle
+ table_cell: ParagraphStyle
+ table_header: ParagraphStyle
+
+ def heading(self, level: int) -> ParagraphStyle:
+ """按公开一到六级标题返回对应的 PDF 样式。"""
+ return self.headings[min(max(level, 1), len(self.headings)) - 1]
+
+
+def build_pdf_styles() -> PdfStyleSet:
+ """注册标准 CID 字体并构造无外部字体依赖的打印样式集。"""
+ _register_cid_fonts()
+ body = ParagraphStyle(
+ "MinerU PDF Body",
+ fontName=BODY_FONT,
+ fontSize=10.5,
+ leading=16,
+ textColor=TEXT_COLOR,
+ alignment=TA_LEFT,
+ spaceBefore=0,
+ spaceAfter=7,
+ splitLongWords=True,
+ allowWidows=1,
+ allowOrphans=1,
+ )
+ headings = tuple(
+ ParagraphStyle(
+ f"MinerU PDF Heading {level}",
+ parent=body,
+ fontName=BODY_BOLD_FONT,
+ fontSize=size,
+ leading=size * 1.3,
+ spaceBefore=10 if level <= 3 else 8,
+ spaceAfter=6 if level <= 3 else 4,
+ keepWithNext=True,
+ )
+ for level, size in enumerate(_HEADING_SIZES, start=1)
+ )
+ caption = ParagraphStyle(
+ "MinerU PDF Caption",
+ parent=body,
+ fontSize=9,
+ leading=12,
+ textColor=MUTED_COLOR,
+ spaceBefore=3,
+ spaceAfter=5,
+ )
+ footnote = ParagraphStyle(
+ "MinerU PDF Footnote",
+ parent=body,
+ fontSize=8.5,
+ leading=11,
+ textColor=MUTED_COLOR,
+ spaceBefore=2,
+ spaceAfter=4,
+ )
+ auxiliary = ParagraphStyle(
+ "MinerU PDF Auxiliary",
+ parent=footnote,
+ fontName="Helvetica-Oblique",
+ spaceBefore=1,
+ spaceAfter=3,
+ )
+ code = ParagraphStyle(
+ "MinerU PDF Code",
+ parent=body,
+ fontName=MONO_FONT,
+ fontSize=8.5,
+ leading=11,
+ backColor=SURFACE_COLOR,
+ borderColor=BORDER_COLOR,
+ borderWidth=0.5,
+ borderPadding=7,
+ borderRadius=3,
+ spaceBefore=5,
+ spaceAfter=7,
+ )
+ spatial_table = ParagraphStyle(
+ "MinerU PDF Spatial Table",
+ parent=code,
+ backColor=BACKGROUND_COLOR,
+ borderPadding=5,
+ )
+ formula_fallback = ParagraphStyle(
+ "MinerU PDF Formula Fallback",
+ parent=body,
+ fontName=MONO_FONT,
+ fontSize=9,
+ leading=13,
+ textColor=MUTED_COLOR,
+ alignment=TA_CENTER,
+ spaceBefore=5,
+ spaceAfter=6,
+ )
+ placeholder = ParagraphStyle(
+ "MinerU PDF Placeholder",
+ parent=body,
+ fontSize=9,
+ leading=12,
+ textColor=MUTED_COLOR,
+ spaceBefore=0,
+ spaceAfter=0,
+ )
+ table_cell = ParagraphStyle(
+ "MinerU PDF Table Cell",
+ parent=body,
+ fontSize=8.5,
+ leading=11,
+ spaceBefore=0,
+ spaceAfter=0,
+ )
+ table_header = ParagraphStyle(
+ "MinerU PDF Table Header",
+ parent=table_cell,
+ fontName=BODY_BOLD_FONT,
+ )
+ return PdfStyleSet(
+ body=body,
+ headings=headings,
+ caption=caption,
+ footnote=footnote,
+ auxiliary=auxiliary,
+ code=code,
+ spatial_table=spatial_table,
+ formula_fallback=formula_fallback,
+ placeholder=placeholder,
+ table_cell=table_cell,
+ table_header=table_header,
+ )
+
+
+def _register_cid_fonts() -> None:
+ """在进程级 ReportLab registry 中幂等注册中日韩标准 CID 字体。"""
+ with _FONT_LOCK:
+ registered = set(pdfmetrics.getRegisteredFontNames())
+ for font_name in (HAN_FONT, JAPANESE_FONT, KOREAN_FONT):
+ if font_name not in registered:
+ pdfmetrics.registerFont(cidfonts.UnicodeCIDFont(font_name))
+
+
+__all__ = [
+ "ACCENT_COLOR",
+ "BACKGROUND_COLOR",
+ "BODY_BOLD_FONT",
+ "BODY_FONT",
+ "BORDER_COLOR",
+ "HAN_FONT",
+ "JAPANESE_FONT",
+ "KOREAN_FONT",
+ "MONO_FONT",
+ "MUTED_COLOR",
+ "PAGE_MARGIN",
+ "PdfStyleSet",
+ "SURFACE_COLOR",
+ "TEXT_COLOR",
+ "build_pdf_styles",
+]
diff --git a/mineru/render/_internal/pdf/table.py b/mineru/render/_internal/pdf/table.py
new file mode 100644
index 00000000..0aca5185
--- /dev/null
+++ b/mineru/render/_internal/pdf/table.py
@@ -0,0 +1,408 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""HTML table 到可分页 ReportLab 原生表格的安全物化。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+from typing import Protocol, TypeAlias
+
+from bs4 import BeautifulSoup, NavigableString, Tag
+from pydantic import ValidationError
+from reportlab.platypus import Flowable, LongTable, Paragraph, Table, TableStyle
+
+from ....types import CodeInlineSpan, EquationInlineSpan, HyperlinkSpan, InlineSpan, InlineStyle, TextSpan, parse_inline_spans
+from ....utils.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
+from .styles import BORDER_COLOR, SURFACE_COLOR, PdfStyleSet
+
+MAX_NESTED_TABLE_DEPTH = 4
+MAX_TABLE_ROWS = 500
+MAX_TABLE_COLUMNS = 100
+MAX_TABLE_SLOTS = 10_000
+_POSITIVE_INTEGER_RE = re.compile(r"[0-9]+")
+_BLOCK_TAGS = {"address", "article", "blockquote", "div", "figcaption", "footer", "header", "li", "p", "section"}
+_SKIPPED_TAGS = {"script", "style", "template", "noscript"}
+
+HtmlTableSource: TypeAlias = str | BeautifulSoup | Tag
+
+
+class PdfTableError(ValueError):
+ """表示 HTML 表格结构或 PDF 表格几何无法安全物化。"""
+
+
+@dataclass(frozen=True, slots=True)
+class HtmlTableCell:
+ """保存原始 HTML 单元格在逻辑占位网格中的位置。"""
+
+ tag: Tag
+ row: int
+ column: int
+ rowspan: int
+ colspan: int
+ is_header: bool
+
+ @property
+ def end_row(self) -> int:
+ """返回单元格占用的末行下标。"""
+ return self.row + self.rowspan - 1
+
+ @property
+ def end_column(self) -> int:
+ """返回单元格占用的末列下标。"""
+ return self.column + self.colspan - 1
+
+
+@dataclass(frozen=True, slots=True)
+class HtmlTableGrid:
+ """保存经过重叠、边界、规模与矩形校验的 HTML 表格网格。"""
+
+ tag: Tag
+ row_count: int
+ column_count: int
+ cells: tuple[HtmlTableCell, ...]
+ header_rows: tuple[int, ...]
+
+
+class ParagraphBuilder(Protocol):
+ """定义表格单元格创建富文本 Paragraph 的回调。"""
+
+ def __call__(self, spans: list[InlineSpan], style: object, max_width: float) -> Paragraph:
+ """把单元格行内 span 构造成指定宽度的 Paragraph。"""
+ ...
+
+
+class HtmlImageBuilder(Protocol):
+ """定义表格单元格创建离线图片或占位 Flowable 的回调。"""
+
+ def __call__(self, source: str, max_width: float, alt_text: str) -> Flowable:
+ """把 HTML img source 转换为图片或宽松占位。"""
+ ...
+
+
+def parse_html_tables(source: HtmlTableSource) -> tuple[HtmlTableGrid, ...]:
+ """解析 source 中相对当前上下文的一个或多个顶层 table。"""
+ root = BeautifulSoup(source, "html.parser") if isinstance(source, str) else source
+ if not isinstance(root, (BeautifulSoup, Tag)):
+ raise PdfTableError("HTML table source must be a string or BeautifulSoup Tag")
+ if isinstance(root, Tag) and root.name == "table":
+ table_tags = (root,)
+ else:
+ parent_table = root.find_parent("table") if isinstance(root, Tag) else None
+ table_tags = tuple(table for table in root.find_all("table") if table.find_parent("table") is parent_table)
+ if not table_tags:
+ raise PdfTableError("HTML does not contain a top-level table")
+ return tuple(_parse_html_table(table) for table in table_tags)
+
+
+def build_pdf_tables(
+ source: HtmlTableSource,
+ *,
+ available_width: float,
+ styles: PdfStyleSet,
+ build_paragraph: ParagraphBuilder,
+ build_image: HtmlImageBuilder,
+ depth: int = 1,
+) -> tuple[Table, ...]:
+ """把 HTML 表格递归转换为支持合并单元格与重复表头的 PDF 表格。"""
+ if depth > MAX_NESTED_TABLE_DEPTH:
+ raise PdfTableError(f"Nested table depth exceeds {MAX_NESTED_TABLE_DEPTH}")
+ if available_width <= 0:
+ raise PdfTableError("available_width must be positive")
+ grids = parse_html_tables(source)
+ return tuple(
+ _build_pdf_table(
+ grid,
+ available_width=available_width,
+ styles=styles,
+ build_paragraph=build_paragraph,
+ build_image=build_image,
+ depth=depth,
+ )
+ for grid in grids
+ )
+
+
+def _parse_html_table(table: Tag) -> HtmlTableGrid:
+ """把单个 table 标签解析为严格矩形占位网格。"""
+ if table.name != "table":
+ raise PdfTableError("Expected a <table> tag")
+ rows = tuple(row for row in table.find_all("tr") if row.find_parent("table") is table)
+ if not rows or len(rows) > MAX_TABLE_ROWS:
+ raise PdfTableError(f"Table row count must be between 1 and {MAX_TABLE_ROWS}")
+ occupied: dict[tuple[int, int], HtmlTableCell] = {}
+ cells: list[HtmlTableCell] = []
+ for row_index, row in enumerate(rows):
+ column_index = 0
+ for source_cell in row.find_all(("td", "th"), recursive=False):
+ while (row_index, column_index) in occupied:
+ column_index += 1
+ rowspan = _parse_span(source_cell, "rowspan")
+ colspan = _parse_span(source_cell, "colspan")
+ if row_index + rowspan > len(rows):
+ raise PdfTableError(f"rowspan exceeds table bounds at row={row_index}, column={column_index}")
+ if column_index + colspan > MAX_TABLE_COLUMNS:
+ raise PdfTableError(f"Table column count exceeds {MAX_TABLE_COLUMNS}")
+ coordinates = tuple(
+ (target_row, target_column)
+ for target_row in range(row_index, row_index + rowspan)
+ for target_column in range(column_index, column_index + colspan)
+ )
+ overlap = next((coordinate for coordinate in coordinates if coordinate in occupied), None)
+ if overlap is not None:
+ raise PdfTableError(f"Cell span overlaps row={overlap[0]}, column={overlap[1]}")
+ placement = HtmlTableCell(
+ tag=source_cell,
+ row=row_index,
+ column=column_index,
+ rowspan=rowspan,
+ colspan=colspan,
+ is_header=source_cell.name == "th",
+ )
+ cells.append(placement)
+ occupied.update(dict.fromkeys(coordinates, placement))
+ if len(occupied) > MAX_TABLE_SLOTS:
+ raise PdfTableError(f"Table occupancy exceeds {MAX_TABLE_SLOTS} slots")
+ column_index += colspan
+ if not occupied:
+ raise PdfTableError("Table must contain at least one cell")
+ column_count = max(column for _, column in occupied) + 1
+ missing = next(
+ (
+ (row_index, column_index)
+ for row_index in range(len(rows))
+ for column_index in range(column_count)
+ if (row_index, column_index) not in occupied
+ ),
+ None,
+ )
+ if missing is not None:
+ raise PdfTableError(f"Table occupancy is not rectangular at row={missing[0]}, column={missing[1]}")
+ header_rows = tuple(
+ row_index
+ for row_index, row in enumerate(rows)
+ if _row_belongs_to_thead(row, table)
+ or all(occupied[(row_index, column_index)].is_header for column_index in range(column_count))
+ )
+ return HtmlTableGrid(
+ tag=table,
+ row_count=len(rows),
+ column_count=column_count,
+ cells=tuple(cells),
+ header_rows=header_rows,
+ )
+
+
+def _build_pdf_table(
+ grid: HtmlTableGrid,
+ *,
+ available_width: float,
+ styles: PdfStyleSet,
+ build_paragraph: ParagraphBuilder,
+ build_image: HtmlImageBuilder,
+ depth: int,
+) -> Table:
+ """物化一个网格,写入单元格内容、合并区域与固定打印样式。"""
+ column_widths = _column_widths(available_width, grid.column_count)
+ data: list[list[object]] = [["" for _ in range(grid.column_count)] for _ in range(grid.row_count)]
+ commands: list[tuple[object, ...]] = [
+ ("GRID", (0, 0), (-1, -1), 0.5, BORDER_COLOR),
+ ("VALIGN", (0, 0), (-1, -1), "TOP"),
+ ("LEFTPADDING", (0, 0), (-1, -1), 5),
+ ("RIGHTPADDING", (0, 0), (-1, -1), 5),
+ ("TOPPADDING", (0, 0), (-1, -1), 4),
+ ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
+ ]
+ for row_index in grid.header_rows:
+ commands.append(("BACKGROUND", (0, row_index), (-1, row_index), SURFACE_COLOR))
+ for placement in grid.cells:
+ cell_width = sum(column_widths[placement.column : placement.column + placement.colspan]) - 10
+ style = styles.table_header if placement.is_header else styles.table_cell
+ data[placement.row][placement.column] = _cell_flowables(
+ placement.tag,
+ max_width=max(1.0, cell_width),
+ style=style,
+ styles=styles,
+ build_paragraph=build_paragraph,
+ build_image=build_image,
+ depth=depth,
+ )
+ if placement.rowspan > 1 or placement.colspan > 1:
+ commands.append(
+ (
+ "SPAN",
+ (placement.column, placement.row),
+ (placement.end_column, placement.end_row),
+ )
+ )
+ repeat_rows = 0
+ while repeat_rows in grid.header_rows:
+ repeat_rows += 1
+ table_class = LongTable if depth == 1 else Table
+ table = table_class(
+ data,
+ colWidths=column_widths,
+ repeatRows=repeat_rows,
+ splitByRow=1,
+ splitInRow=1,
+ hAlign="LEFT",
+ )
+ table.setStyle(TableStyle(commands))
+ return table
+
+
+def _cell_flowables(
+ cell: Tag,
+ *,
+ max_width: float,
+ style: object,
+ styles: PdfStyleSet,
+ build_paragraph: ParagraphBuilder,
+ build_image: HtmlImageBuilder,
+ depth: int,
+) -> list[Flowable]:
+ """把单元格文本、图片与直接嵌套表按安全顺序转换为 Flowable。"""
+ flowables: list[Flowable] = []
+ spans = _html_cell_spans(cell)
+ if spans:
+ flowables.append(build_paragraph(spans, style, max_width))
+ for image in cell.find_all("img"):
+ if image.find_parent("table") is not cell.find_parent("table"):
+ continue
+ source = image.get("src", "")
+ if isinstance(source, list):
+ source = ""
+ alt = image.get("alt", "image")
+ if isinstance(alt, list):
+ alt = " ".join(str(item) for item in alt)
+ flowables.append(build_image(str(source), max_width, str(alt)))
+ for nested in cell.find_all("table"):
+ if nested.find_parent(("td", "th")) is not cell:
+ continue
+ flowables.extend(
+ build_pdf_tables(
+ nested,
+ available_width=max_width,
+ styles=styles,
+ build_paragraph=build_paragraph,
+ build_image=build_image,
+ depth=depth + 1,
+ )
+ )
+ if not flowables:
+ flowables.append(build_paragraph([TextSpan(type="text", content=" ")], style, max_width))
+ return flowables
+
+
+def _html_cell_spans(cell: Tag) -> list[InlineSpan]:
+ """把单元格中非图片、非嵌套表内容转换为严格 InlineSpan。"""
+ spans: list[InlineSpan] = []
+ for child in cell.children:
+ spans.extend(_html_node_spans(child, styles=(), allow_links=True))
+ if not spans:
+ return []
+ try:
+ return parse_inline_spans(spans)
+ except (TypeError, ValidationError, ValueError) as exc:
+ raise PdfTableError("HTML table cell inline content is invalid") from exc
+
+
+def _html_node_spans(node: object, *, styles: tuple[InlineStyle, ...], allow_links: bool) -> list[InlineSpan]:
+ """递归解析安全 HTML 富文本标签,忽略活动内容与独立视觉节点。"""
+ if isinstance(node, NavigableString):
+ text = str(node)
+ return [TextSpan(type="text", content=text, styles=list(styles))] if text else []
+ if not isinstance(node, Tag):
+ return []
+ name = (node.name or "").lower()
+ if name in _SKIPPED_TAGS or name in {"img", "table"}:
+ return []
+ if name == "br":
+ return [TextSpan(type="text", content="\n", styles=list(styles))]
+ if name == "eq":
+ content = node.get_text()
+ return [EquationInlineSpan(type="equation_inline", content=content)] if content.strip() else []
+ if name == "code":
+ content = node.get_text()
+ return [CodeInlineSpan(type="code_inline", content=content)] if content else []
+ style_name: InlineStyle | None = {
+ "b": "bold",
+ "strong": "bold",
+ "i": "italic",
+ "em": "italic",
+ "u": "underline",
+ "s": "strikethrough",
+ "del": "strikethrough",
+ "sup": "superscript",
+ "sub": "subscript",
+ }.get(name)
+ child_styles = tuple(dict.fromkeys((*styles, style_name))) if style_name is not None else styles
+ if name == "a" and allow_links:
+ children = [
+ span
+ for child in node.children
+ for span in _html_node_spans(child, styles=child_styles, allow_links=False)
+ if not isinstance(span, HyperlinkSpan)
+ ]
+ target = sanitize_hyperlink_target(
+ node.get("href"),
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ if target is not None and children:
+ try:
+ return [HyperlinkSpan(type="hyperlink", url=target, content=children)] # type: ignore[arg-type]
+ except ValidationError:
+ pass
+ return children
+ spans = [span for child in node.children for span in _html_node_spans(child, styles=child_styles, allow_links=allow_links)]
+ if name in _BLOCK_TAGS and spans and not _spans_end_with_newline(spans):
+ spans.append(TextSpan(type="text", content="\n"))
+ return spans
+
+
+def _spans_end_with_newline(spans: list[InlineSpan]) -> bool:
+ """判断当前 span 序列是否已经以普通文本换行结束。"""
+ return bool(spans and isinstance(spans[-1], TextSpan) and spans[-1].content.endswith("\n"))
+
+
+def _parse_span(cell: Tag, attribute: str) -> int:
+ """读取严格正整数 rowspan/colspan,缺失时返回一。"""
+ raw_value = cell.get(attribute, "1")
+ if isinstance(raw_value, list):
+ raise PdfTableError(f"Invalid {attribute}: {raw_value!r}")
+ value = str(raw_value).strip()
+ if _POSITIVE_INTEGER_RE.fullmatch(value) is None:
+ raise PdfTableError(f"Invalid {attribute}: {raw_value!r}")
+ span = int(value)
+ if span < 1 or span > MAX_TABLE_SLOTS:
+ raise PdfTableError(f"Invalid {attribute}: {raw_value!r}")
+ return span
+
+
+def _row_belongs_to_thead(row: Tag, table: Tag) -> bool:
+ """判断 tr 是否位于当前 table 的 thead 内。"""
+ parent = row.parent
+ while isinstance(parent, Tag) and parent is not table:
+ if parent.name == "thead":
+ return True
+ parent = parent.parent
+ return False
+
+
+def _column_widths(total_width: float, column_count: int) -> list[float]:
+ """把可用宽度确定性地均分到全部逻辑列。"""
+ if column_count <= 0:
+ raise PdfTableError("Table must contain at least one column")
+ base = total_width / column_count
+ return [base for _ in range(column_count)]
+
+
+__all__ = [
+ "HtmlTableCell",
+ "HtmlTableGrid",
+ "MAX_NESTED_TABLE_DEPTH",
+ "PdfTableError",
+ "build_pdf_tables",
+ "parse_html_tables",
+]
diff --git a/mineru/render/api.py b/mineru/render/api.py
index 550e5f96..78d66bbe 100644
--- a/mineru/render/api.py
+++ b/mineru/render/api.py
@@ -11,8 +11,10 @@ from .contracts import (
ContentListRenderOptions,
ContentListV2RenderOptions,
DocxRenderOptions,
+ EpubRenderOptions,
HtmlRenderOptions,
MarkdownRenderOptions,
+ PdfRenderOptions,
RenderFormat,
RenderOptions,
RenderOutput,
@@ -21,8 +23,10 @@ from .contracts import (
from .content_list import render_content_list
from .content_list_v2 import render_content_list_v2
from .docx import render_docx
+from .epub import render_epub
from .html import render_html
from .markdown import render_markdown
+from .pdf import render_pdf
from .structured_content import render_structured_content
@@ -59,6 +63,28 @@ def render(
...
+@overload
+def render(
+ middle_json: MiddleJson,
+ output_format: Literal[RenderFormat.EPUB],
+ *,
+ options: EpubRenderOptions | None = None,
+) -> bytes:
+ """声明 EPUB 目标对应的字节返回类型。"""
+ ...
+
+
+@overload
+def render(
+ middle_json: MiddleJson,
+ output_format: Literal[RenderFormat.PDF],
+ *,
+ options: PdfRenderOptions | None = None,
+) -> bytes:
+ """声明 PDF 目标对应的字节返回类型。"""
+ ...
+
+
@overload
def render(
middle_json: MiddleJson,
@@ -137,6 +163,32 @@ def render(
asset_resolver=resolved_options.asset_resolver,
)
+ if output_format is RenderFormat.EPUB:
+ resolved_options = options if options is not None else EpubRenderOptions()
+ if not isinstance(resolved_options, EpubRenderOptions):
+ raise TypeError("EPUB output requires EpubRenderOptions")
+ return render_epub(
+ middle_json,
+ mode=resolved_options.mode,
+ title=resolved_options.title,
+ authors=resolved_options.authors,
+ language=resolved_options.language,
+ identifier=resolved_options.identifier,
+ modified_at=resolved_options.modified_at,
+ asset_resolver=resolved_options.asset_resolver,
+ )
+
+ if output_format is RenderFormat.PDF:
+ resolved_options = options if options is not None else PdfRenderOptions()
+ if not isinstance(resolved_options, PdfRenderOptions):
+ raise TypeError("PDF output requires PdfRenderOptions")
+ return render_pdf(
+ middle_json,
+ mode=resolved_options.mode,
+ asset_resolver=resolved_options.asset_resolver,
+ document_title=resolved_options.document_title,
+ )
+
if output_format is RenderFormat.STRUCTURED_CONTENT:
resolved_options = options if options is not None else StructuredContentRenderOptions()
if not isinstance(resolved_options, StructuredContentRenderOptions):
diff --git a/mineru/render/contracts.py b/mineru/render/contracts.py
index 6c7106b3..28748265 100644
--- a/mineru/render/contracts.py
+++ b/mineru/render/contracts.py
@@ -4,7 +4,9 @@
from __future__ import annotations
from dataclasses import dataclass
+from datetime import datetime
from enum import Enum
+import re
from typing import Any, Callable, TypeAlias
from ..types import BlockBase
@@ -16,9 +18,11 @@ class RenderFormat(str, Enum):
MARKDOWN = "markdown"
HTML = "html"
DOCX = "docx"
+ EPUB = "epub"
STRUCTURED_CONTENT = "structured_content"
CONTENT_LIST = "content_list"
CONTENT_LIST_V2 = "content_list_v2"
+ PDF = "pdf"
class RenderMode(str, Enum):
@@ -93,6 +97,62 @@ class DocxRenderOptions:
raise TypeError("asset_resolver must be callable or None")
+_EPUB_LANGUAGE_RE = re.compile(r"(?:[A-Za-z]{2,8}|und)(?:-[A-Za-z0-9]{1,8})*\Z", re.IGNORECASE)
+
+
+@dataclass(frozen=True, slots=True)
+class EpubRenderOptions:
+ """EPUB 3.3 renderer 的统一入口选项。"""
+
+ mode: RenderMode = RenderMode.DEFAULT
+ title: str | None = None
+ authors: tuple[str, ...] = ()
+ language: str = "und"
+ identifier: str | None = None
+ modified_at: datetime | None = None
+ asset_resolver: AssetResolver | None = None
+
+ def __post_init__(self) -> None:
+ """在构造时校验 EPUB 元数据、时间与素材解析器。"""
+ _validate_mode(self.mode)
+ if self.title is not None and (not isinstance(self.title, str) or not self.title.strip()):
+ raise TypeError("title must be a non-empty string or None")
+ if not isinstance(self.authors, tuple) or any(
+ not isinstance(author, str) or not author.strip() for author in self.authors
+ ):
+ raise TypeError("authors must be a tuple of non-empty strings")
+ if not isinstance(self.language, str) or _EPUB_LANGUAGE_RE.fullmatch(self.language.strip()) is None:
+ raise ValueError("language must be a supported BCP 47 language tag")
+ if self.identifier is not None and (not isinstance(self.identifier, str) or not self.identifier.strip()):
+ raise TypeError("identifier must be a non-empty string or None")
+ if self.modified_at is not None:
+ if not isinstance(self.modified_at, datetime):
+ raise TypeError("modified_at must be a datetime or None")
+ if self.modified_at.utcoffset() is None:
+ raise ValueError("modified_at must be timezone-aware")
+ if self.modified_at.year < 1000:
+ raise ValueError("modified_at year must use four digits")
+ if self.asset_resolver is not None and not callable(self.asset_resolver):
+ raise TypeError("asset_resolver must be callable or None")
+
+
+@dataclass(frozen=True, slots=True)
+class PdfRenderOptions:
+ """PDF renderer 的统一入口选项。"""
+
+ mode: RenderMode = RenderMode.FULL
+ asset_resolver: AssetResolver | None = None
+ document_title: str | None = None
+
+ def __post_init__(self) -> None:
+ """在构造时校验分页模式、素材解析器与文档标题。"""
+ _validate_mode(self.mode)
+ if self.asset_resolver is not None and not callable(self.asset_resolver):
+ raise TypeError("asset_resolver must be callable or None")
+ if self.document_title is not None and not isinstance(self.document_title, str):
+ raise TypeError("document_title must be a string or None")
+
+
@dataclass(frozen=True, slots=True)
class StructuredContentRenderOptions:
"""树形 Markdown Structured Content renderer 的统一入口选项。"""
@@ -130,6 +190,8 @@ RenderOptions: TypeAlias = (
MarkdownRenderOptions
| HtmlRenderOptions
| DocxRenderOptions
+ | EpubRenderOptions
+ | PdfRenderOptions
| StructuredContentRenderOptions
| ContentListRenderOptions
| ContentListV2RenderOptions
@@ -142,9 +204,11 @@ __all__ = [
"ContentListRenderOptions",
"ContentListV2RenderOptions",
"DocxRenderOptions",
+ "EpubRenderOptions",
"HtmlRenderOptions",
"ImageRenderer",
"MarkdownRenderOptions",
+ "PdfRenderOptions",
"RenderFormat",
"RenderMode",
"RenderOptions",
diff --git a/mineru/render/epub.py b/mineru/render/epub.py
new file mode 100644
index 00000000..af37ffc0
--- /dev/null
+++ b/mineru/render/epub.py
@@ -0,0 +1,38 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到 EPUB 3.3 的轻量公共门面。"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from ..types import MiddleJson
+from .contracts import AssetResolver, RenderMode
+
+
+def render_epub(
+ middle_json: MiddleJson,
+ *,
+ mode: RenderMode = RenderMode.DEFAULT,
+ title: str | None = None,
+ authors: tuple[str, ...] = (),
+ language: str = "und",
+ identifier: str | None = None,
+ modified_at: datetime | None = None,
+ asset_resolver: AssetResolver | None = None,
+) -> bytes:
+ """惰性加载 EPUB 实现并返回完整 EPUB 3.3 容器字节。"""
+ from ._internal.epub.renderer import render_epub as _render_epub
+
+ return _render_epub(
+ middle_json,
+ mode=mode,
+ title=title,
+ authors=authors,
+ language=language,
+ identifier=identifier,
+ modified_at=modified_at,
+ asset_resolver=asset_resolver,
+ )
+
+
+__all__ = ["render_epub"]
diff --git a/mineru/render/pdf.py b/mineru/render/pdf.py
new file mode 100644
index 00000000..2d010d7e
--- /dev/null
+++ b/mineru/render/pdf.py
@@ -0,0 +1,28 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到 PDF bytes 的轻量公共门面。"""
+
+from __future__ import annotations
+
+from ..types import MiddleJson
+from .contracts import AssetResolver, RenderMode
+
+
+def render_pdf(
+ middle_json: MiddleJson,
+ *,
+ mode: RenderMode = RenderMode.FULL,
+ asset_resolver: AssetResolver | None = None,
+ document_title: str | None = None,
+) -> bytes:
+ """惰性加载 PDF 实现并渲染严格 MiddleJson。"""
+ from ._internal.pdf.renderer import render_pdf as _render_pdf
+
+ return _render_pdf(
+ middle_json,
+ mode=mode,
+ asset_resolver=asset_resolver,
+ document_title=document_title,
+ )
+
+
+__all__ = ["render_pdf"]
diff --git a/mineru/resources/epub/mineru.css b/mineru/resources/epub/mineru.css
new file mode 100644
index 00000000..6b162cc0
--- /dev/null
+++ b/mineru/resources/epub/mineru.css
@@ -0,0 +1,99 @@
+html {
+ color: #1f2328;
+ background: #fff;
+ font-family: serif;
+ line-height: 1.6;
+}
+
+body {
+ margin: 0;
+ padding: 0 5%;
+}
+
+.mineru-document {
+ max-width: 48rem;
+ margin: 0 auto;
+}
+
+.mineru-block,
+.mineru-figure,
+.mineru-visual-body,
+.mineru-page-footnote,
+.mineru-page-aux {
+ margin: 1em 0;
+}
+
+.mineru-heading {
+ line-height: 1.25;
+ break-after: avoid;
+}
+
+.mineru-page-break {
+ border: 0;
+ border-top: 1px solid #d0d7de;
+ margin: 2em 0;
+ break-after: page;
+}
+
+img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+}
+
+figure,
+figcaption,
+.mineru-caption,
+.mineru-footnote {
+ margin-left: 0;
+ text-align: left;
+}
+
+table {
+ border-collapse: collapse;
+ max-width: 100%;
+}
+
+th,
+td {
+ border: 1px solid #8c959f;
+ padding: 0.3em 0.5em;
+ vertical-align: top;
+}
+
+pre {
+ overflow-wrap: anywhere;
+ white-space: pre-wrap;
+}
+
+code,
+kbd,
+pre {
+ font-family: monospace;
+}
+
+.mineru-preserve-whitespace,
+.mineru-algorithm {
+ white-space: pre-wrap;
+}
+
+.mineru-page-footnote,
+.mineru-footnote,
+figcaption {
+ color: #57606a;
+ font-size: 0.9em;
+}
+
+.mineru-text-emphasis {
+ font-weight: 600;
+}
+
+.mineru-list-marker {
+ margin-right: 0.4em;
+}
+
+.mineru-list--explicit,
+.mineru-list--unmarked {
+ list-style: none;
+ padding-left: 1.2em;
+}
diff --git a/pyproject.toml b/pyproject.toml
index f426475f..45397d75 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -52,6 +52,7 @@ dependencies = [
"PyYAML>=6.0.1,<7",
"packaging",
"reportlab",
+ "ziamath>=0.13,<0.14",
"pdftext>=0.6.3,<0.8.0",
"modelscope>=1.26.0",
"huggingface-hub[hf_xet]>=0.32.4",
diff --git a/tests/unittest/_epub_test_utils.py b/tests/unittest/_epub_test_utils.py
index 86e14b4c..78971c32 100644
--- a/tests/unittest/_epub_test_utils.py
+++ b/tests/unittest/_epub_test_utils.py
@@ -24,6 +24,8 @@ def build_epub_fixture(
nav_in_spine: bool = False,
nav_extra_body_text: str = "",
strip_headings: bool = False,
+ unclosed_br_first_chapter: bool = False,
+ unclosed_br_second_chapter: bool = False,
) -> bytes:
"""构造覆盖 XHTML、SVG、CSS、公式、表格、列表和图片的最小 EPUB 3。"""
container = """<?xml version="1.0" encoding="UTF-8"?>
@@ -89,6 +91,8 @@ def build_epub_fixture(
'<!DOCTYPE html [<!ENTITY x "hidden">]><html xmlns="http://www.w3.org/1999/xhtml">',
1,
)
+ if unclosed_br_first_chapter:
+ chapter_one = chapter_one.replace("</body>", "<p>Malformed<br>tail</p></body>", 1)
chapter_two = """<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><body>
<section id="section-two"><h2>Section Two</h2></section>
@@ -101,6 +105,8 @@ def build_epub_fixture(
if strip_headings:
chapter_one = chapter_one.replace('<h1 id="chapter-one">Chapter One</h1>', '<p id="chapter-one">Chapter One</p>')
chapter_two = chapter_two.replace("<h2>Section Two</h2>", "<p>Section Two</p>")
+ if unclosed_br_second_chapter:
+ chapter_two = chapter_two.replace("<pre>", "<p>Recovered before<br>Recovered after</p><pre>", 1)
nav_xhtml = """<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><body>
<nav epub:type="toc" role="doc-toc"><ol>
diff --git a/tests/unittest/test_backend_architecture.py b/tests/unittest/test_backend_architecture.py
index 96f04e42..19a2de5e 100644
--- a/tests/unittest/test_backend_architecture.py
+++ b/tests/unittest/test_backend_architecture.py
@@ -44,6 +44,8 @@ _CHINESE_DOCSTRING_PATHS = (
_PROJECT_ROOT / "mineru/render/markdown.py",
_PROJECT_ROOT / "mineru/render/html.py",
_PROJECT_ROOT / "mineru/render/docx.py",
+ _PROJECT_ROOT / "mineru/render/epub.py",
+ _PROJECT_ROOT / "mineru/render/pdf.py",
_PROJECT_ROOT / "mineru/render/structured_content.py",
_PROJECT_ROOT / "mineru/utils/image.py",
)
@@ -327,7 +329,20 @@ import mineru.render
from mineru.model.flash import PdfModel
assert PdfModel.__name__ == "PdfModel"
-for prefix in ("torch", "cv2", "pypdfium2", "pdftext", "docx", "bs4", "lxml", "nh3"):
+for prefix in (
+ "torch",
+ "cv2",
+ "pypdfium2",
+ "pdftext",
+ "docx",
+ "bs4",
+ "lxml",
+ "nh3",
+ "PIL",
+ "latex2mathml",
+ "reportlab",
+ "ziamath",
+):
assert prefix not in sys.modules, prefix
assert not any(name.startswith(prefix + ".") for name in sys.modules), prefix
assert before_env == dict(os.environ)
diff --git a/tests/unittest/test_epub_render.py b/tests/unittest/test_epub_render.py
new file mode 100644
index 00000000..d165b28a
--- /dev/null
+++ b/tests/unittest/test_epub_render.py
@@ -0,0 +1,500 @@
+from __future__ import annotations
+
+import base64
+from copy import deepcopy
+from datetime import datetime, timezone
+from io import BytesIO
+from zipfile import ZIP_STORED, ZipFile
+
+from lxml import etree
+from PIL import Image
+
+from mineru.backend.analyze import doc_analyze
+from mineru.model.flash.epub import EpubPackage
+from mineru.render import RenderMode, render_epub
+from mineru.types import (
+ AlgorithmBodyBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ DocTitleBlock,
+ EquationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ IndexBlock,
+ MiddleJson,
+ PageAuxTextBlock,
+ PageBlock,
+ PageFootnoteBlock,
+ PageInfo,
+ ParagraphTitleBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+)
+
+from _epub_test_utils import build_epub_fixture
+from _span_test_utils import equation, hyperlink, inline
+
+_FIXED_TIME = datetime(2026, 1, 2, 3, 4, 6, tzinfo=timezone.utc)
+_PNG_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+_PNG_BYTES = base64.b64decode(_PNG_URI.split(",", 1)[1])
+_NS = {
+ "container": "urn:oasis:names:tc:opendocument:xmlns:container",
+ "dc": "http://purl.org/dc/elements/1.1/",
+ "epub": "http://www.idpf.org/2007/ops",
+ "math": "http://www.w3.org/1998/Math/MathML",
+ "opf": "http://www.idpf.org/2007/opf",
+ "xhtml": "http://www.w3.org/1999/xhtml",
+}
+
+
+def _middle(*pages: PageInfo) -> MiddleJson:
+ """构造无需固定版式 bbox 的测试 MiddleJson。"""
+ return MiddleJson(
+ pages=list(pages),
+ is_full_document=True,
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:
+ """按调用方顺序构造一页测试内容。"""
+ return PageInfo(page_idx=page_idx, blocks=list(blocks))
+
+
+def _archive(payload: bytes) -> ZipFile:
+ """从内存字节打开 EPUB ZIP,供测试读取成员。"""
+ return ZipFile(BytesIO(payload))
+
+
+def _xml(archive: ZipFile, name: str) -> etree._Element:
+ """使用禁用网络和实体的 parser 读取 EPUB XML 成员。"""
+ parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True, recover=False)
+ return etree.fromstring(archive.read(name), parser=parser)
+
+
+def _text(element: etree._Element) -> str:
+ """合并 XML 节点全部可见文本,便于断言。"""
+ return "".join(element.itertext())
+
+
+def test_epub_package_is_single_spine_epub33_with_stable_metadata_and_mathml() -> None:
+ """验证 OCF、必需元数据、单正文 spine、导航和确定性输出。"""
+ middle = _middle(
+ _page(
+ 0,
+ DocTitleBlock(type="doc_title", index=0, level=1, anchor="chapter-one", content=inline("Book Title")),
+ TextBlock(
+ type="text",
+ index=1,
+ content=[*inline("Inline "), equation("x^2"), *inline(" and text")],
+ ),
+ EquationBlock(type="equation", index=2, content=r"\frac{a}{b}"),
+ )
+ )
+
+ first = render_epub(
+ middle,
+ authors=("Alice", "Bob"),
+ language="en-US",
+ modified_at=_FIXED_TIME,
+ )
+ second = render_epub(
+ middle,
+ authors=("Alice", "Bob"),
+ language="en-US",
+ modified_at=_FIXED_TIME,
+ )
+ assert first == second
+ later = render_epub(
+ middle,
+ authors=("Alice", "Bob"),
+ language="en-US",
+ modified_at=datetime(2027, 2, 3, tzinfo=timezone.utc),
+ )
+
+ with _archive(first) as archive:
+ members = archive.infolist()
+ assert members[0].filename == "mimetype"
+ assert members[0].compress_type == ZIP_STORED
+ assert members[0].extra == b""
+ assert archive.read("mimetype") == b"application/epub+zip"
+ assert [item.filename for item in members if item.filename.endswith(".xhtml")] == [
+ "EPUB/nav.xhtml",
+ "EPUB/text/content.xhtml",
+ ]
+
+ container = _xml(archive, "META-INF/container.xml")
+ assert (
+ container.xpath("string(container:rootfiles/container:rootfile/@full-path)", namespaces=_NS) == "EPUB/package.opf"
+ )
+
+ package = _xml(archive, "EPUB/package.opf")
+ assert package.xpath("string(opf:metadata/dc:title)", namespaces=_NS) == "Book Title"
+ assert package.xpath("string(opf:metadata/dc:language)", namespaces=_NS) == "en-US"
+ assert package.xpath("opf:metadata/dc:creator/text()", namespaces=_NS) == ["Alice", "Bob"]
+ assert package.xpath("string(opf:metadata/opf:meta[@property='dcterms:modified'])", namespaces=_NS) == (
+ "2026-01-02T03:04:06Z"
+ )
+ assert package.xpath("string(opf:metadata/dc:identifier)", namespaces=_NS).startswith("urn:uuid:")
+ assert package.xpath("count(opf:spine/opf:itemref)", namespaces=_NS) == 1.0
+ assert package.xpath("string(opf:manifest/opf:item[@id='content']/@properties)", namespaces=_NS) == "mathml"
+
+ navigation = _xml(archive, "EPUB/nav.xhtml")
+ assert navigation.xpath("count(xhtml:body/xhtml:nav[@epub:type='toc'])", namespaces=_NS) == 1.0
+ assert navigation.xpath("string(//xhtml:nav[@epub:type='toc']//xhtml:a/@href)", namespaces=_NS) == (
+ "text/content.xhtml#chapter-one"
+ )
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ assert content.xpath("count(//math:math)", namespaces=_NS) == 2.0
+ assert not content.xpath("//xhtml:script", namespaces=_NS)
+ with _archive(later) as archive:
+ later_package = _xml(archive, "EPUB/package.opf")
+ later_identifier = later_package.xpath("string(opf:metadata/dc:identifier)", namespaces=_NS)
+ with _archive(first) as archive:
+ first_package = _xml(archive, "EPUB/package.opf")
+ first_identifier = first_package.xpath("string(opf:metadata/dc:identifier)", namespaces=_NS)
+ assert later_identifier == first_identifier
+
+
+def test_epub_default_and_full_modes_keep_shared_planner_semantics_without_mutation() -> None:
+ """验证 DEFAULT 连续阅读、FULL 页面边界和严格输入不可变。"""
+ middle = _middle(
+ _page(
+ 0,
+ PageAuxTextBlock(type="header", index=0, content=inline("HEADER")),
+ TextBlock(type="text", index=1, content=inline("inter-")),
+ ),
+ _page(5),
+ _page(
+ 9,
+ TextBlock(type="text", index=0, content=inline("national"), continues_prev=True),
+ PageAuxTextBlock(type="footer", index=1, content=inline("FOOTER")),
+ ),
+ )
+ original = deepcopy(middle)
+
+ default = render_epub(middle, modified_at=_FIXED_TIME)
+ full = render_epub(middle, mode=RenderMode.FULL, modified_at=_FIXED_TIME)
+
+ with _archive(default) as archive:
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ paragraphs = content.xpath("//xhtml:p[contains(@class, 'mineru-text')]", namespaces=_NS)
+ assert [_text(item) for item in paragraphs] == ["international"]
+ assert not content.xpath("//xhtml:section[contains(@class, 'mineru-page')]", namespaces=_NS)
+ assert "HEADER" not in _text(content) and "FOOTER" not in _text(content)
+ with _archive(full) as archive:
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ assert content.xpath("//xhtml:section[contains(@class, 'mineru-page')]/@data-page-idx", namespaces=_NS) == [
+ "0",
+ "5",
+ "9",
+ ]
+ assert content.xpath("count(//xhtml:hr[contains(@class, 'mineru-page-break')])", namespaces=_NS) == 2.0
+ paragraphs = content.xpath("//xhtml:p[contains(@class, 'mineru-text')]", namespaces=_NS)
+ assert [_text(item) for item in paragraphs] == ["inter-", "national"]
+ assert "HEADER" in _text(content) and "FOOTER" in _text(content)
+ assert middle == original
+
+
+def test_epub_navigation_prefers_valid_index_then_falls_back_to_heading_hierarchy() -> None:
+ """验证源目录优先、无效项过滤和标题层级回退。"""
+ source_index = IndexBlock(
+ type="index",
+ index=0,
+ content=[
+ ParagraphTitleBlock(type="paragraph_title", level=2, anchor="a", content=inline("Source A\t1")),
+ IndexBlock(
+ type="index",
+ content=[
+ ParagraphTitleBlock(type="paragraph_title", level=3, anchor="b", content=inline("Source B\t2")),
+ ParagraphTitleBlock(type="paragraph_title", level=3, anchor="missing", content=inline("Missing")),
+ ],
+ ),
+ ],
+ )
+ indexed = _middle(
+ _page(
+ 0,
+ source_index,
+ ParagraphTitleBlock(type="paragraph_title", index=1, level=2, anchor="a", content=inline("Heading A")),
+ ParagraphTitleBlock(type="paragraph_title", index=2, level=3, anchor="b", content=inline("Heading B")),
+ )
+ )
+ with _archive(render_epub(indexed, modified_at=_FIXED_TIME)) as archive:
+ navigation = _xml(archive, "EPUB/nav.xhtml")
+ toc = navigation.xpath("//xhtml:nav[@epub:type='toc']", namespaces=_NS)[0]
+ assert toc.xpath(".//xhtml:a/text()", namespaces=_NS) == ["Source A", "Source B"]
+ assert toc.xpath(".//xhtml:a/@href", namespaces=_NS) == [
+ "text/content.xhtml#a",
+ "text/content.xhtml#b",
+ ]
+ assert toc.xpath("count(./xhtml:ol/xhtml:li/xhtml:ol/xhtml:li)", namespaces=_NS) == 1.0
+
+ fallback = _middle(
+ _page(
+ 0,
+ ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="same", content=inline("First")),
+ ParagraphTitleBlock(type="paragraph_title", index=1, level=4, anchor="child", content=inline("Child")),
+ ParagraphTitleBlock(type="paragraph_title", index=2, level=2, anchor="same", content=inline("Second")),
+ )
+ )
+ with _archive(render_epub(fallback, modified_at=_FIXED_TIME)) as archive:
+ navigation = _xml(archive, "EPUB/nav.xhtml")
+ toc = navigation.xpath("//xhtml:nav[@epub:type='toc']", namespaces=_NS)[0]
+ assert toc.xpath(".//xhtml:a/text()", namespaces=_NS) == ["First", "Child", "Second"]
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ assert content.xpath("//xhtml:h2/@id | //xhtml:h4/@id", namespaces=_NS) == ["same", "child", "same-2"]
+
+
+def test_epub_assets_are_embedded_deduplicated_and_missing_sources_degrade_to_text() -> None:
+ """验证 resolver/base64 去重、富 HTML 图片重写及缺图文字降级。"""
+ requested: list[str] = []
+
+ def resolve_asset(path: str) -> bytes:
+ """记录 sidecar 请求,并仅为已知图片返回有效 PNG。"""
+ requested.append(path)
+ if path != "images/shared.png":
+ raise FileNotFoundError(path)
+ return _PNG_BYTES
+
+ middle = _middle(
+ _page(
+ 0,
+ ImageBlock.model_validate(
+ {
+ "type": "image",
+ "index": 0,
+ "content": [
+ {"type": "image_caption", "content": inline("Primary caption")},
+ {
+ "type": "image_body",
+ "index": 0,
+ "content": "Primary OCR",
+ "image_path": "images/shared.png",
+ "image_base64": _PNG_URI,
+ },
+ ],
+ }
+ ),
+ TableBlock(
+ type="table",
+ index=1,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=1,
+ content=(
+ '<table><tr><td><img src="images/shared.png" alt="Cell image"/></td></tr></table>'
+ "<ul>Loose text<div>Nested text</div><li>List item</li></ul><!--hidden comment-->"
+ '<script>alert(1)</script><a href="missing.xhtml">Relative link text</a>'
+ ),
+ )
+ ],
+ ),
+ ImageBlock(
+ type="image",
+ index=2,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=2,
+ content="Remote OCR",
+ image_url="https://example.com/remote.png",
+ )
+ ],
+ ),
+ ImageBlock(
+ type="image",
+ index=3,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=3,
+ content="Broken OCR",
+ image_path="images/missing.png",
+ image_base64="data:image/png;base64,broken",
+ )
+ ],
+ ),
+ )
+ )
+
+ payload = render_epub(middle, asset_resolver=resolve_asset, modified_at=_FIXED_TIME)
+ with _archive(payload) as archive:
+ assets = [name for name in archive.namelist() if name.startswith("EPUB/assets/")]
+ assert len(assets) == 1
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ sources = content.xpath("//xhtml:img/@src", namespaces=_NS)
+ assert len(sources) == 2 and len(set(sources)) == 1
+ assert all(source.startswith("../assets/") for source in sources)
+ visible = _text(content)
+ assert all(value in visible for value in ("Primary OCR", "Primary caption", "Remote OCR", "Broken OCR"))
+ assert "Relative link text" in visible
+ assert "Loose textNested textList item" in visible
+ assert "hidden comment" not in visible
+ assert not content.xpath("//xhtml:script", namespaces=_NS)
+ assert not content.xpath("//xhtml:a[@href='missing.xhtml']", namespaces=_NS)
+ assert "https://example.com/remote.png" not in archive.read("EPUB/text/content.xhtml").decode()
+ assert requested == ["images/shared.png", "images/missing.png"]
+
+
+def test_epub_mathml_failure_uses_visible_latex_without_false_manifest_property() -> None:
+ """验证无效 LaTeX 回退为可见文本且不会误声明 mathml。"""
+ middle = _middle(_page(0, EquationBlock(type="equation", index=0, content="{")))
+ with _archive(render_epub(middle, modified_at=_FIXED_TIME)) as archive:
+ package = _xml(archive, "EPUB/package.opf")
+ assert package.xpath("string(opf:manifest/opf:item[@id='content']/@properties)", namespaces=_NS) == ""
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ assert not content.xpath("//math:math", namespaces=_NS)
+ fallback = content.xpath("//xhtml:code[contains(@class, 'mineru-latex-fallback')]", namespaces=_NS)
+ assert len(fallback) == 1 and _text(fallback[0]) == "{"
+
+
+def test_epub_static_chart_code_and_algorithm_cover_remaining_visual_bodies() -> None:
+ """验证 chart、空代码和带行内公式算法均有无脚本静态表示。"""
+ middle = _middle(
+ _page(
+ 0,
+ ChartBlock(
+ type="chart",
+ index=0,
+ sub_type="bar",
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=0,
+ content="| A | B |\n| --- | --- |\n| 1 | 2 |",
+ )
+ ],
+ ),
+ CodeBlock(
+ type="code",
+ index=1,
+ sub_type="code",
+ guess_lang="python",
+ content=[CodeBodyBlock(type="code_body", index=1, content="")],
+ ),
+ CodeBlock(
+ type="code",
+ index=2,
+ sub_type="algorithm",
+ content=[
+ AlgorithmBodyBlock(
+ type="algorithm_body",
+ index=2,
+ content=[*inline("Step ", styles=["bold"]), equation("x+1")],
+ )
+ ],
+ ),
+ )
+ )
+ with _archive(render_epub(middle, modified_at=_FIXED_TIME)) as archive:
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ assert "| A | B |" in _text(content)
+ code = content.xpath("//xhtml:pre[contains(@class, 'mineru-code')]/xhtml:code", namespaces=_NS)
+ assert len(code) == 1 and code[0].get("class") == "language-python"
+ assert content.xpath("//xhtml:div[contains(@class, 'mineru-algorithm')]//xhtml:strong", namespaces=_NS)
+ assert content.xpath("//xhtml:div[contains(@class, 'mineru-algorithm')]//math:math", namespaces=_NS)
+ assert not content.xpath("//xhtml:script", namespaces=_NS)
+
+
+def test_epub_resolver_converts_webp_to_manifested_png() -> None:
+ """验证 reader 兼容性较弱的 WebP sidecar 会在内存中转为 PNG。"""
+ source = BytesIO()
+ Image.new("RGBA", (2, 2), (10, 20, 30, 128)).save(source, format="WEBP", lossless=True)
+ middle = _middle(
+ _page(
+ 0,
+ ImageBlock(
+ type="image",
+ index=0,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=0,
+ content="WebP image",
+ image_path="images/source.webp",
+ )
+ ],
+ ),
+ )
+ )
+ payload = render_epub(
+ middle,
+ modified_at=_FIXED_TIME,
+ asset_resolver=lambda _: source.getvalue(),
+ )
+ with _archive(payload) as archive:
+ asset_names = [name for name in archive.namelist() if name.startswith("EPUB/assets/")]
+ assert len(asset_names) == 1 and asset_names[0].endswith(".png")
+ assert archive.read(asset_names[0]).startswith(b"\x89PNG\r\n\x1a\n")
+ package = _xml(archive, "EPUB/package.opf")
+ assert package.xpath("string(opf:manifest/opf:item[starts-with(@id, 'asset-')]/@media-type)", namespaces=_NS) == (
+ "image/png"
+ )
+
+
+def test_real_epub_middlejson_renders_and_roundtrips_through_existing_flash_parser() -> None:
+ """验证丰富 EPUB fixture 的所有核心结构可生成并由现有 parser 回读。"""
+ source, _ = doc_analyze(build_epub_fixture(), file_suffix="epub")
+ payload = render_epub(source, modified_at=_FIXED_TIME)
+
+ package = EpubPackage(payload)
+ try:
+ assert len(package.spine) == 1
+ assert package.metadata.title == "Chapter One"
+ finally:
+ package.close()
+
+ with _archive(payload) as archive:
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ assert content.xpath("//xhtml:table", namespaces=_NS)
+ assert content.xpath("//math:math", namespaces=_NS)
+ assert content.xpath("//xhtml:aside[@epub:type='footnote']", namespaces=_NS)
+ assert content.xpath("//xhtml:pre", namespaces=_NS)
+ assert content.xpath("//xhtml:ol | //xhtml:ul", namespaces=_NS)
+ assert content.xpath("//xhtml:img", namespaces=_NS)
+
+ roundtrip, _ = doc_analyze(payload, file_suffix="epub")
+ assert len(roundtrip.pages) == 1
+ visible = " ".join(str(block.content) for page in roundtrip.pages for block in page.blocks if hasattr(block, "content"))
+ assert "Chapter One" in visible and "Section Two" in visible and "Footnote body" in visible
+
+
+def test_epub_fragment_links_gain_noteref_semantics_and_external_links_remain() -> None:
+ """验证脚注 fragment 被标为 noteref,安全外链保持可点击。"""
+ middle = _middle(
+ _page(
+ 0,
+ TextBlock(
+ type="text",
+ index=0,
+ content=[
+ *inline("See "),
+ hyperlink("#note", "[1]"),
+ *inline(" and "),
+ hyperlink("https://example.com/a b", "external"),
+ ],
+ ),
+ PageFootnoteBlock(
+ type="page_footnote",
+ index=1,
+ anchor="note",
+ content=inline("Footnote body"),
+ ),
+ )
+ )
+ with _archive(render_epub(middle, modified_at=_FIXED_TIME)) as archive:
+ content = _xml(archive, "EPUB/text/content.xhtml")
+ note_link = content.xpath("//xhtml:a[@href='#note']", namespaces=_NS)[0]
+ assert note_link.get(f"{{{_NS['epub']}}}type") == "noteref"
+ assert note_link.get("role") == "doc-noteref"
+ assert content.xpath("string(//xhtml:a[normalize-space(.)='external']/@href)", namespaces=_NS) == (
+ "https://example.com/a%20b"
+ )
diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.py
index 0452d498..a20fba47 100644
--- a/tests/unittest/test_flash_epub.py
+++ b/tests/unittest/test_flash_epub.py
@@ -11,6 +11,7 @@ from zipfile import ZIP_DEFLATED, ZipFile
import pytest
from bs4 import BeautifulSoup
from lxml import etree
+from loguru import logger
import mineru.model.flash.epub.package as epub_package_module
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
@@ -542,6 +543,33 @@ def test_epub_corrupt_chapter_keeps_empty_spine_placeholder() -> None:
assert "SVG text" in inline_text(middle.pages[2].blocks[0].content) # type: ignore[union-attr]
+def test_epub_malformed_xhtml_warns_and_recovers_without_relaxing_xml_part() -> None:
+ """验证正文 XHTML 严格失败后告警恢复,而通用 XML 入口仍保持严格。"""
+ payload = build_epub_fixture(unclosed_br_second_chapter=True)
+ package = EpubPackage(payload)
+ try:
+ assert package.xml_part("EPUB/text/ch2.xhtml", allow_external_doctype=True) is None
+ recovered = package.xhtml_part("EPUB/text/ch2.xhtml", allow_external_doctype=True)
+ assert recovered is not None
+ assert etree.QName(recovered).localname == "html"
+ finally:
+ package.close()
+
+ warning_messages: list[str] = []
+ sink_id = logger.add(lambda message: warning_messages.append(str(message)), level="WARNING", format="{message}")
+ try:
+ middle, model = doc_analyze(payload, file_suffix="epub")
+ finally:
+ logger.remove(sink_id)
+
+ assert len(model.pages) == 3
+ assert model.pages[1]
+ assert "Recovered before" in str(model.pages[1])
+ assert "Recovered after" in str(model.pages[1])
+ assert middle.pages[1].blocks
+ assert any("Recovered malformed EPUB XHTML part path='EPUB/text/ch2.xhtml'" in message for message in warning_messages)
+
+
def test_epub_svg_extraction_skips_hidden_descendants_and_hidden_root() -> None:
"""验证 standalone SVG 不提取隐藏文本、隐藏图片或隐藏祖先子树。"""
package = EpubPackage(build_epub_fixture())
@@ -610,9 +638,23 @@ def test_epub_rejects_encrypted_unsafe_and_dtd_inputs() -> None:
try:
with pytest.raises(EpubParseError, match="DTD declarations are not allowed"):
dtd_package.xml_part("EPUB/text/ch1.xhtml")
+ with pytest.raises(EpubParseError, match="DTD declarations are not allowed"):
+ dtd_package.xhtml_part("EPUB/text/ch1.xhtml", allow_external_doctype=True)
finally:
dtd_package.close()
+ malformed_dtd_package = EpubPackage(
+ build_epub_fixture(
+ dtd_first_chapter=True,
+ unclosed_br_first_chapter=True,
+ )
+ )
+ try:
+ with pytest.raises(EpubParseError, match="DTD declarations are not allowed"):
+ malformed_dtd_package.xhtml_part("EPUB/text/ch1.xhtml", allow_external_doctype=True)
+ finally:
+ malformed_dtd_package.close()
+
def test_epub_resource_limits_fail_before_semantic_conversion(monkeypatch: pytest.MonkeyPatch) -> None:
"""验证 ZIP 条目与 XML 深度预算在正文遍历前生效。"""
diff --git a/tests/unittest/test_pdf_render.py b/tests/unittest/test_pdf_render.py
new file mode 100644
index 00000000..6cad5cdc
--- /dev/null
+++ b/tests/unittest/test_pdf_render.py
@@ -0,0 +1,455 @@
+from __future__ import annotations
+
+from concurrent.futures import ThreadPoolExecutor
+from copy import deepcopy
+from io import BytesIO
+import base64
+
+from PIL import Image
+from pypdf import PdfReader
+import pytest
+from reportlab.graphics.shapes import Drawing
+import ziamath
+
+from _span_test_utils import inline as _inline
+from mineru.render import RenderMode, render_pdf
+from mineru.render._internal.pdf import formula as formula_module
+from mineru.render._internal.pdf.formula import FormulaRenderer, FormulaVector, PdfFormulaError
+from mineru.types import (
+ AlgorithmBodyBlock,
+ ChartAnnotationBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ DocTitleBlock,
+ EquationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ IndexBlock,
+ ListBlock,
+ MiddleJson,
+ PageAuxTextBlock,
+ PageBlock,
+ PageFootnoteBlock,
+ PageInfo,
+ ParagraphTitleBlock,
+ TableBlock,
+ TextBlock,
+)
+
+
+def _middle(*pages: PageInfo) -> MiddleJson:
+ """构造无需源坐标布局的严格测试 MiddleJson。"""
+ return MiddleJson(
+ pages=list(pages),
+ is_full_document=True,
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:
+ """按调用方顺序构造一页测试内容。"""
+ return PageInfo(page_idx=page_idx, blocks=list(blocks))
+
+
+def _png_bytes(size: tuple[int, int] = (20, 10)) -> bytes:
+ """生成可由 Pillow、ReportLab 与 pypdf 测试读取的 PNG。"""
+ output = BytesIO()
+ Image.new("RGB", size, (30, 80, 130)).save(output, format="PNG")
+ return output.getvalue()
+
+
+def _png_uri() -> str:
+ """返回有效 PNG data URI。"""
+ return f"data:image/png;base64,{base64.b64encode(_png_bytes()).decode('ascii')}"
+
+
+def _reader(payload: bytes) -> PdfReader:
+ """从内存 bytes 打开 PDF 并先验证固定签名。"""
+ assert payload.startswith(b"%PDF-")
+ return PdfReader(BytesIO(payload))
+
+
+def _page_text(reader: PdfReader, page_index: int) -> str:
+ """提取指定 PDF 页的可搜索文字。"""
+ return reader.pages[page_index].extract_text() or ""
+
+
+def test_pdf_defaults_to_full_and_preserves_empty_pages_auxiliary_blocks_and_input() -> None:
+ """验证 PDF 默认 FULL、空页、页面辅助块、源页边界与输入无副作用。"""
+ middle = _middle(
+ _page(
+ 0,
+ PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),
+ TextBlock(type="text", index=1, content=_inline("inter-")),
+ ),
+ _page(5),
+ _page(
+ 9,
+ TextBlock(type="text", index=0, content=_inline("national"), continues_prev=True),
+ PageAuxTextBlock(type="footer", index=1, content=_inline("FOOTER")),
+ ),
+ )
+ original = deepcopy(middle)
+
+ full_payload = render_pdf(middle, document_title="PDF Contract")
+ assert full_payload == render_pdf(middle, document_title="PDF Contract")
+ full_reader = _reader(full_payload)
+ default_reader = _reader(render_pdf(middle, mode=RenderMode.DEFAULT))
+
+ assert len(full_reader.pages) == 3
+ assert "HEADER" in _page_text(full_reader, 0) and "inter-" in _page_text(full_reader, 0)
+ assert not _page_text(full_reader, 1).strip()
+ assert "national" in _page_text(full_reader, 2) and "FOOTER" in _page_text(full_reader, 2)
+ assert full_reader.metadata.title == "PDF Contract"
+ assert full_reader.metadata.creation_date is not None and full_reader.metadata.creation_date.year == 2000
+ assert len(default_reader.pages) == 1
+ assert "international" in _page_text(default_reader, 0).replace("\n", "")
+ assert "HEADER" not in _page_text(default_reader, 0) and "FOOTER" not in _page_text(default_reader, 0)
+ assert middle == original
+
+
+def test_pdf_renders_inline_and_display_formulas_as_vector_paths_with_links() -> None:
+ """验证行内/行间公式矢量化、标签、中文混排及内外部链接。"""
+ middle = _middle(
+ _page(
+ 0,
+ ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="section-one", content=_inline("章节一")),
+ TextBlock(
+ type="text",
+ index=1,
+ content=[
+ {"type": "text", "content": "中文 Before "},
+ {"type": "equation_inline", "content": r"c=\pm\sqrt{a^2+b^2}"},
+ {"type": "text", "content": " after "},
+ {"type": "hyperlink", "url": "#section-one", "content": _inline("jump")},
+ {"type": "text", "content": " and "},
+ {"type": "hyperlink", "url": "https://example.com", "content": _inline("external")},
+ ],
+ ),
+ EquationBlock(type="equation", index=2, content=r"\frac{1}{1-x^2}\tag{7}"),
+ )
+ )
+
+ reader = _reader(render_pdf(middle))
+ text = _page_text(reader, 0)
+ resources = reader.pages[0]["/Resources"]
+ xobjects = resources.get("/XObject", {})
+ image_xobjects = [value for value in xobjects.values() if value.get_object().get("/Subtype") == "/Image"]
+
+ assert "章节一" in text and "中文 Before" in text and "after" in text
+ assert "jump" in text and "external" in text
+ assert not image_xobjects
+ assert len(reader.pages[0].get("/Annots", [])) >= 2
+ stream = reader.pages[0].get_contents().get_data()
+ assert b" m" in stream and (b" c" in stream or b" l" in stream)
+
+
+def test_pdf_formula_failures_fall_back_to_visible_latex(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 ZiaMath 失败时行内与行间公式均保留可见 LaTeX。"""
+ original_render = FormulaRenderer.render
+
+ def fail_bad_formula(
+ self: FormulaRenderer,
+ latex: str,
+ *,
+ inline: bool,
+ font_size: float,
+ color: str = "#1f2937",
+ ) -> object:
+ """仅让测试公式进入稳定回退,其余公式沿用真实实现。"""
+ if latex == "bad":
+ raise PdfFormulaError("synthetic formula failure")
+ return original_render(self, latex, inline=inline, font_size=font_size, color=color)
+
+ monkeypatch.setattr(FormulaRenderer, "render", fail_bad_formula)
+ middle = _middle(
+ _page(
+ 0,
+ TextBlock(
+ type="text",
+ index=0,
+ content=[{"type": "text", "content": "inline "}, {"type": "equation_inline", "content": "bad"}],
+ ),
+ EquationBlock(type="equation", index=1, content="bad"),
+ )
+ )
+
+ text = _page_text(_reader(render_pdf(middle)), 0)
+
+ assert "$bad$" in text
+ assert "bad" in text
+
+
+ "source,inline",
+ [
+ (r"\frac{1}{1-x^2}", False),
+ (r"\sqrt[3]{x+y}", True),
+ (r"\sum_{i=1}^{n} i^2", False),
+ (r"\int_0^\infty e^{-x}\,dx", False),
+ (r"\begin{bmatrix}a&b\\c&d\end{bmatrix}", False),
+ (r"\left(\frac{x}{y}\right)^2", True),
+ (r"\begin{aligned}a&=b+c\\d&=e\end{aligned}", False),
+ (r"\color{red}{x}+\boxed{y}", True),
+ ],
+)
+def test_ziamath_vector_corpus_covers_inline_and_display_constructs(source: str, inline: bool) -> None:
+ """验证分数、根式、积分、矩阵、aligned 与颜色均能生成有效矢量几何。"""
+ vector = FormulaRenderer().render(source, inline=inline, font_size=12)
+
+ assert vector.width > 0 and vector.height > 0
+ assert vector.ascent >= 0 and vector.descent >= 0
+ assert vector.drawing.contents
+
+
+def test_formula_cache_is_bounded_and_skips_oversized_entries(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证公式超长或唯一项超过预算时继续渲染但不扩张文档级缓存。"""
+ calls: list[str] = []
+
+ def fake_render(latex: str, *, inline: bool, font_size: float, color: str) -> FormulaVector:
+ """返回固定矢量并记录实际转换次数。"""
+ calls.append(latex)
+ return FormulaVector(Drawing(1, 1), width=1, height=1, ascent=1, descent=0)
+
+ monkeypatch.setattr(formula_module, "_render_ziamath_formula", fake_render)
+ renderer = FormulaRenderer()
+ oversized = "x" * (formula_module.MAX_FORMULA_CHARACTERS + 1)
+ renderer.render(oversized, inline=True, font_size=10)
+ renderer.render(oversized, inline=True, font_size=10)
+ for index in range(formula_module.MAX_CACHED_FORMULAS + 3):
+ renderer.render(f"x_{index}", inline=True, font_size=10)
+
+ assert calls.count(oversized) == 2
+ assert len(renderer._cache) == formula_module.MAX_CACHED_FORMULAS # noqa: SLF001
+
+
+def test_long_formulas_scale_or_wrap_without_hiding_surrounding_text() -> None:
+ """验证超宽行内与行间公式缩放后仍保留前后可搜索正文。"""
+ formula = "+".join(f"x_{index}^2" for index in range(45))
+ middle = _middle(
+ _page(
+ 0,
+ TextBlock(
+ type="text",
+ index=0,
+ content=[
+ {"type": "text", "content": "before long formula "},
+ {"type": "equation_inline", "content": formula},
+ {"type": "text", "content": " after long formula"},
+ ],
+ ),
+ EquationBlock(type="equation", index=1, content=formula + r"\tag{wide}"),
+ )
+ )
+
+ reader = _reader(render_pdf(middle))
+ text = "\n".join(_page_text(reader, index) for index in range(len(reader.pages)))
+
+ assert "before long formula" in text
+ assert "after long formula" in text
+
+
+def test_pdf_uses_asset_resolver_and_replaces_missing_or_remote_images_with_placeholders() -> None:
+ """验证 sidecar 优先级、有效图片、损坏素材和远程 URL 的宽松占位策略。"""
+ requested: list[str] = []
+
+ def resolve_asset(path: str) -> bytes:
+ """记录图片请求,并分别返回有效或损坏字节。"""
+ requested.append(path)
+ return _png_bytes() if path == "images/ok.png" else b"broken"
+
+ middle = _middle(
+ _page(
+ 0,
+ ImageBlock(
+ type="image",
+ index=0,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=0,
+ content="valid image",
+ image_path="images/ok.png",
+ image_base64=_png_uri(),
+ )
+ ],
+ ),
+ ImageBlock(
+ type="image",
+ index=1,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=1,
+ content="external svg",
+ image_base64=(
+ "data:image/svg+xml;base64,"
+ + base64.b64encode(
+ b'<svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>'
+ ).decode("ascii")
+ ),
+ )
+ ],
+ ),
+ ImageBlock(
+ type="image",
+ index=2,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=2,
+ content="broken image",
+ image_path="images/broken.png",
+ )
+ ],
+ ),
+ ImageBlock(
+ type="image",
+ index=3,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=3,
+ content="remote image",
+ image_url="https://example.com/image.png",
+ )
+ ],
+ ),
+ )
+ )
+
+ reader = _reader(render_pdf(middle, asset_resolver=resolve_asset))
+ text = _page_text(reader, 0)
+
+ assert requested == ["images/ok.png", "images/broken.png"]
+ assert text.count("image unavailable") == 3
+ assert "https://example.com/image.png" in text
+ assert "page_idx=0, block_index=2, block_type=image_body" in text
+
+
+def test_pdf_renders_tables_lists_indices_code_algorithm_and_annotations() -> None:
+ """验证原生表格合并、嵌套表、目录、列表、代码算法与说明的组合输出。"""
+ table = TableBlock.model_validate(
+ {
+ "type": "table",
+ "index": 2,
+ "content": [
+ {
+ "type": "table_body",
+ "index": 2,
+ "content": (
+ "<table><thead><tr><th colspan='2'>Header</th></tr></thead>"
+ "<tbody><tr><td rowspan='2'>A<eq>x^2</eq></td><td>B</td></tr>"
+ "<tr><td><table><tr><td>Nested</td></tr></table></td></tr></tbody></table>"
+ ),
+ },
+ {"type": "table_caption", "content": _inline("Table caption")},
+ {"type": "table_footnote", "content": _inline("Table note")},
+ ],
+ }
+ )
+ index = IndexBlock(
+ type="index",
+ index=1,
+ content=[ParagraphTitleBlock(type="paragraph_title", level=2, anchor="target", content=_inline("Target\t9"))],
+ )
+ code = CodeBlock(
+ type="code",
+ index=3,
+ sub_type="code",
+ guess_lang="python",
+ content=[
+ CodeBodyBlock(type="code_body", index=3, content="print('中文')\nprint(2)"),
+ {"type": "code_caption", "content": _inline("Code caption")},
+ ],
+ )
+ algorithm = CodeBlock(
+ type="code",
+ index=4,
+ sub_type="algorithm",
+ content=[
+ AlgorithmBodyBlock(
+ type="algorithm_body",
+ index=4,
+ content=[{"type": "text", "content": "for "}, {"type": "equation_inline", "content": "n^2"}],
+ )
+ ],
+ )
+ chart = ChartBlock(
+ type="chart",
+ index=5,
+ sub_type="bar",
+ content=[
+ ChartBodyBlock(type="chart_body", index=5, content="<table><tr><th>Year</th></tr><tr><td>2026</td></tr></table>"),
+ ChartAnnotationBlock(type="chart_caption", content=_inline("Chart caption")),
+ ],
+ )
+ middle = _middle(
+ _page(
+ 0,
+ ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="target", content=_inline("Target")),
+ index,
+ table,
+ code,
+ algorithm,
+ chart,
+ ListBlock(type="list", index=6, content=[TextBlock(type="text", content=_inline("1. item"))]),
+ PageFootnoteBlock(type="page_footnote", index=7, anchor="note", content=_inline("Page note")),
+ )
+ )
+
+ reader = _reader(render_pdf(middle))
+ text = "\n".join(_page_text(reader, index) for index in range(len(reader.pages)))
+
+ for expected in (
+ "Target",
+ "Header",
+ "Nested",
+ "Table caption",
+ "Table note",
+ "print('中文')",
+ "Code caption",
+ "Year",
+ "2026",
+ "Chart caption",
+ "1. item",
+ "Page note",
+ ):
+ assert expected in text
+
+
+def test_pdf_formula_configuration_is_restored_across_parallel_renders() -> None:
+ """验证并行 PDF 公式渲染不会泄漏 ZiaMath 的进程级 svg2 配置。"""
+ previous_svg2 = ziamath.config.svg2
+ middle = _middle(
+ _page(
+ 0,
+ DocTitleBlock(type="doc_title", index=0, level=1, content=_inline("Parallel")),
+ EquationBlock(type="equation", index=1, content=r"\sum_{i=1}^{n} i^2"),
+ )
+ )
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ outputs = list(executor.map(lambda _index: render_pdf(middle), range(4)))
+
+ assert all(_reader(payload).pages for payload in outputs)
+ assert ziamath.config.svg2 is previous_svg2
+
+
+def test_pdf_public_arguments_remain_strict() -> None:
+ """验证专用 PDF 门面拒绝旧 dict、字符串 mode 与错误参数类型。"""
+ middle = _middle(_page(0))
+
+ with pytest.raises(TypeError, match="MiddleJson"):
+ render_pdf(middle.to_dict()) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="RenderMode"):
+ render_pdf(middle, mode="full") # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="asset_resolver"):
+ render_pdf(middle, asset_resolver="images") # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="document_title"):
+ render_pdf(middle, document_title=1) # type: ignore[arg-type]
diff --git a/tests/unittest/test_render_api.py b/tests/unittest/test_render_api.py
index 221352d0..4225fc24 100644
--- a/tests/unittest/test_render_api.py
+++ b/tests/unittest/test_render_api.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from _span_test_utils import inline as _inline
from copy import deepcopy
+from datetime import datetime, timezone
from io import BytesIO
from docx import Document
@@ -14,8 +15,10 @@ from mineru.render import (
ContentListV2RenderOptions,
DocxRenderError,
DocxRenderOptions,
+ EpubRenderOptions,
HtmlRenderOptions,
MarkdownRenderOptions,
+ PdfRenderOptions,
RenderFormat,
RenderMode,
StructuredContentRenderOptions,
@@ -49,13 +52,19 @@ def _png_bytes() -> bytes:
def test_unified_render_dispatches_all_native_output_types_without_mutation() -> None:
- """验证统一入口默认分发四种原生结果且不修改输入。"""
+ """验证统一入口分发全部原生结果且不修改输入。"""
middle = _middle(_page(0, TextBlock(type="text", index=0, content=_inline("hello"))))
original = deepcopy(middle)
markdown = render(middle, RenderFormat.MARKDOWN)
html = render(middle, RenderFormat.HTML)
docx = render(middle, RenderFormat.DOCX)
+ epub = render(
+ middle,
+ RenderFormat.EPUB,
+ options=EpubRenderOptions(modified_at=datetime(2026, 1, 2, tzinfo=timezone.utc)),
+ )
+ pdf = render(middle, RenderFormat.PDF)
structured_content = render(middle, RenderFormat.STRUCTURED_CONTENT)
content_list = render(middle, RenderFormat.CONTENT_LIST)
content_list_v2 = render(middle, RenderFormat.CONTENT_LIST_V2)
@@ -63,6 +72,8 @@ def test_unified_render_dispatches_all_native_output_types_without_mutation() ->
assert markdown == "hello"
assert isinstance(html, str) and "<html" in html and "hello" in html
assert isinstance(docx, bytes) and docx.startswith(b"PK\x03\x04")
+ assert isinstance(epub, bytes) and epub.startswith(b"PK\x03\x04")
+ assert isinstance(pdf, bytes) and pdf.startswith(b"%PDF-")
assert Document(BytesIO(docx)).paragraphs[0].text == "hello"
assert structured_content["pages"][0]["blocks"][0]["content"] == "hello"
assert content_list == [{"type": "text", "text": "hello", "page_idx": 0}]
@@ -134,6 +145,11 @@ def test_unified_render_forwards_format_specific_options() -> None:
document_title="Unified Render",
),
)
+ pdf = render(
+ middle,
+ RenderFormat.PDF,
+ options=PdfRenderOptions(mode=RenderMode.DEFAULT, document_title="Unified Render"),
+ )
original_tree = render(middle, RenderFormat.STRUCTURED_CONTENT)
assert "\n\n---\n\n" in markdown
@@ -146,6 +162,7 @@ def test_unified_render_forwards_format_specific_options() -> None:
assert "https://cdn.example/doc/images/a%20b.png" in image_markdown
assert "<title>Unified Render</title>" in html_document
assert 'src="https://cdn.example/doc/images/a%20b.png"' in html_document
+ assert pdf == render_module.render_pdf(middle, mode=RenderMode.DEFAULT, document_title="Unified Render")
assert [page["blocks"][0]["content"] for page in original_tree["pages"]] == ["first-", "second"]
assert original_tree["pages"][1]["blocks"][0]["continues_prev"] is True
@@ -202,6 +219,10 @@ def test_unified_render_rejects_legacy_format_and_mismatched_options() -> None:
render(middle, RenderFormat.MARKDOWN, options=HtmlRenderOptions()) # type: ignore[arg-type]
with pytest.raises(TypeError, match="StructuredContentRenderOptions"):
render(middle, RenderFormat.STRUCTURED_CONTENT, options=DocxRenderOptions()) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="EpubRenderOptions"):
+ render(middle, RenderFormat.EPUB, options=DocxRenderOptions()) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="PdfRenderOptions"):
+ render(middle, RenderFormat.PDF, options=DocxRenderOptions()) # type: ignore[arg-type]
with pytest.raises(TypeError, match="ContentListRenderOptions"):
render(middle, RenderFormat.CONTENT_LIST, options=DocxRenderOptions()) # type: ignore[arg-type]
with pytest.raises(TypeError, match="ContentListV2RenderOptions"):
@@ -214,9 +235,11 @@ def test_public_options_validate_fields() -> None:
"markdown",
"html",
"docx",
+ "epub",
"structured_content",
"content_list",
"content_list_v2",
+ "pdf",
]
with pytest.raises(TypeError, match="RenderMode"):
@@ -233,6 +256,22 @@ def test_public_options_validate_fields() -> None:
HtmlRenderOptions(document_title=1) # type: ignore[arg-type]
with pytest.raises(TypeError, match="asset_resolver"):
DocxRenderOptions(asset_resolver="images") # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="authors"):
+ EpubRenderOptions(authors=["Alice"]) # type: ignore[arg-type]
+ with pytest.raises(ValueError, match="BCP 47"):
+ EpubRenderOptions(language="zh CN")
+ with pytest.raises(ValueError, match="timezone-aware"):
+ EpubRenderOptions(modified_at=datetime(2026, 1, 2))
+ with pytest.raises(ValueError, match="four digits"):
+ EpubRenderOptions(modified_at=datetime(999, 1, 2, tzinfo=timezone.utc))
+ with pytest.raises(TypeError, match="asset_resolver"):
+ EpubRenderOptions(asset_resolver="images") # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="RenderMode"):
+ PdfRenderOptions(mode="full") # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="asset_resolver"):
+ PdfRenderOptions(asset_resolver="images") # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="document_title"):
+ PdfRenderOptions(document_title=1) # type: ignore[arg-type]
def test_public_render_exposes_all_three_structured_output_names() -> None:
@@ -240,6 +279,8 @@ def test_public_render_exposes_all_three_structured_output_names() -> None:
assert callable(render_module.render_structured_content)
assert callable(render_module.render_content_list)
assert callable(render_module.render_content_list_v2)
+ assert callable(render_module.render_epub)
+ assert callable(render_module.render_pdf)
assert not hasattr(render_module, "MarkdownRenderMode")
assert ContentListRenderOptions is render_module.ContentListRenderOptions
assert ContentListV2RenderOptions is render_module.ContentListV2RenderOptions