Skip to content

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

feat: add render size support for WMF/EMF images and enhance SVG handling

myhloli5824ca43ec3a
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 3e2dcd0b..30551392 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -89,8 +89,10 @@ docx_bytes = render_docx(
`render_docx()` 只接受严格 `MiddleJson`,返回完整 `.docx` bytes,不写文件、不读取 cwd,
也不访问网络。block 同时携带两种图片来源时优先解码 `image_base64`;仅有
`image_path` 时必须提供 `asset_resolver(relative_path) -> bytes`。必需图片缺失、路径
-不安全、格式损坏或 SVG 输入会抛出带 `page_idx/block_index/block_type` 的
-`DocxRenderError`;WebP 在内存中转为 PNG。
+不安全、格式损坏或任意外部 SVG 输入会抛出带 `page_idx/block_index/block_type` 的
+`DocxRenderError`;WebP 在内存中转为 PNG。MinerU 自己生成并通过安全子集校验的
+WMF/EMF SVG 会写入 Office 2016 `asvg:svgBlip`,同时保留高密度 PNG fallback,现代
+Word/LibreOffice 可使用矢量资源,旧版 Office 仍能显示同尺寸后备图。
DOCX 输出固定使用 A4 纵向与 20 mm 页边距。标题是 Word Heading 1–9,标题与
`page_footnote` anchor 是 document-wide bookmark,Index 标题叶子和正文 `#anchor`
diff --git a/mineru/model/flash/office/doc/doc_converter.py b/mineru/model/flash/office/doc/doc_converter.py
index 213eba7e..89243758 100644
--- a/mineru/model/flash/office/doc/doc_converter.py
+++ b/mineru/model/flash/office/doc/doc_converter.py
@@ -167,6 +167,7 @@ class DocConverter:
payload.data,
part_name=f"image.{payload.extension}",
content_type=payload.content_type,
+ render_size_emu=payload.render_size_emu,
)
@classmethod
diff --git a/mineru/model/flash/office/doc/images.py b/mineru/model/flash/office/doc/images.py
index e7c69afe..d90673a6 100644
--- a/mineru/model/flash/office/doc/images.py
+++ b/mineru/model/flash/office/doc/images.py
@@ -35,9 +35,7 @@ class ImageStore:
total: int = 0
cache: dict[bytes, DocImagePayload] = field(default_factory=dict)
- equation_decoder: OfficeImageEquationDecoder = field(
- default_factory=OfficeImageEquationDecoder
- )
+ equation_decoder: OfficeImageEquationDecoder = field(default_factory=OfficeImageEquationDecoder)
def add(self, payload: OfficeImagePayload) -> DocImagePayload:
"""计入一张唯一图片并返回内部载荷。"""
@@ -47,9 +45,7 @@ class ImageStore:
if cached is not None:
return cached
if self.total + len(payload.data) > MAX_ASSET_TOTAL_BYTES:
- raise LegacyOfficeResourceLimitError(
- f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
- )
+ raise LegacyOfficeResourceLimitError(f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}")
converted = DocImagePayload(
payload.data,
payload.extension,
@@ -59,6 +55,7 @@ class ImageStore:
part_name=f"image.{payload.extension}",
content_type=payload.content_type,
),
+ render_size_emu=payload.render_size_emu,
)
self.total += len(payload.data)
self.cache[digest] = converted
diff --git a/mineru/model/flash/office/doc/models.py b/mineru/model/flash/office/doc/models.py
index 3fabbada..ec801dc5 100644
--- a/mineru/model/flash/office/doc/models.py
+++ b/mineru/model/flash/office/doc/models.py
@@ -96,6 +96,7 @@ class DocImagePayload:
extension: str
content_type: str
equation_latex: str | None = None
+ render_size_emu: tuple[int, int] | None = None
@dataclass(frozen=True, slots=True)
diff --git a/mineru/model/flash/office/image.py b/mineru/model/flash/office/image.py
index c4311305..f869a10a 100644
--- a/mineru/model/flash/office/image.py
+++ b/mineru/model/flash/office/image.py
@@ -1,6 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
"""Flash Office 文档的图片识别、转码与占位图生成。"""
+import base64
from functools import lru_cache
from io import BytesIO
from pathlib import PurePosixPath
@@ -12,6 +13,7 @@ from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
from ....utils.platform import is_windows_environment
from .._shared.image import image_to_b64str
+from .metafile import MetafileError, render_metafile
VECTOR_IMAGE_FORMATS = frozenset({"WMF", "EMF"})
VECTOR_IMAGE_EXTENSIONS = frozenset({".wmf", ".emf"})
@@ -38,12 +40,15 @@ def _is_wmf_payload(image_data: bytes) -> bool:
"""根据 placeable 或标准 METAHEADER magic 判断原始载荷是否为 WMF。"""
return image_data.startswith(b"\xd7\xcd\xc6\x9a") or (
- len(image_data) >= 4
- and image_data[:2] in {b"\x01\x00", b"\x02\x00"}
- and image_data[2:4] == b"\x09\x00"
+ len(image_data) >= 4 and image_data[:2] in {b"\x01\x00", b"\x02\x00"} and image_data[2:4] == b"\x09\x00"
)
+def _is_emf_payload(image_data: bytes) -> bool:
+ """根据 EMR_HEADER type 与 ENHMETA_SIGNATURE 判断载荷是否为 EMF。"""
+ return len(image_data) >= 44 and struct.unpack_from("<I", image_data, 0)[0] == 1 and image_data[40:44] == b" EMF"
+
+
def is_vector_image(pil_image: Image.Image) -> bool:
"""判断已由 Pillow 打开的图片是否属于 WMF/EMF 矢量格式。"""
return (getattr(pil_image, "format", None) or "").upper() in VECTOR_IMAGE_FORMATS
@@ -69,14 +74,8 @@ def is_valid_vector_image_payload(
if label == "WMF":
return _is_wmf_payload(image_data)
if label == "EMF":
- return (
- len(image_data) >= 44
- and struct.unpack_from("<I", image_data, 0)[0] == 1
- and image_data[40:44] == b" EMF"
- )
- return _is_wmf_payload(image_data) or (
- len(image_data) >= 44 and image_data[40:44] == b" EMF"
- )
+ return _is_emf_payload(image_data)
+ return _is_wmf_payload(image_data) or _is_emf_payload(image_data)
def _vector_image_format_label(part_name: object | None = None, content_type: str | None = None) -> str:
@@ -197,35 +196,93 @@ def serialize_vector_part_with_placeholder(
return get_standard_vector_placeholder_data_uri()
+def _serialize_native_metafile(image_data: bytes, image_format: str) -> str | None:
+ """在 Windows 上优先调用 Pillow/GDI 渲染原始 WMF/EMF。"""
+ try:
+ pil_image = Image.open(BytesIO(image_data))
+ pil_image.load(dpi=VECTOR_IMAGE_RENDER_DPI)
+ return image_to_b64str(pil_image, image_format="PNG")
+ except PIL_IMAGE_LOAD_ERRORS as exc:
+ logger.warning(f"Native Windows rendering failed for {image_format}: {exc}. Falling back to MinerU renderer.")
+ return None
+
+
+def _render_size_from_emu(render_size_emu: tuple[int, int] | None) -> tuple[int, int] | None:
+ """把 OfficeArt ptSize 的 EMU 尺寸转换为 144 DPI 像素提示。"""
+ if render_size_emu is None or render_size_emu[0] <= 0 or render_size_emu[1] <= 0:
+ return None
+ emu_per_inch = 914_400
+ return (
+ max(1, round(render_size_emu[0] * VECTOR_IMAGE_RENDER_DPI / emu_per_inch)),
+ max(1, round(render_size_emu[1] * VECTOR_IMAGE_RENDER_DPI / emu_per_inch)),
+ )
+
+
+def _serialize_cross_platform_metafile(
+ image_data: bytes,
+ image_format: str,
+ *,
+ size_hint: tuple[int, int] | None = None,
+) -> str | None:
+ """调用 MinerU 内部 WMF/EMF 引擎并生成带 PNG fallback 的 SVG。"""
+ try:
+ rendered = render_metafile(
+ image_data,
+ output_format="svg",
+ dpi=VECTOR_IMAGE_RENDER_DPI,
+ size_hint=size_hint,
+ )
+ except MetafileError as exc:
+ logger.warning(f"Failed to render {image_format} image with MinerU: {exc}. Using placeholder instead.")
+ return None
+ if rendered.partial:
+ diagnostic_codes = sorted({diagnostic.code for diagnostic in rendered.diagnostics})
+ logger.warning(
+ f"Rendered partial {image_format} image with MinerU, diagnostics={diagnostic_codes[:16]}, "
+ f"size={rendered.width}x{rendered.height}"
+ )
+ encoded = base64.b64encode(rendered.data).decode("ascii")
+ return f"data:{rendered.media_type};base64,{encoded}"
+
+
def serialize_office_image(
image_data: bytes,
*,
part_name: object | None = None,
content_type: str | None = None,
+ render_size_emu: tuple[int, int] | None = None,
) -> str | None:
"""识别并序列化 Office 图片,透明图保留 PNG,普通位图优先使用 JPEG。"""
is_wmf_payload = _is_wmf_payload(image_data)
+ is_emf_payload = _is_emf_payload(image_data)
if is_wmf_payload:
part_name = "image.wmf"
content_type = "image/wmf"
- if is_wmf_payload or is_vector_image_part(part_name, content_type):
- if not is_windows_environment():
- return serialize_vector_part_with_placeholder(part_name, content_type)
-
- try:
- pil_image = Image.open(BytesIO(image_data))
- except PIL_IMAGE_LOAD_ERRORS as e:
+ elif is_emf_payload:
+ part_name = "image.emf"
+ content_type = "image/emf"
+ if is_wmf_payload or is_emf_payload or is_vector_image_part(part_name, content_type):
+ image_format = (
+ "WMF" if is_wmf_payload else "EMF" if is_emf_payload else _vector_image_format_label(part_name, content_type)
+ )
+ if not (is_wmf_payload or is_emf_payload):
logger.warning(
- f"Warning: vector image cannot be opened by Pillow: {e}, "
- f"part_name={part_name}, content_type={content_type}. "
+ f"Vector image payload does not match WMF/EMF signature, part_name={part_name}, content_type={content_type}. "
"Using placeholder instead."
)
return serialize_vector_part_with_placeholder(part_name, content_type)
-
- return serialize_vector_image_with_placeholder(
- pil_image,
- image_format_override=_vector_image_format_label(part_name, content_type),
+ rendered = _serialize_cross_platform_metafile(
+ image_data,
+ image_format,
+ size_hint=_render_size_from_emu(render_size_emu),
)
+ if rendered is not None:
+ return rendered
+ if is_windows_environment():
+ native = _serialize_native_metafile(image_data, image_format)
+ if native is not None:
+ return native
+ return serialize_vector_part_with_placeholder(part_name, content_type)
try:
pil_image = Image.open(BytesIO(image_data))
diff --git a/mineru/model/flash/office/legacy/officeart.py b/mineru/model/flash/office/legacy/officeart.py
index c0aeed31..afe2312a 100644
--- a/mineru/model/flash/office/legacy/officeart.py
+++ b/mineru/model/flash/office/legacy/officeart.py
@@ -54,6 +54,7 @@ class OfficeImagePayload:
data: bytes
extension: str
content_type: str
+ render_size_emu: tuple[int, int] | None = None
@dataclass(frozen=True, slots=True)
@@ -123,9 +124,7 @@ def iter_descendants(
stack: list[Iterator[OfficeArtRecord]] = [iter_records(data, charge=charge)]
while stack:
if len(stack) > MAX_RECORD_DEPTH:
- raise LegacyOfficeResourceLimitError(
- f"record nesting exceeds max_record_depth={MAX_RECORD_DEPTH}"
- )
+ raise LegacyOfficeResourceLimitError(f"record nesting exceeds max_record_depth={MAX_RECORD_DEPTH}")
try:
record = next(stack[-1])
except StopIteration:
@@ -237,6 +236,8 @@ def decode_blip(record: OfficeArtRecord) -> OfficeImagePayload | None:
if header_offset + 34 > len(body):
return None
declared_size = int(struct.unpack_from("<I", body, header_offset)[0])
+ render_width_emu, render_height_emu = struct.unpack_from("<ii", body, header_offset + 20)
+ render_size_emu = (render_width_emu, render_height_emu) if render_width_emu > 0 and render_height_emu > 0 else None
compressed_size = int(struct.unpack_from("<I", body, header_offset + 28)[0])
compression = body[header_offset + 32]
payload_start = header_offset + 34
@@ -260,16 +261,23 @@ def decode_blip(record: OfficeArtRecord) -> OfficeImagePayload | None:
if not reached_eof:
return None
if len(data) > MAX_ENTRY_BYTES:
- raise LegacyOfficeResourceLimitError(
- "metafile BLIP decompression exceeded its limit"
- )
+ raise LegacyOfficeResourceLimitError("metafile BLIP decompression exceeded its limit")
else:
data = payload
if record.record_type == 0xF01A:
- return OfficeImagePayload(data=data, extension="emf", content_type="image/emf")
- if data.startswith(b"\xd7\xcd\xc6\x9a") and len(data) >= 22:
- data = data[22:]
- return OfficeImagePayload(data=data, extension="wmf", content_type="image/wmf")
+ return OfficeImagePayload(
+ data=data,
+ extension="emf",
+ content_type="image/emf",
+ render_size_emu=render_size_emu,
+ )
+ # 保留合法 placeable header,使跨平台渲染器继续获得 bbox 与 units-per-inch。
+ return OfficeImagePayload(
+ data=data,
+ extension="wmf",
+ content_type="image/wmf",
+ render_size_emu=render_size_emu,
+ )
def first_blip(
@@ -338,11 +346,7 @@ def decode_bstore(
) -> dict[int, OfficeImagePayload]:
"""按一基 BSE 序号解码 drawing group 中的图片资源。"""
- bse_records = [
- record
- for record in iter_descendants(data, charge=charge)
- if record.record_type == OFFICEART_BSE
- ]
+ bse_records = [record for record in iter_descendants(data, charge=charge) if record.record_type == OFFICEART_BSE]
result: dict[int, OfficeImagePayload] = {}
asset_total = 0
for index, bse in enumerate(bse_records[:MAX_PICTURE_RECORDS], start=1):
@@ -355,9 +359,7 @@ def decode_bstore(
continue
asset_total += len(decoded.data)
if asset_total > MAX_ASSET_TOTAL_BYTES:
- raise LegacyOfficeResourceLimitError(
- f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
- )
+ raise LegacyOfficeResourceLimitError(f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}")
result[index] = decoded
if len(bse_records) > MAX_PICTURE_RECORDS:
logger.warning(
diff --git a/mineru/model/flash/office/metafile/__init__.py b/mineru/model/flash/office/metafile/__init__.py
new file mode 100644
index 00000000..ff233b68
--- /dev/null
+++ b/mineru/model/flash/office/metafile/__init__.py
@@ -0,0 +1,22 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""Office WMF/EMF 的跨平台内部渲染能力。"""
+
+from .api import render_metafile
+from .models import (
+ MetafileDiagnostic,
+ MetafileError,
+ MetafileMalformedError,
+ MetafileRenderResult,
+ MetafileResourceLimitError,
+ MetafileUnsupportedError,
+)
+
+__all__ = [
+ "MetafileDiagnostic",
+ "MetafileError",
+ "MetafileMalformedError",
+ "MetafileRenderResult",
+ "MetafileResourceLimitError",
+ "MetafileUnsupportedError",
+ "render_metafile",
+]
diff --git a/mineru/model/flash/office/metafile/api.py b/mineru/model/flash/office/metafile/api.py
new file mode 100644
index 00000000..87078cb7
--- /dev/null
+++ b/mineru/model/flash/office/metafile/api.py
@@ -0,0 +1,36 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""WMF/EMF 内部渲染入口。"""
+
+from __future__ import annotations
+
+from .models import MetafileOutputFormat, MetafileRenderResult
+from .parser import parse_metafile
+from .render import encode_document
+
+
+def render_metafile(
+ data: bytes,
+ *,
+ output_format: MetafileOutputFormat = "png",
+ dpi: int = 144,
+ size_hint: tuple[int, int] | None = None,
+) -> MetafileRenderResult:
+ """把 WMF/EMF 字节渲染为 PNG、JPEG 或安全 SVG。"""
+ if output_format not in {"png", "jpeg", "svg"}:
+ raise ValueError(f"unsupported metafile output format: {output_format}")
+ document = parse_metafile(data, dpi=dpi, size_hint=size_hint)
+ output, media_type = encode_document(document, output_format)
+ return MetafileRenderResult(
+ data=output,
+ output_format=output_format,
+ media_type=media_type,
+ width=document.width,
+ height=document.height,
+ source_format=document.source_format,
+ emfplus_mode=document.emfplus_mode,
+ partial=document.partial,
+ diagnostics=document.diagnostics,
+ )
+
+
+__all__ = ["render_metafile"]
diff --git a/mineru/model/flash/office/metafile/binary.py b/mineru/model/flash/office/metafile/binary.py
new file mode 100644
index 00000000..42876dc5
--- /dev/null
+++ b/mineru/model/flash/office/metafile/binary.py
@@ -0,0 +1,76 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""WMF/EMF 使用的严格有界二进制读取器。"""
+
+from __future__ import annotations
+
+import struct
+
+from .models import MetafileMalformedError
+
+
+class BoundedReader:
+ """在固定 memoryview 边界内读取小端标量和切片。"""
+
+ def __init__(self, data: bytes | memoryview, *, base_offset: int = 0) -> None:
+ """保存输入视图与用于诊断的绝对起始偏移。"""
+ self.data = memoryview(data)
+ self.base_offset = base_offset
+
+ def _require(self, offset: int, size: int) -> None:
+ """验证读取范围,不允许负数或越过当前视图。"""
+ if offset < 0 or size < 0 or offset > len(self.data) - size:
+ raise MetafileMalformedError(
+ f"metafile field exceeds record boundary: offset={self.base_offset + offset}, size={size}"
+ )
+
+ def u8(self, offset: int) -> int:
+ """读取小端无符号 8 位整数。"""
+ self._require(offset, 1)
+ return int(self.data[offset])
+
+ def i16(self, offset: int) -> int:
+ """读取小端有符号 16 位整数。"""
+ self._require(offset, 2)
+ return int(struct.unpack_from("<h", self.data, offset)[0])
+
+ def u16(self, offset: int) -> int:
+ """读取小端无符号 16 位整数。"""
+ self._require(offset, 2)
+ return int(struct.unpack_from("<H", self.data, offset)[0])
+
+ def i32(self, offset: int) -> int:
+ """读取小端有符号 32 位整数。"""
+ self._require(offset, 4)
+ return int(struct.unpack_from("<i", self.data, offset)[0])
+
+ def u32(self, offset: int) -> int:
+ """读取小端无符号 32 位整数。"""
+ self._require(offset, 4)
+ return int(struct.unpack_from("<I", self.data, offset)[0])
+
+ def f32(self, offset: int) -> float:
+ """读取小端 IEEE-754 单精度浮点数。"""
+ self._require(offset, 4)
+ return float(struct.unpack_from("<f", self.data, offset)[0])
+
+ def bytes(self, offset: int, size: int) -> bytes:
+ """返回经过边界校验的不可变字节切片。"""
+ self._require(offset, size)
+ return self.data[offset : offset + size].tobytes()
+
+ def subreader(self, offset: int, size: int) -> BoundedReader:
+ """返回继承绝对偏移信息的有界子读取器。"""
+ self._require(offset, size)
+ return BoundedReader(self.data[offset : offset + size], base_offset=self.base_offset + offset)
+
+ def remaining(self, offset: int) -> int:
+ """返回从指定位置到当前视图末尾的剩余字节数。"""
+ self._require(offset, 0)
+ return len(self.data) - offset
+
+ def __len__(self) -> int:
+ """返回当前视图的总字节数。"""
+ return len(self.data)
+
+
+__all__ = ["BoundedReader"]
diff --git a/mineru/model/flash/office/metafile/geometry.py b/mineru/model/flash/office/metafile/geometry.py
new file mode 100644
index 00000000..df97e501
--- /dev/null
+++ b/mineru/model/flash/office/metafile/geometry.py
@@ -0,0 +1,409 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""WMF/EMF 跨后端复用的路径与几何计算。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from math import atan2, ceil, cos, hypot, pi, sin
+from typing import Iterable
+
+from .limits import MAX_FLATTENED_POINTS
+from .models import GraphicsPath, Matrix, MetafileResourceLimitError, PathSegment, Point, Rect
+
+
+_ELLIPSE_KAPPA = 0.5522847498307936
+_DEFAULT_FLATNESS = 0.25
+_MAX_CUBIC_DEPTH = 12
+
+
+@dataclass(slots=True)
+class FlattenBudget:
+ """累计单次文档渲染产生的折线点数并执行固定预算。"""
+
+ limit: int = MAX_FLATTENED_POINTS
+ used: int = 0
+
+ def charge(self, count: int = 1) -> None:
+ """累计离散点数,超过固定预算时终止渲染。"""
+ self.used += count
+ if self.used > self.limit:
+ raise MetafileResourceLimitError(f"metafile exceeds max_flattened_points={self.limit}")
+
+
+class PathBuilder:
+ """以可变列表构造最终不可变的 GraphicsPath。"""
+
+ def __init__(self) -> None:
+ """创建空路径并清除当前点与子路径起点。"""
+ self._segments: list[PathSegment] = []
+ self.current: Point | None = None
+ self.subpath_start: Point | None = None
+ self._figure_closed = False
+
+ def move_to(self, point: Point) -> None:
+ """移动当前点并开始新的子路径。"""
+ self._segments.append(PathSegment("M", (point,)))
+ self.current = point
+ self.subpath_start = point
+ self._figure_closed = False
+
+ def line_to(self, point: Point) -> None:
+ """从当前点追加直线;空路径会先建立起点。"""
+ if self.current is None:
+ self.move_to(point)
+ return
+ if self._figure_closed:
+ self.move_to(self.current)
+ self._segments.append(PathSegment("L", (point,)))
+ self.current = point
+
+ def cubic_to(self, control1: Point, control2: Point, endpoint: Point) -> None:
+ """从当前点追加三次贝塞尔曲线。"""
+ if self.current is None:
+ self.move_to(endpoint)
+ return
+ if self._figure_closed:
+ self.move_to(self.current)
+ self._segments.append(PathSegment("C", (control1, control2, endpoint)))
+ self.current = endpoint
+
+ def close(self) -> None:
+ """闭合当前子路径并把当前点恢复到其起点。"""
+ if self.current is None or self.subpath_start is None or self._figure_closed:
+ return
+ self._segments.append(PathSegment("Z"))
+ self.current = self.subpath_start
+ self._figure_closed = True
+
+ @property
+ def figure_open(self) -> bool:
+ """返回当前是否存在可由 CloseFigure 闭合的开放 figure。"""
+ return self.current is not None and self.subpath_start is not None and not self._figure_closed
+
+ def extend(self, path: GraphicsPath) -> None:
+ """按顺序追加另一条路径的全部片段。"""
+ for segment in path.segments:
+ if segment.verb == "M":
+ self.move_to(segment.points[0])
+ elif segment.verb == "L":
+ self.line_to(segment.points[0])
+ elif segment.verb == "C":
+ self.cubic_to(*segment.points)
+ elif segment.verb == "Z":
+ self.close()
+
+ def build(self) -> GraphicsPath:
+ """冻结并返回当前路径片段。"""
+ return GraphicsPath(tuple(self._segments))
+
+ def clear(self) -> None:
+ """清空全部路径片段与当前点。"""
+ self._segments.clear()
+ self.current = None
+ self.subpath_start = None
+ self._figure_closed = False
+
+
+def colorref_to_rgb(value: int) -> tuple[int, int, int]:
+ """把 GDI COLORREF 的 BGR 字节序转换为 RGB。"""
+ return value & 0xFF, (value >> 8) & 0xFF, (value >> 16) & 0xFF
+
+
+def transform_path(path: GraphicsPath, matrix: Matrix) -> GraphicsPath:
+ """把路径中的所有控制点应用到同一仿射变换。"""
+ segments: list[PathSegment] = []
+ for segment in path.segments:
+ segments.append(PathSegment(segment.verb, tuple(matrix.transform_point(point) for point in segment.points)))
+ return GraphicsPath(tuple(segments))
+
+
+def rectangle_path(rect: Rect) -> GraphicsPath:
+ """把矩形转换为闭合路径。"""
+ normalized = rect.normalized()
+ builder = PathBuilder()
+ builder.move_to((normalized.left, normalized.top))
+ builder.line_to((normalized.right, normalized.top))
+ builder.line_to((normalized.right, normalized.bottom))
+ builder.line_to((normalized.left, normalized.bottom))
+ builder.close()
+ return builder.build()
+
+
+def round_rectangle_path(rect: Rect, radius_x: float, radius_y: float) -> GraphicsPath:
+ """把圆角矩形转换为包含三次曲线的闭合路径。"""
+ normalized = rect.normalized()
+ radius_x = min(abs(radius_x), abs(normalized.width) / 2.0)
+ radius_y = min(abs(radius_y), abs(normalized.height) / 2.0)
+ if radius_x <= 0.0 or radius_y <= 0.0:
+ return rectangle_path(normalized)
+ kx = radius_x * _ELLIPSE_KAPPA
+ ky = radius_y * _ELLIPSE_KAPPA
+ left, top, right, bottom = normalized.left, normalized.top, normalized.right, normalized.bottom
+ builder = PathBuilder()
+ builder.move_to((left + radius_x, top))
+ builder.line_to((right - radius_x, top))
+ builder.cubic_to((right - radius_x + kx, top), (right, top + radius_y - ky), (right, top + radius_y))
+ builder.line_to((right, bottom - radius_y))
+ builder.cubic_to((right, bottom - radius_y + ky), (right - radius_x + kx, bottom), (right - radius_x, bottom))
+ builder.line_to((left + radius_x, bottom))
+ builder.cubic_to((left + radius_x - kx, bottom), (left, bottom - radius_y + ky), (left, bottom - radius_y))
+ builder.line_to((left, top + radius_y))
+ builder.cubic_to((left, top + radius_y - ky), (left + radius_x - kx, top), (left + radius_x, top))
+ builder.close()
+ return builder.build()
+
+
+def ellipse_path(rect: Rect) -> GraphicsPath:
+ """把椭圆转换为四段三次贝塞尔曲线。"""
+ normalized = rect.normalized()
+ center_x = (normalized.left + normalized.right) / 2.0
+ center_y = (normalized.top + normalized.bottom) / 2.0
+ radius_x = normalized.width / 2.0
+ radius_y = normalized.height / 2.0
+ if radius_x <= 0.0 or radius_y <= 0.0:
+ return GraphicsPath(())
+ kx = radius_x * _ELLIPSE_KAPPA
+ ky = radius_y * _ELLIPSE_KAPPA
+ builder = PathBuilder()
+ builder.move_to((center_x + radius_x, center_y))
+ builder.cubic_to(
+ (center_x + radius_x, center_y + ky),
+ (center_x + kx, center_y + radius_y),
+ (center_x, center_y + radius_y),
+ )
+ builder.cubic_to(
+ (center_x - kx, center_y + radius_y),
+ (center_x - radius_x, center_y + ky),
+ (center_x - radius_x, center_y),
+ )
+ builder.cubic_to(
+ (center_x - radius_x, center_y - ky),
+ (center_x - kx, center_y - radius_y),
+ (center_x, center_y - radius_y),
+ )
+ builder.cubic_to(
+ (center_x + kx, center_y - radius_y),
+ (center_x + radius_x, center_y - ky),
+ (center_x + radius_x, center_y),
+ )
+ builder.close()
+ return builder.build()
+
+
+def arc_path(
+ rect: Rect,
+ start: Point,
+ end: Point,
+ *,
+ direction: int,
+ close_mode: str = "open",
+) -> GraphicsPath:
+ """按 GDI 椭圆边界与方向生成 arc、pie 或 chord 路径。"""
+ normalized = rect.normalized()
+ center_x = (normalized.left + normalized.right) / 2.0
+ center_y = (normalized.top + normalized.bottom) / 2.0
+ radius_x = normalized.width / 2.0
+ radius_y = normalized.height / 2.0
+ if radius_x <= 0.0 or radius_y <= 0.0:
+ return GraphicsPath(())
+ start_angle = atan2((start[1] - center_y) / radius_y, (start[0] - center_x) / radius_x)
+ end_angle = atan2((end[1] - center_y) / radius_y, (end[0] - center_x) / radius_x)
+ if direction == 1:
+ while end_angle >= start_angle:
+ end_angle -= 2.0 * pi
+ else:
+ while end_angle <= start_angle:
+ end_angle += 2.0 * pi
+ sweep = end_angle - start_angle
+ steps = max(4, min(256, int(ceil(abs(sweep) / (pi / 24.0)))))
+ points = [
+ (
+ center_x + radius_x * cos(start_angle + sweep * index / steps),
+ center_y + radius_y * sin(start_angle + sweep * index / steps),
+ )
+ for index in range(steps + 1)
+ ]
+ builder = PathBuilder()
+ if close_mode == "pie":
+ builder.move_to((center_x, center_y))
+ builder.line_to(points[0])
+ else:
+ builder.move_to(points[0])
+ for point in points[1:]:
+ builder.line_to(point)
+ if close_mode in {"pie", "chord"}:
+ builder.close()
+ return builder.build()
+
+
+def path_bounds(path: GraphicsPath) -> Rect | None:
+ """返回包含路径全部端点和控制点的保守包围盒。"""
+ points = [point for segment in path.segments for point in segment.points]
+ if not points:
+ return None
+ xs = [point[0] for point in points]
+ ys = [point[1] for point in points]
+ return Rect(min(xs), min(ys), max(xs), max(ys))
+
+
+def close_open_subpaths(path: GraphicsPath) -> GraphicsPath:
+ """为 StrokeAndFillPath 显式闭合路径中的全部开放 figure。"""
+ segments: list[PathSegment] = []
+ figure_open = False
+ for segment in path.segments:
+ if segment.verb == "M":
+ if figure_open:
+ segments.append(PathSegment("Z"))
+ figure_open = True
+ elif segment.verb == "Z":
+ figure_open = False
+ segments.append(segment)
+ if figure_open:
+ segments.append(PathSegment("Z"))
+ return GraphicsPath(tuple(segments))
+
+
+def union_rectangles(rectangles: Iterable[Rect | None]) -> Rect | None:
+ """合并所有非空矩形并返回整体包围盒。"""
+ present = [rectangle.normalized() for rectangle in rectangles if rectangle is not None]
+ if not present:
+ return None
+ return Rect(
+ min(rectangle.left for rectangle in present),
+ min(rectangle.top for rectangle in present),
+ max(rectangle.right for rectangle in present),
+ max(rectangle.bottom for rectangle in present),
+ )
+
+
+def _point_line_distance(point: Point, start: Point, end: Point) -> float:
+ """返回点到无限直线的距离,退化直线按点距处理。"""
+ delta_x = end[0] - start[0]
+ delta_y = end[1] - start[1]
+ length = hypot(delta_x, delta_y)
+ if length <= 1e-12:
+ return hypot(point[0] - start[0], point[1] - start[1])
+ return abs(delta_y * point[0] - delta_x * point[1] + end[0] * start[1] - end[1] * start[0]) / length
+
+
+def _split_cubic(
+ start: Point,
+ control1: Point,
+ control2: Point,
+ endpoint: Point,
+) -> tuple[tuple[Point, ...], tuple[Point, ...]]:
+ """按 de Casteljau 中点算法把三次贝塞尔曲线二分。"""
+ first = ((start[0] + control1[0]) / 2.0, (start[1] + control1[1]) / 2.0)
+ second = ((control1[0] + control2[0]) / 2.0, (control1[1] + control2[1]) / 2.0)
+ third = ((control2[0] + endpoint[0]) / 2.0, (control2[1] + endpoint[1]) / 2.0)
+ fourth = ((first[0] + second[0]) / 2.0, (first[1] + second[1]) / 2.0)
+ fifth = ((second[0] + third[0]) / 2.0, (second[1] + third[1]) / 2.0)
+ midpoint = ((fourth[0] + fifth[0]) / 2.0, (fourth[1] + fifth[1]) / 2.0)
+ return (start, first, fourth, midpoint), (midpoint, fifth, third, endpoint)
+
+
+def _flatten_cubic(
+ start: Point,
+ control1: Point,
+ control2: Point,
+ endpoint: Point,
+ *,
+ flatness: float,
+ max_depth: int,
+ budget: FlattenBudget,
+) -> list[Point]:
+ """按输出空间误差自适应离散单条三次贝塞尔曲线。"""
+ result: list[Point] = []
+ stack: list[tuple[Point, Point, Point, Point, int]] = [(start, control1, control2, endpoint, 0)]
+ while stack:
+ current_start, current_control1, current_control2, current_endpoint, depth = stack.pop()
+ error = max(
+ _point_line_distance(current_control1, current_start, current_endpoint),
+ _point_line_distance(current_control2, current_start, current_endpoint),
+ )
+ if error <= flatness or depth >= max_depth:
+ budget.charge()
+ result.append(current_endpoint)
+ continue
+ left, right = _split_cubic(current_start, current_control1, current_control2, current_endpoint)
+ stack.append((*right, depth + 1))
+ stack.append((*left, depth + 1))
+ return result
+
+
+def flatten_path(
+ path: GraphicsPath,
+ *,
+ flatness: float = _DEFAULT_FLATNESS,
+ max_depth: int = _MAX_CUBIC_DEPTH,
+ budget: FlattenBudget | None = None,
+) -> list[tuple[list[Point], bool]]:
+ """把曲线路径按输出像素误差离散成 Pillow 可绘制的折线子路径。"""
+ if flatness <= 0.0:
+ raise ValueError("flatness must be positive")
+ if max_depth < 0:
+ raise ValueError("max_depth must not be negative")
+ active_budget = budget or FlattenBudget()
+ subpaths: list[tuple[list[Point], bool]] = []
+ current_points: list[Point] = []
+ current_point: Point | None = None
+ closed = False
+ for segment in path.segments:
+ if segment.verb == "M":
+ if current_points:
+ subpaths.append((current_points, closed))
+ current_points = [segment.points[0]]
+ active_budget.charge()
+ current_point = segment.points[0]
+ closed = False
+ elif segment.verb == "L":
+ if current_point is None:
+ current_points = [segment.points[0]]
+ else:
+ current_points.append(segment.points[0])
+ active_budget.charge()
+ current_point = segment.points[0]
+ elif segment.verb == "C" and current_point is not None:
+ control1, control2, endpoint = segment.points
+ current_points.extend(
+ _flatten_cubic(
+ current_point,
+ control1,
+ control2,
+ endpoint,
+ flatness=flatness,
+ max_depth=max_depth,
+ budget=active_budget,
+ )
+ )
+ current_point = endpoint
+ elif segment.verb == "Z":
+ closed = True
+ if current_points and current_points[-1] != current_points[0]:
+ current_points.append(current_points[0])
+ active_budget.charge()
+ if current_points:
+ subpaths.append((current_points, closed))
+ return subpaths
+
+
+def vector_length(vector: Point) -> float:
+ """返回二维向量的欧氏长度。"""
+ return hypot(vector[0], vector[1])
+
+
+__all__ = [
+ "FlattenBudget",
+ "PathBuilder",
+ "arc_path",
+ "close_open_subpaths",
+ "colorref_to_rgb",
+ "ellipse_path",
+ "flatten_path",
+ "path_bounds",
+ "rectangle_path",
+ "round_rectangle_path",
+ "transform_path",
+ "union_rectangles",
+ "vector_length",
+]
diff --git a/mineru/model/flash/office/metafile/limits.py b/mineru/model/flash/office/metafile/limits.py
new file mode 100644
index 00000000..b145893b
--- /dev/null
+++ b/mineru/model/flash/office/metafile/limits.py
@@ -0,0 +1,36 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""WMF/EMF 解析与渲染的固定安全预算。"""
+
+from typing import Final
+
+
+MAX_METAFILE_BYTES: Final = 128 * 1024 * 1024
+MAX_RECORDS: Final = 1_000_000
+MAX_POINTS_PER_RECORD: Final = 1_000_000
+MAX_TOTAL_POINTS: Final = 5_000_000
+MAX_COMMANDS: Final = 100_000
+MAX_OBJECTS: Final = 65_536
+MAX_STATE_DEPTH: Final = 64
+MAX_DIAGNOSTICS: Final = 256
+MAX_CANVAS_DIMENSION: Final = 8_192
+MAX_CANVAS_PIXELS: Final = 16_000_000
+MAX_RENDER_WORK_PIXELS: Final = 512_000_000
+MAX_EMBEDDED_BITMAP_BYTES: Final = 128 * 1024 * 1024
+MAX_FLATTENED_POINTS: Final = 5_000_000
+
+
+__all__ = [
+ "MAX_CANVAS_DIMENSION",
+ "MAX_CANVAS_PIXELS",
+ "MAX_COMMANDS",
+ "MAX_DIAGNOSTICS",
+ "MAX_EMBEDDED_BITMAP_BYTES",
+ "MAX_FLATTENED_POINTS",
+ "MAX_METAFILE_BYTES",
+ "MAX_OBJECTS",
+ "MAX_POINTS_PER_RECORD",
+ "MAX_RECORDS",
+ "MAX_RENDER_WORK_PIXELS",
+ "MAX_STATE_DEPTH",
+ "MAX_TOTAL_POINTS",
+]
diff --git a/mineru/model/flash/office/metafile/models.py b/mineru/model/flash/office/metafile/models.py
new file mode 100644
index 00000000..15ca1d84
--- /dev/null
+++ b/mineru/model/flash/office/metafile/models.py
@@ -0,0 +1,341 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""WMF/EMF 回放状态、绘图 IR 与结果模型。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal, TypeAlias
+
+
+MetafileSourceFormat: TypeAlias = Literal["wmf", "emf"]
+MetafileOutputFormat: TypeAlias = Literal["png", "jpeg", "svg"]
+EmfPlusMode: TypeAlias = Literal["none", "dual", "only"]
+DiagnosticLevel: TypeAlias = Literal["info", "warning", "error"]
+Point: TypeAlias = tuple[float, float]
+
+
+class MetafileError(ValueError):
+ """WMF/EMF 渲染错误基类,并携带稳定错误码。"""
+
+ code = "metafile_error"
+
+
+class MetafileMalformedError(MetafileError):
+ """WMF/EMF 头部或记录流不满足格式边界。"""
+
+ code = "malformed"
+
+
+class MetafileResourceLimitError(MetafileError):
+ """WMF/EMF 输入或输出超过固定安全预算。"""
+
+ code = "resource_limit"
+
+
+class MetafileUnsupportedError(MetafileError):
+ """输入使用无法安全降级的 WMF/EMF 能力。"""
+
+ code = "unsupported"
+
+
+@dataclass(frozen=True, slots=True)
+class MetafileDiagnostic:
+ """记录单个可定位、可聚合的 WMF/EMF 渲染诊断。"""
+
+ code: str
+ level: DiagnosticLevel
+ message: str
+ record_type: int | None = None
+ record_index: int | None = None
+ offset: int | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class Color:
+ """保存标准 RGBA 颜色分量。"""
+
+ red: int
+ green: int
+ blue: int
+ alpha: int = 255
+
+ def rgba(self) -> tuple[int, int, int, int]:
+ """返回 Pillow 可直接消费的 RGBA 元组。"""
+ return self.red, self.green, self.blue, self.alpha
+
+ def svg(self) -> str:
+ """返回不含透明度的 SVG 十六进制颜色。"""
+ return f"#{self.red:02x}{self.green:02x}{self.blue:02x}"
+
+
+BLACK = Color(0, 0, 0)
+WHITE = Color(255, 255, 255)
+TRANSPARENT = Color(0, 0, 0, 0)
+
+
+@dataclass(frozen=True, slots=True)
+class Rect:
+ """保存规范化前后均可使用的浮点矩形。"""
+
+ left: float
+ top: float
+ right: float
+ bottom: float
+
+ @property
+ def width(self) -> float:
+ """返回矩形的有符号宽度。"""
+ return self.right - self.left
+
+ @property
+ def height(self) -> float:
+ """返回矩形的有符号高度。"""
+ return self.bottom - self.top
+
+ def normalized(self) -> Rect:
+ """返回左右、上下均按升序排列的矩形。"""
+ return Rect(
+ min(self.left, self.right),
+ min(self.top, self.bottom),
+ max(self.left, self.right),
+ max(self.top, self.bottom),
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class Matrix:
+ """保存二维仿射变换,采用 SVG/Pillow 常用的六参数表示。"""
+
+ a: float = 1.0
+ b: float = 0.0
+ c: float = 0.0
+ d: float = 1.0
+ e: float = 0.0
+ f: float = 0.0
+
+ def transform_point(self, point: Point) -> Point:
+ """把单点应用到当前仿射变换。"""
+ x, y = point
+ return self.a * x + self.c * y + self.e, self.b * x + self.d * y + self.f
+
+ def transform_vector(self, vector: Point) -> Point:
+ """只应用线性部分,避免平移污染长度和方向。"""
+ x, y = vector
+ return self.a * x + self.c * y, self.b * x + self.d * y
+
+ def then(self, following: Matrix) -> Matrix:
+ """返回先应用当前矩阵、再应用 following 的组合矩阵。"""
+ return Matrix(
+ a=following.a * self.a + following.c * self.b,
+ b=following.b * self.a + following.d * self.b,
+ c=following.a * self.c + following.c * self.d,
+ d=following.b * self.c + following.d * self.d,
+ e=following.a * self.e + following.c * self.f + following.e,
+ f=following.b * self.e + following.d * self.f + following.f,
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class Pen:
+ """保存已经解析的 GDI 画笔。"""
+
+ color: Color = BLACK
+ width: float = 1.0
+ style: int = 0
+ cosmetic: bool = True
+ null: bool = False
+ cap: Literal["round", "square", "flat"] = "round"
+ join: Literal["round", "bevel", "miter"] = "round"
+ dashes: tuple[float, ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class Brush:
+ """保存已经解析的 GDI 画刷。"""
+
+ kind: Literal["solid", "null", "hatch", "pattern"] = "solid"
+ color: Color = WHITE
+ hatch: int = 0
+ pattern: bytes | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class Font:
+ """保存 GDI LOGFONT 中与跨平台绘制有关的字段。"""
+
+ face_name: str = "Arial"
+ height: float = -12.0
+ width: float = 0.0
+ weight: int = 400
+ italic: bool = False
+ underline: bool = False
+ strikeout: bool = False
+ charset: int = 1
+ escapement: float = 0.0
+ orientation: float = 0.0
+
+
+@dataclass(frozen=True, slots=True)
+class PathSegment:
+ """保存单个 move/line/cubic/close 路径片段。"""
+
+ verb: Literal["M", "L", "C", "Z"]
+ points: tuple[Point, ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class GraphicsPath:
+ """保存不可变的跨后端绘图路径。"""
+
+ segments: tuple[PathSegment, ...]
+
+
+@dataclass(frozen=True, slots=True)
+class ClipOperation:
+ """保存按 GDI 顺序应用的单次裁剪区域操作。"""
+
+ path: GraphicsPath
+ mode: Literal["and", "or", "xor", "diff", "copy"]
+ fill_rule: Literal["evenodd", "nonzero"] = "evenodd"
+
+
+ClipStack: TypeAlias = tuple[ClipOperation, ...]
+
+
+@dataclass(frozen=True, slots=True)
+class DrawPathCommand:
+ """保存一次路径填充和描边操作。"""
+
+ path: GraphicsPath
+ pen: Pen
+ brush: Brush
+ stroke: bool
+ fill: bool
+ fill_rule: Literal["evenodd", "nonzero"]
+ clip: ClipStack
+ rop2: int
+ miter_limit: float = 10.0
+
+
+@dataclass(frozen=True, slots=True)
+class DrawTextCommand:
+ """保存一次 GDI 文字输出及其显式字符位置。"""
+
+ text: str
+ origin: Point
+ positions: tuple[Point, ...]
+ font: Font
+ font_height: float
+ rotation: float
+ text_align: int
+ color: Color
+ background_color: Color
+ opaque: bool
+ bounds: Rect | None
+ clip: ClipStack
+
+
+@dataclass(frozen=True, slots=True)
+class DrawImageCommand:
+ """保存一次 DIB/位图绘制及其 GDI 合成参数。"""
+
+ dib_header: bytes
+ bits: bytes
+ destination: tuple[Point, Point, Point, Point]
+ source: Rect | None
+ rop: int
+ stretch_mode: int = 3
+ constant_alpha: int = 255
+ use_source_alpha: bool = False
+ clip: ClipStack = ()
+
+
+DrawCommand: TypeAlias = DrawPathCommand | DrawTextCommand | DrawImageCommand
+
+
+@dataclass(frozen=True, slots=True)
+class MetafileDocument:
+ """保存解析完成、可被多个后端消费的统一图元文档。"""
+
+ source_format: MetafileSourceFormat
+ emfplus_mode: EmfPlusMode
+ bounds: Rect
+ width: int
+ height: int
+ commands: tuple[DrawCommand, ...]
+ diagnostics: tuple[MetafileDiagnostic, ...]
+ partial: bool
+
+
+@dataclass(frozen=True, slots=True)
+class MetafileRenderResult:
+ """保存最终图片字节、尺寸与解析诊断。"""
+
+ data: bytes
+ output_format: MetafileOutputFormat
+ media_type: str
+ width: int
+ height: int
+ source_format: MetafileSourceFormat
+ emfplus_mode: EmfPlusMode
+ partial: bool
+ diagnostics: tuple[MetafileDiagnostic, ...]
+
+
+@dataclass(slots=True)
+class GdiState:
+ """保存 WMF/EMF 当前 playback device context。"""
+
+ pen: Pen = field(default_factory=Pen)
+ brush: Brush = field(default_factory=Brush)
+ font: Font = field(default_factory=Font)
+ text_color: Color = BLACK
+ background_color: Color = WHITE
+ background_mode: int = 2
+ text_align: int = 0
+ map_mode: int = 1
+ window_origin: Point = (0.0, 0.0)
+ window_extent: Point = (1.0, 1.0)
+ viewport_origin: Point = (0.0, 0.0)
+ viewport_extent: Point = (1.0, 1.0)
+ world_transform: Matrix = field(default_factory=Matrix)
+ current_position: Point = (0.0, 0.0)
+ polygon_fill_mode: int = 1
+ rop2: int = 13
+ stretch_mode: int = 1
+ arc_direction: int = 2
+ miter_limit: float = 10.0
+ brush_origin: Point = (0.0, 0.0)
+ clip: ClipStack = ()
+ device_pixels_per_mm: Point = (96.0 / 25.4, 96.0 / 25.4)
+
+
+__all__ = [
+ "BLACK",
+ "WHITE",
+ "Brush",
+ "ClipOperation",
+ "Color",
+ "DrawCommand",
+ "DrawImageCommand",
+ "DrawPathCommand",
+ "DrawTextCommand",
+ "EmfPlusMode",
+ "Font",
+ "GdiState",
+ "GraphicsPath",
+ "Matrix",
+ "MetafileDiagnostic",
+ "MetafileDocument",
+ "MetafileError",
+ "MetafileMalformedError",
+ "MetafileOutputFormat",
+ "MetafileRenderResult",
+ "MetafileResourceLimitError",
+ "MetafileSourceFormat",
+ "MetafileUnsupportedError",
+ "PathSegment",
+ "Pen",
+ "Point",
+ "Rect",
+]
diff --git a/mineru/model/flash/office/metafile/parser.py b/mineru/model/flash/office/metafile/parser.py
new file mode 100644
index 00000000..300eec7d
--- /dev/null
+++ b/mineru/model/flash/office/metafile/parser.py
@@ -0,0 +1,1959 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""WMF/EMF 有界解析与 GDI 状态回放。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+from math import atan2, degrees, isfinite
+import struct
+
+from .binary import BoundedReader
+from .geometry import (
+ PathBuilder,
+ arc_path,
+ close_open_subpaths,
+ colorref_to_rgb,
+ ellipse_path,
+ path_bounds,
+ rectangle_path,
+ round_rectangle_path,
+ transform_path,
+ union_rectangles,
+ vector_length,
+)
+from .limits import (
+ MAX_CANVAS_DIMENSION,
+ MAX_CANVAS_PIXELS,
+ MAX_COMMANDS,
+ MAX_DIAGNOSTICS,
+ MAX_EMBEDDED_BITMAP_BYTES,
+ MAX_METAFILE_BYTES,
+ MAX_OBJECTS,
+ MAX_POINTS_PER_RECORD,
+ MAX_RECORDS,
+ MAX_STATE_DEPTH,
+ MAX_TOTAL_POINTS,
+)
+from .models import (
+ BLACK,
+ WHITE,
+ Brush,
+ ClipOperation,
+ Color,
+ DrawCommand,
+ DrawImageCommand,
+ DrawPathCommand,
+ DrawTextCommand,
+ EmfPlusMode,
+ Font,
+ GdiState,
+ GraphicsPath,
+ Matrix,
+ MetafileDiagnostic,
+ MetafileDocument,
+ MetafileMalformedError,
+ MetafileResourceLimitError,
+ MetafileSourceFormat,
+ MetafileUnsupportedError,
+ Pen,
+ Point,
+ Rect,
+)
+
+
+_EMF_SIGNATURE = 0x464D4520
+_EMFPLUS_SIGNATURE = 0x2B464D45
+_PLACEABLE_WMF_KEY = 0x9AC6CDD7
+
+_RGN_AND = 1
+_RGN_OR = 2
+_RGN_XOR = 3
+_RGN_DIFF = 4
+_RGN_COPY = 5
+
+_ETO_OPAQUE = 0x0002
+_ETO_CLIPPED = 0x0004
+_ETO_GLYPH_INDEX = 0x0010
+_ETO_PDY = 0x2000
+_TA_UPDATECP = 0x0001
+_TA_RIGHT = 0x0002
+_TA_CENTER = 0x0006
+
+_SRCCOPY = 0x00CC0020
+_SUPPORTED_ROP3 = {
+ _SRCCOPY,
+ 0x008800C6,
+ 0x00EE0086,
+ 0x00660046,
+ 0x00550009,
+ 0x00000042,
+ 0x00FF0062,
+}
+
+
+@dataclass(frozen=True, slots=True)
+class _HeaderInfo:
+ """保存格式头部解析出的记录边界、坐标边界和输出尺寸。"""
+
+ source_format: MetafileSourceFormat
+ record_start: int
+ record_end: int
+ bounds: Rect | None
+ pixel_size: tuple[int, int] | None
+ emfplus_mode: EmfPlusMode = "none"
+ device_pixels_per_mm: Point = (96.0 / 25.4, 96.0 / 25.4)
+ wmf_object_count: int = 0
+
+
+class _DiagnosticSink:
+ """收集有界诊断并聚合超出预算的重复项目。"""
+
+ def __init__(self) -> None:
+ """创建空诊断列表和截断计数器。"""
+ self.items: list[MetafileDiagnostic] = []
+ self.omitted = 0
+
+ def add(
+ self,
+ code: str,
+ level: str,
+ message: str,
+ *,
+ record_type: int | None = None,
+ record_index: int | None = None,
+ offset: int | None = None,
+ ) -> None:
+ """在预算内追加诊断,超出时只累计省略数量。"""
+ if len(self.items) >= MAX_DIAGNOSTICS:
+ self.omitted += 1
+ return
+ normalized_level = level if level in {"info", "warning", "error"} else "warning"
+ self.items.append(
+ MetafileDiagnostic(
+ code=code,
+ level=normalized_level, # type: ignore[arg-type]
+ message=message,
+ record_type=record_type,
+ record_index=record_index,
+ offset=offset,
+ )
+ )
+
+ def freeze(self) -> tuple[MetafileDiagnostic, ...]:
+ """冻结诊断,并在需要时追加一条截断摘要。"""
+ if self.omitted:
+ self.items.append(
+ MetafileDiagnostic(
+ code="diagnostics_truncated",
+ level="warning",
+ message=f"omitted {self.omitted} additional metafile diagnostics",
+ )
+ )
+ return tuple(self.items)
+
+
+class _Playback:
+ """把 WMF/EMF records 回放为统一绘图命令。"""
+
+ def __init__(self, header: _HeaderInfo, diagnostics: _DiagnosticSink) -> None:
+ """初始化 GDI 状态、对象表、路径与资源计数。"""
+ self.header = header
+ self.diagnostics = diagnostics
+ self.state = GdiState(device_pixels_per_mm=header.device_pixels_per_mm)
+ self.state_stack: list[GdiState] = []
+ self.emf_objects: dict[int, Pen | Brush | Font] = {}
+ self.wmf_objects: list[Pen | Brush | Font | None] = [None] * min(header.wmf_object_count, MAX_OBJECTS)
+ self.commands: list[DrawCommand] = []
+ self.path_builder = PathBuilder()
+ self.path_active = False
+ self.path_ready = False
+ self.partial = False
+ self.total_points = 0
+ self.record_type: int | None = None
+ self.record_index: int | None = None
+ self.record_offset: int | None = None
+
+ def set_record_context(self, record_type: int, record_index: int, offset: int) -> None:
+ """更新后续诊断所使用的当前记录定位信息。"""
+ self.record_type = record_type
+ self.record_index = record_index
+ self.record_offset = offset
+
+ def warn(self, code: str, message: str, *, partial: bool = True) -> None:
+ """为当前记录追加警告,并按需标记输出不完整。"""
+ self.partial = self.partial or partial
+ self.diagnostics.add(
+ code,
+ "warning",
+ message,
+ record_type=self.record_type,
+ record_index=self.record_index,
+ offset=self.record_offset,
+ )
+
+ def charge_points(self, count: int) -> None:
+ """累计点数并执行单记录与全文件预算。"""
+ if count < 0 or count > MAX_POINTS_PER_RECORD:
+ raise MetafileResourceLimitError(f"metafile record exceeds max_points_per_record={MAX_POINTS_PER_RECORD}")
+ self.total_points += count
+ if self.total_points > MAX_TOTAL_POINTS:
+ raise MetafileResourceLimitError(f"metafile exceeds max_total_points={MAX_TOTAL_POINTS}")
+
+ def append_command(self, command: DrawCommand) -> None:
+ """在命令预算内追加一条统一绘图命令。"""
+ if len(self.commands) >= MAX_COMMANDS:
+ raise MetafileResourceLimitError(f"metafile exceeds max_commands={MAX_COMMANDS}")
+ self.commands.append(command)
+
+ def copy_state(self) -> GdiState:
+ """复制当前可由 SaveDC/RestoreDC 恢复的 GDI 状态。"""
+ return replace(self.state)
+
+ def save_dc(self) -> None:
+ """把当前 GDI 状态压入有界栈。"""
+ if len(self.state_stack) >= MAX_STATE_DEPTH:
+ raise MetafileResourceLimitError(f"metafile exceeds max_state_depth={MAX_STATE_DEPTH}")
+ self.state_stack.append(self.copy_state())
+
+ def restore_dc(self, level: int) -> None:
+ """按 GDI 相对或绝对层级恢复已保存状态。"""
+ if not self.state_stack:
+ self.warn("restore_dc_underflow", "RestoreDC ignored because the state stack is empty")
+ return
+ if level < 0:
+ target = len(self.state_stack) + level
+ elif level > 0:
+ target = level - 1
+ else:
+ self.warn("restore_dc_zero", "RestoreDC level 0 is invalid")
+ return
+ if target < 0 or target >= len(self.state_stack):
+ self.warn("restore_dc_out_of_range", f"RestoreDC level is out of range: {level}")
+ return
+ self.state = self.state_stack[target]
+ del self.state_stack[target:]
+
+ def _mapping_matrix(self) -> Matrix:
+ """根据 mapping mode、window 和 viewport 计算 page-to-device 变换。"""
+ mode = self.state.map_mode
+ window_x, window_y = self.state.window_origin
+ viewport_x, viewport_y = self.state.viewport_origin
+ if mode in {7, 8}:
+ window_width, window_height = self.state.window_extent
+ viewport_width, viewport_height = self.state.viewport_extent
+ if window_width == 0.0 or window_height == 0.0:
+ self.warn("zero_window_extent", "zero window extent was replaced by identity mapping")
+ scale_x = scale_y = 1.0
+ else:
+ scale_x = viewport_width / window_width
+ scale_y = viewport_height / window_height
+ elif mode == 2:
+ scale_x = self.state.device_pixels_per_mm[0] / 10.0
+ scale_y = -self.state.device_pixels_per_mm[1] / 10.0
+ elif mode == 3:
+ scale_x = self.state.device_pixels_per_mm[0] / 100.0
+ scale_y = -self.state.device_pixels_per_mm[1] / 100.0
+ elif mode == 4:
+ scale_x = self.state.device_pixels_per_mm[0] * 25.4 / 100.0
+ scale_y = -self.state.device_pixels_per_mm[1] * 25.4 / 100.0
+ elif mode == 5:
+ scale_x = self.state.device_pixels_per_mm[0] * 25.4 / 1000.0
+ scale_y = -self.state.device_pixels_per_mm[1] * 25.4 / 1000.0
+ elif mode == 6:
+ scale_x = self.state.device_pixels_per_mm[0] * 25.4 / 1440.0
+ scale_y = -self.state.device_pixels_per_mm[1] * 25.4 / 1440.0
+ else:
+ scale_x = scale_y = 1.0
+ return Matrix(
+ a=scale_x,
+ d=scale_y,
+ e=viewport_x - window_x * scale_x,
+ f=viewport_y - window_y * scale_y,
+ )
+
+ def logical_matrix(self) -> Matrix:
+ """返回 world-to-page 与 page-to-device 的组合变换。"""
+ return self.state.world_transform.then(self._mapping_matrix())
+
+ def map_point(self, point: Point) -> Point:
+ """把 GDI 逻辑点转换为统一 device 坐标。"""
+ mapped = self.logical_matrix().transform_point(point)
+ if not all(isfinite(value) and abs(value) <= 1e12 for value in mapped):
+ raise MetafileResourceLimitError("metafile coordinate is non-finite or unreasonably large")
+ return mapped
+
+ def map_vector(self, vector: Point) -> Point:
+ """把不含平移的 GDI 逻辑向量转换为 device 向量。"""
+ mapped = self.logical_matrix().transform_vector(vector)
+ if not all(isfinite(value) and abs(value) <= 1e12 for value in mapped):
+ raise MetafileResourceLimitError("metafile vector is non-finite or unreasonably large")
+ return mapped
+
+ def resolved_pen(self) -> Pen:
+ """把当前画笔宽度解析为 device 单位并保留 cosmetic 语义。"""
+ pen = self.state.pen
+ if pen.null:
+ return pen
+ if pen.cosmetic:
+ return replace(pen, width=max(1.0, pen.width))
+ width = vector_length(self.map_vector((pen.width or 1.0, 0.0)))
+ return replace(pen, width=max(width, 1.0))
+
+ def emit_path(self, path: GraphicsPath, *, stroke: bool, fill: bool) -> None:
+ """把路径追加到当前 path bracket 或直接生成绘图命令。"""
+ if self.path_active:
+ self.path_builder.extend(path)
+ return
+ if not path.segments:
+ return
+ self.append_command(
+ DrawPathCommand(
+ path=path,
+ pen=self.resolved_pen(),
+ brush=self.state.brush,
+ stroke=stroke and not self.state.pen.null,
+ fill=fill and self.state.brush.kind != "null",
+ fill_rule="evenodd" if self.state.polygon_fill_mode == 1 else "nonzero",
+ clip=self.state.clip,
+ rop2=self.state.rop2,
+ miter_limit=self.state.miter_limit,
+ )
+ )
+
+ def emit_logical_path(self, path: GraphicsPath, *, stroke: bool, fill: bool) -> None:
+ """把逻辑坐标路径变换后交给统一路径输出。"""
+ self.emit_path(transform_path(path, self.logical_matrix()), stroke=stroke, fill=fill)
+
+ def move_to(self, point: Point) -> None:
+ """更新 GDI current position,并在活动 path 中开始新 figure。"""
+ self.state.current_position = point
+ if self.path_active:
+ self.path_builder.move_to(self.map_point(point))
+
+ def _ensure_active_path_current(self) -> None:
+ """保证活动 path 的下一条 To 记录从 GDI current position 起笔。"""
+ mapped = self.map_point(self.state.current_position)
+ if self.path_builder.current != mapped:
+ self.path_builder.move_to(mapped)
+
+ def line_to(self, endpoint: Point) -> None:
+ """按 LineTo 语义追加直线并更新 GDI current position。"""
+ if self.path_active:
+ self._ensure_active_path_current()
+ self.path_builder.line_to(self.map_point(endpoint))
+ else:
+ self.emit_path(
+ _path_from_device_points(
+ [self.map_point(self.state.current_position), self.map_point(endpoint)],
+ close=False,
+ ),
+ stroke=True,
+ fill=False,
+ )
+ self.state.current_position = endpoint
+
+ def polyline_to(self, points: list[Point]) -> None:
+ """按 PolylineTo 语义连续追加折线并更新 GDI current position。"""
+ if not points:
+ return
+ if self.path_active:
+ self._ensure_active_path_current()
+ for point in points:
+ self.path_builder.line_to(self.map_point(point))
+ else:
+ mapped = [self.map_point(self.state.current_position), *(self.map_point(point) for point in points)]
+ self.emit_path(_path_from_device_points(mapped, close=False), stroke=True, fill=False)
+ self.state.current_position = points[-1]
+
+ def polybezier_to(self, points: list[Point]) -> None:
+ """按 PolyBezierTo 语义连续追加三次曲线并更新 GDI current position。"""
+ if not points:
+ return
+ remaining = points
+ if len(remaining) % 3:
+ self.warn("invalid_bezier_points", "PolyBezierTo point count is not a multiple of three")
+ remaining = remaining[: len(remaining) - len(remaining) % 3]
+ if not remaining:
+ return
+ builder = self.path_builder if self.path_active else PathBuilder()
+ if self.path_active:
+ self._ensure_active_path_current()
+ else:
+ builder.move_to(self.map_point(self.state.current_position))
+ for index in range(0, len(remaining), 3):
+ builder.cubic_to(
+ self.map_point(remaining[index]),
+ self.map_point(remaining[index + 1]),
+ self.map_point(remaining[index + 2]),
+ )
+ if not self.path_active:
+ self.emit_path(builder.build(), stroke=True, fill=False)
+ self.state.current_position = remaining[-1]
+
+ def begin_path(self) -> None:
+ """开始新的 GDI path bracket 并清除旧路径。"""
+ if self.path_active:
+ self.warn("begin_path_while_active", "BeginPath replaced an already active path bracket")
+ self.path_builder.clear()
+ self.path_active = True
+ self.path_ready = False
+
+ def end_path(self) -> None:
+ """结束 path bracket 并保留路径供后续 fill/stroke/clip。"""
+ if not self.path_active:
+ self.warn("end_path_without_begin", "EndPath ignored without a matching BeginPath")
+ return
+ self.path_active = False
+ self.path_ready = True
+
+ def consume_path(self) -> GraphicsPath:
+ """返回并清除已经结束的当前路径。"""
+ if not self.path_ready:
+ self.warn("path_not_ready", "path operation ignored because no completed path exists")
+ return GraphicsPath(())
+ path = self.path_builder.build()
+ self.path_builder.clear()
+ self.path_ready = False
+ return path
+
+ def add_clip(self, path: GraphicsPath, mode: int) -> None:
+ """把 GDI region combine mode 转换为不可变裁剪操作。"""
+ mode_name = _clip_mode_name(mode)
+ if mode_name is None:
+ self.warn("unsupported_clip_mode", f"unsupported clip combine mode: {mode}")
+ return
+ operation = ClipOperation(
+ path=path,
+ mode=mode_name,
+ fill_rule="evenodd" if self.state.polygon_fill_mode == 1 else "nonzero",
+ )
+ if mode == _RGN_COPY:
+ self.state.clip = (operation,)
+ else:
+ self.state.clip = (*self.state.clip, operation)
+
+ def reset_clip(self) -> None:
+ """恢复为没有额外裁剪区域的初始状态。"""
+ self.state.clip = ()
+
+ def create_wmf_object(self, value: Pen | Brush | Font) -> None:
+ """按 WMF 首个空槽规则登记图形对象。"""
+ for index, existing in enumerate(self.wmf_objects):
+ if existing is None:
+ self.wmf_objects[index] = value
+ return
+ if len(self.wmf_objects) >= MAX_OBJECTS:
+ raise MetafileResourceLimitError(f"WMF object table exceeds max_objects={MAX_OBJECTS}")
+ self.wmf_objects.append(value)
+
+ def select_object(self, value: Pen | Brush | Font) -> None:
+ """按对象实际类型更新当前选中画笔、画刷或字体。"""
+ if isinstance(value, Pen):
+ self.state.pen = value
+ elif isinstance(value, Brush):
+ self.state.brush = value
+ else:
+ self.state.font = value
+
+ def select_emf_handle(self, handle: int) -> None:
+ """选择 EMF 显式 handle 或 stock object。"""
+ if handle & 0x80000000:
+ stock = _stock_object(handle & 0x7FFFFFFF)
+ if stock is None:
+ self.warn("unknown_stock_object", f"unknown EMF stock object: {handle:#x}")
+ return
+ self.select_object(stock)
+ return
+ value = self.emf_objects.get(handle)
+ if value is None:
+ self.warn("missing_object", f"EMF object handle does not exist: {handle}")
+ return
+ self.select_object(value)
+
+ def select_wmf_handle(self, handle: int) -> None:
+ """选择 WMF 对象槽或兼容的 stock object。"""
+ if handle & 0x8000:
+ stock = _stock_object(handle & 0x7FFF)
+ if stock is None:
+ self.warn("unknown_stock_object", f"unknown WMF stock object: {handle:#x}")
+ return
+ self.select_object(stock)
+ return
+ if handle >= len(self.wmf_objects) or self.wmf_objects[handle] is None:
+ self.warn("missing_object", f"WMF object handle does not exist: {handle}")
+ return
+ self.select_object(self.wmf_objects[handle]) # type: ignore[arg-type]
+
+ def finalize(self, size_hint: tuple[int, int] | None) -> MetafileDocument:
+ """解析最终边界、输出尺寸并冻结统一图元文档。"""
+ command_bounds = _commands_bounds(self.commands)
+ bounds = self.header.bounds
+ if bounds is None or abs(bounds.width) < 1e-9 or abs(bounds.height) < 1e-9:
+ bounds = command_bounds
+ if bounds is None or abs(bounds.width) < 1e-9 or abs(bounds.height) < 1e-9:
+ raise MetafileUnsupportedError("metafile contains no visible output")
+ bounds = bounds.normalized()
+ requested = size_hint or self.header.pixel_size
+ if requested is None:
+ requested = max(1, round(bounds.width)), max(1, round(bounds.height))
+ width, height, downscaled = _bounded_canvas_size(requested)
+ if downscaled:
+ self.diagnostics.add(
+ "canvas_downscaled",
+ "warning",
+ f"metafile canvas was downscaled from {requested[0]}x{requested[1]} to {width}x{height}",
+ )
+ return MetafileDocument(
+ source_format=self.header.source_format,
+ emfplus_mode=self.header.emfplus_mode,
+ bounds=bounds,
+ width=width,
+ height=height,
+ commands=tuple(self.commands),
+ diagnostics=self.diagnostics.freeze(),
+ partial=self.partial,
+ )
+
+
+def _clip_mode_name(mode: int) -> str | None:
+ """把 GDI RegionMode 数值转换为内部裁剪操作名称。"""
+ return {
+ _RGN_AND: "and",
+ _RGN_OR: "or",
+ _RGN_XOR: "xor",
+ _RGN_DIFF: "diff",
+ _RGN_COPY: "copy",
+ }.get(mode)
+
+
+def _stock_object(index: int) -> Pen | Brush | Font | None:
+ """返回常见 GDI stock object 的确定性跨平台表示。"""
+ brushes: dict[int, Brush] = {
+ 0: Brush(color=WHITE),
+ 1: Brush(color=Color(192, 192, 192)),
+ 2: Brush(color=Color(128, 128, 128)),
+ 3: Brush(color=Color(64, 64, 64)),
+ 4: Brush(color=BLACK),
+ 5: Brush(kind="null"),
+ 6: Brush(kind="null"),
+ 18: Brush(color=WHITE),
+ }
+ if index in brushes:
+ return brushes[index]
+ pens: dict[int, Pen] = {
+ 7: Pen(color=WHITE),
+ 8: Pen(color=BLACK),
+ 9: Pen(null=True),
+ 19: Pen(color=BLACK),
+ }
+ if index in pens:
+ return pens[index]
+ if 10 <= index <= 17:
+ return Font(face_name="Courier New" if index in {10, 11, 16} else "Arial")
+ return None
+
+
+def _commands_bounds(commands: list[DrawCommand]) -> Rect | None:
+ """计算全部绘图命令的保守可见包围盒。"""
+ rectangles: list[Rect | None] = []
+ for command in commands:
+ if isinstance(command, DrawPathCommand):
+ rectangles.append(path_bounds(command.path))
+ elif isinstance(command, DrawTextCommand):
+ if command.bounds is not None and abs(command.bounds.width) > 0 and abs(command.bounds.height) > 0:
+ rectangles.append(command.bounds)
+ else:
+ estimated_width = max(command.font_height * 0.6 * len(command.text), command.font_height)
+ rectangles.append(
+ Rect(
+ command.origin[0],
+ command.origin[1] - command.font_height,
+ command.origin[0] + estimated_width,
+ command.origin[1] + command.font_height * 0.25,
+ )
+ )
+ else:
+ xs = [point[0] for point in command.destination]
+ ys = [point[1] for point in command.destination]
+ rectangles.append(Rect(min(xs), min(ys), max(xs), max(ys)))
+ return union_rectangles(rectangles)
+
+
+def _bounded_canvas_size(requested: tuple[int, int]) -> tuple[int, int, bool]:
+ """按单边和总像素预算等比收缩画布尺寸。"""
+ width, height = requested
+ if width <= 0 or height <= 0:
+ raise MetafileMalformedError(f"metafile canvas must be positive: {width}x{height}")
+ scale = min(1.0, MAX_CANVAS_DIMENSION / width, MAX_CANVAS_DIMENSION / height)
+ if width * height * scale * scale > MAX_CANVAS_PIXELS:
+ scale = min(scale, (MAX_CANVAS_PIXELS / (width * height)) ** 0.5)
+ bounded_width = max(1, round(width * scale))
+ bounded_height = max(1, round(height * scale))
+ return bounded_width, bounded_height, scale < 1.0
+
+
+def _parse_rect_i32(reader: BoundedReader, offset: int) -> Rect:
+ """读取四个有符号 32 位坐标组成的 RectL。"""
+ return Rect(reader.i32(offset), reader.i32(offset + 4), reader.i32(offset + 8), reader.i32(offset + 12))
+
+
+def _parse_rect_i16(reader: BoundedReader, offset: int) -> Rect:
+ """读取四个有符号 16 位坐标组成的 WMF 矩形。"""
+ return Rect(reader.i16(offset), reader.i16(offset + 2), reader.i16(offset + 4), reader.i16(offset + 6))
+
+
+def _parse_xform(reader: BoundedReader, offset: int) -> Matrix:
+ """读取 EMF XForm 六个浮点参数并拒绝非有限值。"""
+ values = tuple(reader.f32(offset + index * 4) for index in range(6))
+ if not all(isfinite(value) and abs(value) <= 1e12 for value in values):
+ raise MetafileMalformedError("EMF XForm contains non-finite or unreasonably large values")
+ return Matrix(a=values[0], b=values[1], c=values[2], d=values[3], e=values[4], f=values[5])
+
+
+def _parse_color(value: int, *, alpha: int = 255) -> Color:
+ """把 GDI COLORREF 转换为带指定透明度的内部颜色。"""
+ red, green, blue = colorref_to_rgb(value)
+ return Color(red, green, blue, alpha)
+
+
+def _detect_source_format(data: bytes) -> MetafileSourceFormat:
+ """只依据实际文件签名区分 WMF 与 EMF。"""
+ if (
+ len(data) >= 44
+ and struct.unpack_from("<I", data, 0)[0] == 1
+ and struct.unpack_from("<I", data, 40)[0] == _EMF_SIGNATURE
+ ):
+ return "emf"
+ wmf_offset = 22 if len(data) >= 22 and struct.unpack_from("<I", data, 0)[0] == _PLACEABLE_WMF_KEY else 0
+ if len(data) >= wmf_offset + 18:
+ file_type, header_size = struct.unpack_from("<HH", data, wmf_offset)
+ if file_type in {1, 2} and header_size == 9:
+ return "wmf"
+ raise MetafileMalformedError("input does not contain a valid WMF or EMF signature")
+
+
+def _scan_emfplus_mode(data: bytes, start: int, end: int) -> EmfPlusMode:
+ """预扫描 EMR_COMMENT 中的 EMF+ header 并识别 Only/Dual。"""
+ offset = start
+ found_header = False
+ found_dual = False
+ record_count = 0
+ while offset + 8 <= end:
+ record_type, record_size = struct.unpack_from("<II", data, offset)
+ record_count += 1
+ if record_count > MAX_RECORDS:
+ raise MetafileResourceLimitError(f"EMF exceeds max_records={MAX_RECORDS}")
+ if record_size < 8 or record_size % 4 or record_size > end - offset:
+ raise MetafileMalformedError(f"invalid EMF record while scanning comments: offset={offset}, size={record_size}")
+ if record_type == 70 and record_size >= 28:
+ data_size = struct.unpack_from("<I", data, offset + 8)[0]
+ if data_size <= record_size - 12 and struct.unpack_from("<I", data, offset + 12)[0] == _EMFPLUS_SIGNATURE:
+ payload_offset = offset + 16
+ payload_end = offset + 12 + data_size
+ while payload_offset + 12 <= payload_end:
+ plus_type, flags, plus_size, plus_data_size = struct.unpack_from("<HHII", data, payload_offset)
+ if plus_size < 12 or plus_size > payload_end - payload_offset or plus_data_size > plus_size - 12:
+ break
+ if plus_type == 0x4001:
+ found_header = True
+ found_dual = found_dual or bool(flags & 1)
+ payload_offset += plus_size
+ offset += record_size
+ if record_type == 14:
+ break
+ if not found_header:
+ return "none"
+ return "dual" if found_dual else "only"
+
+
+def _parse_emf_header(data: bytes, dpi: int, size_hint: tuple[int, int] | None) -> _HeaderInfo:
+ """解析 EMR_HEADER、声明文件边界和物理输出尺寸。"""
+ reader = BoundedReader(data)
+ if len(reader) < 88 or reader.u32(0) != 1:
+ raise MetafileMalformedError("EMF header is truncated or has the wrong record type")
+ header_size = reader.u32(4)
+ if header_size < 88 or header_size % 4 or header_size > len(reader):
+ raise MetafileMalformedError(f"invalid EMF header size: {header_size}")
+ if reader.u32(40) != _EMF_SIGNATURE:
+ raise MetafileMalformedError("invalid EMF signature")
+ declared_bytes = reader.u32(48)
+ declared_records = reader.u32(52)
+ if declared_bytes < header_size or declared_bytes > len(reader):
+ raise MetafileMalformedError(f"invalid EMF declared byte size: {declared_bytes}")
+ if declared_records == 0 or declared_records > MAX_RECORDS:
+ raise MetafileResourceLimitError(f"invalid or excessive EMF record count: {declared_records}")
+ bounds = _parse_rect_i32(reader, 8)
+ frame = _parse_rect_i32(reader, 24)
+ device_x, device_y = reader.i32(72), reader.i32(76)
+ millimeter_x, millimeter_y = reader.i32(80), reader.i32(84)
+ if millimeter_x > 0 and millimeter_y > 0 and device_x > 0 and device_y > 0:
+ device_scale = device_x / millimeter_x, device_y / millimeter_y
+ else:
+ device_scale = dpi / 25.4, dpi / 25.4
+ pixel_size = size_hint
+ if pixel_size is None and frame.width != 0 and frame.height != 0:
+ pixel_size = max(1, round(abs(frame.width) * dpi / 2540.0)), max(1, round(abs(frame.height) * dpi / 2540.0))
+ if pixel_size is None and bounds.width != 0 and bounds.height != 0:
+ pixel_size = max(1, round(abs(bounds.width))), max(1, round(abs(bounds.height)))
+ emfplus_mode = _scan_emfplus_mode(data, 0, declared_bytes)
+ return _HeaderInfo(
+ source_format="emf",
+ record_start=0,
+ record_end=declared_bytes,
+ bounds=bounds,
+ pixel_size=pixel_size,
+ emfplus_mode=emfplus_mode,
+ device_pixels_per_mm=device_scale,
+ )
+
+
+def _parse_wmf_header(data: bytes, dpi: int, size_hint: tuple[int, int] | None) -> _HeaderInfo:
+ """解析 placeable/standard WMF 头部、对象表大小与输出尺寸。"""
+ reader = BoundedReader(data)
+ record_start = 0
+ bounds: Rect | None = None
+ pixel_size = size_hint
+ if len(reader) >= 22 and reader.u32(0) == _PLACEABLE_WMF_KEY:
+ checksum = 0
+ for offset in range(0, 20, 2):
+ checksum ^= reader.u16(offset)
+ if checksum != reader.u16(20):
+ raise MetafileMalformedError("placeable WMF checksum does not match")
+ bounds = Rect(reader.i16(6), reader.i16(8), reader.i16(10), reader.i16(12))
+ units_per_inch = reader.u16(14)
+ if units_per_inch == 0:
+ raise MetafileMalformedError("placeable WMF units-per-inch must be nonzero")
+ if pixel_size is None:
+ pixel_size = (
+ max(1, round(abs(bounds.width) * dpi / units_per_inch)),
+ max(1, round(abs(bounds.height) * dpi / units_per_inch)),
+ )
+ record_start = 22
+ if len(reader) < record_start + 18:
+ raise MetafileMalformedError("standard WMF header is truncated")
+ header = reader.subreader(record_start, 18)
+ if header.u16(0) not in {1, 2} or header.u16(2) != 9:
+ raise MetafileMalformedError("invalid standard WMF header")
+ declared_bytes = header.u32(6) * 2
+ if declared_bytes < 18 or declared_bytes > len(reader) - record_start:
+ raise MetafileMalformedError(f"invalid WMF declared byte size: {declared_bytes}")
+ object_count = header.u16(10)
+ if object_count > MAX_OBJECTS:
+ raise MetafileResourceLimitError(f"WMF object table exceeds max_objects={MAX_OBJECTS}")
+ return _HeaderInfo(
+ source_format="wmf",
+ record_start=record_start + 18,
+ record_end=record_start + declared_bytes,
+ bounds=bounds,
+ pixel_size=pixel_size,
+ device_pixels_per_mm=(dpi / 25.4, dpi / 25.4),
+ wmf_object_count=object_count,
+ )
+
+
+def parse_metafile(
+ data: bytes,
+ *,
+ dpi: int = 144,
+ size_hint: tuple[int, int] | None = None,
+) -> MetafileDocument:
+ """检测并解析 WMF/EMF,返回跨后端统一图元文档。"""
+ if not isinstance(data, bytes):
+ raise TypeError("metafile data must be bytes")
+ if not data:
+ raise MetafileMalformedError("metafile data must not be empty")
+ if len(data) > MAX_METAFILE_BYTES:
+ raise MetafileResourceLimitError(f"metafile exceeds max_metafile_bytes={MAX_METAFILE_BYTES}")
+ if not isinstance(dpi, int) or dpi < 1 or dpi > 1200:
+ raise ValueError("dpi must be an integer between 1 and 1200")
+ if size_hint is not None and (
+ len(size_hint) != 2 or not all(isinstance(value, int) for value in size_hint) or size_hint[0] <= 0 or size_hint[1] <= 0
+ ):
+ raise ValueError("size_hint must contain two positive integers")
+ source_format = _detect_source_format(data)
+ header = _parse_emf_header(data, dpi, size_hint) if source_format == "emf" else _parse_wmf_header(data, dpi, size_hint)
+ if header.emfplus_mode == "only":
+ raise MetafileUnsupportedError("EMF+ Only metafiles are not supported")
+ diagnostics = _DiagnosticSink()
+ playback = _Playback(header, diagnostics)
+ if source_format == "emf":
+ _play_emf(data, header, playback)
+ else:
+ _play_wmf(data, header, playback)
+ return playback.finalize(size_hint)
+
+
+def _pen_dash_pattern(style: int, width: float) -> tuple[float, ...]:
+ """把常见 GDI pen style 转换为 device 单位虚线模式。"""
+ unit = max(width, 1.0)
+ return {
+ 1: (6.0 * unit, 3.0 * unit),
+ 2: (unit, 2.0 * unit),
+ 3: (6.0 * unit, 2.0 * unit, unit, 2.0 * unit),
+ 4: (6.0 * unit, 2.0 * unit, unit, 2.0 * unit, unit, 2.0 * unit),
+ 8: (unit, unit),
+ }.get(style & 0xF, ())
+
+
+def _make_pen(style: int, width: float, color_value: int, *, extended: bool = False) -> Pen:
+ """从 LOGPEN/EXTLOGPEN 字段构造统一画笔。"""
+ basic_style = style & 0xF
+ cap = "square" if style & 0x100 else "flat" if style & 0x200 else "round"
+ join = "bevel" if style & 0x1000 else "miter" if style & 0x2000 else "round"
+ geometric = bool(style & 0x10000) if extended else abs(width) > 1.0
+ normalized_width = max(abs(width), 1.0)
+ return Pen(
+ color=_parse_color(color_value),
+ width=normalized_width,
+ style=style,
+ cosmetic=not geometric,
+ null=basic_style == 5,
+ cap=cap,
+ join=join,
+ dashes=_pen_dash_pattern(style, normalized_width),
+ )
+
+
+def _make_brush(style: int, color_value: int, hatch: int = 0, pattern: bytes | None = None) -> Brush:
+ """从 LOGBRUSH 字段构造统一画刷。"""
+ if style == 1:
+ return Brush(kind="null")
+ if style == 2:
+ return Brush(kind="hatch", color=_parse_color(color_value), hatch=hatch)
+ if style in {3, 5, 6, 7, 8}:
+ return Brush(kind="pattern", color=_parse_color(color_value), hatch=hatch, pattern=pattern)
+ return Brush(kind="solid", color=_parse_color(color_value), hatch=hatch)
+
+
+def _decode_font_name(raw: bytes, *, wide: bool) -> str:
+ """解码 LOGFONT face name 并移除结尾 NUL。"""
+ if wide:
+ if len(raw) % 2:
+ raw = raw[:-1]
+ text = raw.decode("utf-16le", errors="replace")
+ else:
+ text = raw.decode("cp1252", errors="replace")
+ return text.split("\x00", 1)[0].strip() or "Arial"
+
+
+def _parse_emf_font(record: BoundedReader) -> Font:
+ """解析 EMR_EXTCREATEFONTINDIRECTW 的 LOGFONTW 首部。"""
+ return Font(
+ face_name=_decode_font_name(record.bytes(40, 64), wide=True),
+ height=float(record.i32(12)),
+ width=float(record.i32(16)),
+ escapement=float(record.i32(20)),
+ orientation=float(record.i32(24)),
+ weight=record.i32(28),
+ italic=bool(record.u8(32)),
+ underline=bool(record.u8(33)),
+ strikeout=bool(record.u8(34)),
+ charset=record.u8(35),
+ )
+
+
+def _parse_wmf_font(payload: BoundedReader) -> Font:
+ """解析 META_CREATEFONTINDIRECT 的 16 位 LOGFONT。"""
+ if len(payload) < 18:
+ raise MetafileMalformedError("WMF LOGFONT is truncated")
+ face_size = min(32, max(0, len(payload) - 18))
+ return Font(
+ face_name=_decode_font_name(payload.bytes(18, face_size), wide=False),
+ height=float(payload.i16(0)),
+ width=float(payload.i16(2)),
+ escapement=float(payload.i16(4)),
+ orientation=float(payload.i16(6)),
+ weight=payload.i16(8),
+ italic=bool(payload.u8(10)),
+ underline=bool(payload.u8(11)),
+ strikeout=bool(payload.u8(12)),
+ charset=payload.u8(13),
+ )
+
+
+def _charset_codec(charset: int) -> str:
+ """把常见 Windows LOGFONT charset 映射为 Python codec。"""
+ return {
+ 0: "cp1252",
+ 1: "cp1252",
+ 2: "cp1252",
+ 128: "shift_jis",
+ 129: "cp949",
+ 134: "gb18030",
+ 136: "big5",
+ 161: "cp1253",
+ 162: "cp1254",
+ 163: "cp1258",
+ 177: "cp1255",
+ 178: "cp1256",
+ 186: "cp1257",
+ 204: "cp1251",
+ 222: "cp874",
+ 238: "cp1250",
+ 255: "cp437",
+ }.get(charset, "cp1252")
+
+
+def _decode_ansi_text(raw: bytes, charset: int) -> str:
+ """按当前 LOGFONT charset 尽力解码 GDI ANSI 文本。"""
+ return raw.decode(_charset_codec(charset), errors="replace")
+
+
+def _path_from_device_points(points: list[Point], *, close: bool) -> GraphicsPath:
+ """从 device 坐标点列构造单个折线路径。"""
+ if not points:
+ return GraphicsPath(())
+ builder = PathBuilder()
+ builder.move_to(points[0])
+ for point in points[1:]:
+ builder.line_to(point)
+ if close:
+ builder.close()
+ return builder.build()
+
+
+def _read_emf_points(record: BoundedReader, count: int, offset: int, *, compact: bool) -> list[Point]:
+ """读取 EMF PointL/PointS 数组并保留逻辑坐标。"""
+ stride = 4 if compact else 8
+ if count < 0 or count > MAX_POINTS_PER_RECORD or count > record.remaining(offset) // stride:
+ raise MetafileMalformedError(f"EMF point array exceeds record boundary: count={count}")
+ if compact:
+ return [(float(record.i16(offset + index * 4)), float(record.i16(offset + index * 4 + 2))) for index in range(count)]
+ return [(float(record.i32(offset + index * 8)), float(record.i32(offset + index * 8 + 4))) for index in range(count)]
+
+
+def _read_wmf_points(payload: BoundedReader, count: int, offset: int) -> list[Point]:
+ """读取 WMF PointS 数组并保留逻辑坐标。"""
+ if count < 0 or count > MAX_POINTS_PER_RECORD or count > payload.remaining(offset) // 4:
+ raise MetafileMalformedError(f"WMF point array exceeds record boundary: count={count}")
+ return [(float(payload.i16(offset + index * 4)), float(payload.i16(offset + index * 4 + 2))) for index in range(count)]
+
+
+def _emit_polybezier(playback: _Playback, points: list[Point], *, to: bool) -> None:
+ """把 PolyBezier/PolyBezierTo 点列追加为三次路径。"""
+ if not points:
+ return
+ if to:
+ playback.polybezier_to(points)
+ return
+ builder = PathBuilder()
+ builder.move_to(playback.map_point(points[0]))
+ remaining = points[1:]
+ if len(remaining) % 3:
+ playback.warn("invalid_bezier_points", "PolyBezier point count is not a multiple of three")
+ remaining = remaining[: len(remaining) - len(remaining) % 3]
+ for index in range(0, len(remaining), 3):
+ builder.cubic_to(
+ playback.map_point(remaining[index]),
+ playback.map_point(remaining[index + 1]),
+ playback.map_point(remaining[index + 2]),
+ )
+ playback.emit_path(builder.build(), stroke=True, fill=False)
+
+
+def _emit_text(
+ playback: _Playback,
+ *,
+ text: str,
+ reference: Point,
+ options: int,
+ bounds: Rect | None,
+ advances: list[Point] | None,
+) -> None:
+ """把 GDI 文字和显式 advance 转换为统一文字命令。"""
+ if not text:
+ return
+ if options & _ETO_GLYPH_INDEX:
+ playback.warn("glyph_index_text", "glyph-index text was replaced with visible placeholder glyphs")
+ text = "□" * len(text)
+ logical_origin = playback.state.current_position if playback.state.text_align & _TA_UPDATECP else reference
+ origin = playback.map_point(logical_origin)
+ positions: list[Point] = []
+ if advances:
+ cursor_x, cursor_y = logical_origin
+ for index, _character in enumerate(text):
+ positions.append(playback.map_point((cursor_x, cursor_y)))
+ if index < len(advances):
+ cursor_x += advances[index][0]
+ cursor_y += advances[index][1]
+ if playback.state.text_align & _TA_UPDATECP:
+ playback.state.current_position = (cursor_x, cursor_y)
+ font = playback.state.font
+ mapped_height = vector_length(playback.map_vector((0.0, font.height or -12.0)))
+ baseline_vector = playback.map_vector((1.0, 0.0))
+ rotation = degrees(atan2(baseline_vector[1], baseline_vector[0])) + font.escapement / 10.0
+ mapped_bounds: Rect | None = None
+ if bounds is not None and (options & (_ETO_OPAQUE | _ETO_CLIPPED)):
+ corners = [
+ playback.map_point((bounds.left, bounds.top)),
+ playback.map_point((bounds.right, bounds.top)),
+ playback.map_point((bounds.right, bounds.bottom)),
+ playback.map_point((bounds.left, bounds.bottom)),
+ ]
+ mapped_bounds = Rect(
+ min(point[0] for point in corners),
+ min(point[1] for point in corners),
+ max(point[0] for point in corners),
+ max(point[1] for point in corners),
+ )
+ clip = playback.state.clip
+ if mapped_bounds is not None and options & _ETO_CLIPPED:
+ clip = (*clip, ClipOperation(rectangle_path(mapped_bounds), "and"))
+ playback.append_command(
+ DrawTextCommand(
+ text=text,
+ origin=origin,
+ positions=tuple(positions),
+ font=font,
+ font_height=max(mapped_height, 1.0),
+ rotation=rotation,
+ text_align=playback.state.text_align,
+ color=playback.state.text_color,
+ background_color=playback.state.background_color,
+ opaque=bool(options & _ETO_OPAQUE) or playback.state.background_mode == 2,
+ bounds=mapped_bounds,
+ clip=clip,
+ )
+ )
+
+
+def _append_image_command(
+ playback: _Playback,
+ record: BoundedReader,
+ *,
+ off_bmi: int,
+ cb_bmi: int,
+ off_bits: int,
+ cb_bits: int,
+ destination: Rect,
+ source: Rect | None,
+ rop: int,
+ constant_alpha: int = 255,
+ use_source_alpha: bool = False,
+) -> None:
+ """校验 DIB 子区间并追加统一位图命令。"""
+ if cb_bmi <= 0 or cb_bits <= 0:
+ playback.warn("empty_dib", "bitmap record does not contain a DIB header and pixel payload")
+ return
+ if rop not in _SUPPORTED_ROP3:
+ playback.warn("unsupported_rop3", f"unsupported ROP3 will use source-over approximation: {rop:#x}")
+ if (
+ cb_bmi > MAX_EMBEDDED_BITMAP_BYTES
+ or cb_bits > MAX_EMBEDDED_BITMAP_BYTES
+ or cb_bmi + cb_bits > MAX_EMBEDDED_BITMAP_BYTES
+ ):
+ raise MetafileResourceLimitError(f"embedded bitmap exceeds max_embedded_bitmap_bytes={MAX_EMBEDDED_BITMAP_BYTES}")
+ dib_header = record.bytes(off_bmi, cb_bmi)
+ bits = record.bytes(off_bits, cb_bits)
+ corners = (
+ playback.map_point((destination.left, destination.top)),
+ playback.map_point((destination.right, destination.top)),
+ playback.map_point((destination.right, destination.bottom)),
+ playback.map_point((destination.left, destination.bottom)),
+ )
+ playback.append_command(
+ DrawImageCommand(
+ dib_header=dib_header,
+ bits=bits,
+ destination=corners,
+ source=source,
+ rop=rop,
+ stretch_mode=playback.state.stretch_mode,
+ constant_alpha=max(0, min(constant_alpha, 255)),
+ use_source_alpha=use_source_alpha,
+ clip=playback.state.clip,
+ )
+ )
+
+
+def _play_emf(data: bytes, header: _HeaderInfo, playback: _Playback) -> None:
+ """按文件顺序验证并回放全部 EMF records。"""
+ offset = header.record_start
+ record_index = 0
+ saw_eof = False
+ while offset < header.record_end:
+ if offset + 8 > header.record_end:
+ raise MetafileMalformedError(f"truncated EMF record header at offset={offset}")
+ record_type, record_size = struct.unpack_from("<II", data, offset)
+ record_index += 1
+ if record_index > MAX_RECORDS:
+ raise MetafileResourceLimitError(f"EMF exceeds max_records={MAX_RECORDS}")
+ if record_size < 8 or record_size % 4 or record_size > header.record_end - offset:
+ raise MetafileMalformedError(f"invalid EMF record size at offset={offset}: {record_size}")
+ playback.set_record_context(record_type, record_index, offset)
+ record = BoundedReader(memoryview(data)[offset : offset + record_size], base_offset=offset)
+ _handle_emf_record(record_type, record, playback)
+ offset += record_size
+ if record_type == 14:
+ saw_eof = True
+ break
+ if not saw_eof:
+ raise MetafileMalformedError("EMF record stream does not contain EMR_EOF")
+
+
+def _play_wmf(data: bytes, header: _HeaderInfo, playback: _Playback) -> None:
+ """按文件顺序验证并回放全部 WMF records。"""
+ offset = header.record_start
+ record_index = 0
+ saw_eof = False
+ while offset < header.record_end:
+ if offset + 6 > header.record_end:
+ raise MetafileMalformedError(f"truncated WMF record header at offset={offset}")
+ size_words = struct.unpack_from("<I", data, offset)[0]
+ function = struct.unpack_from("<H", data, offset + 4)[0]
+ record_size = size_words * 2
+ record_index += 1
+ if record_index > MAX_RECORDS:
+ raise MetafileResourceLimitError(f"WMF exceeds max_records={MAX_RECORDS}")
+ if size_words < 3 or record_size > header.record_end - offset:
+ raise MetafileMalformedError(f"invalid WMF record size at offset={offset}: words={size_words}")
+ playback.set_record_context(function, record_index, offset)
+ payload = BoundedReader(memoryview(data)[offset + 6 : offset + record_size], base_offset=offset + 6)
+ _handle_wmf_record(function, payload, playback)
+ offset += record_size
+ if function == 0:
+ saw_eof = True
+ break
+ if not saw_eof:
+ raise MetafileMalformedError("WMF record stream does not contain META_EOF")
+
+
+def _handle_emf_poly(record_type: int, record: BoundedReader, playback: _Playback) -> bool:
+ """处理 EMF 32/16 位折线、多边形与贝塞尔记录。"""
+ simple_types = {2, 3, 4, 5, 6, 85, 86, 87, 88, 89}
+ poly_types = {7, 8, 90, 91}
+ if record_type not in simple_types | poly_types:
+ return False
+ compact = record_type >= 85
+ if record_type in simple_types:
+ count = record.u32(24)
+ playback.charge_points(count)
+ points = _read_emf_points(record, count, 28, compact=compact)
+ if record_type in {2, 5, 85, 88}:
+ _emit_polybezier(playback, points, to=record_type in {5, 88})
+ return True
+ mapped = [playback.map_point(point) for point in points]
+ if record_type in {6, 89}:
+ playback.polyline_to(points)
+ return True
+ playback.emit_path(
+ _path_from_device_points(mapped, close=record_type in {3, 86}),
+ stroke=True,
+ fill=record_type in {3, 86},
+ )
+ return True
+
+ polygon_count = record.u32(24)
+ total_count = record.u32(28)
+ if polygon_count > MAX_POINTS_PER_RECORD or polygon_count > record.remaining(32) // 4:
+ raise MetafileMalformedError(f"EMF polygon count array exceeds record boundary: count={polygon_count}")
+ counts = [record.u32(32 + index * 4) for index in range(polygon_count)]
+ if sum(counts) != total_count:
+ raise MetafileMalformedError("EMF poly-polygon counts do not equal total point count")
+ playback.charge_points(total_count)
+ points_offset = 32 + polygon_count * 4
+ points = _read_emf_points(record, total_count, points_offset, compact=compact)
+ builder = PathBuilder()
+ cursor = 0
+ close = record_type in {8, 91}
+ for count in counts:
+ mapped = [playback.map_point(point) for point in points[cursor : cursor + count]]
+ builder.extend(_path_from_device_points(mapped, close=close))
+ cursor += count
+ playback.emit_path(builder.build(), stroke=True, fill=close)
+ return True
+
+
+def _handle_emf_record(record_type: int, record: BoundedReader, playback: _Playback) -> None:
+ """分派并执行单条 EMF record,未知绘图记录按规范跳过。"""
+ if record_type in {1, 14, 70}:
+ return
+ if _handle_emf_poly(record_type, record, playback):
+ return
+
+ if record_type == 9:
+ playback.state.window_extent = float(record.i32(8)), float(record.i32(12))
+ return
+ if record_type == 10:
+ playback.state.window_origin = float(record.i32(8)), float(record.i32(12))
+ return
+ if record_type == 11:
+ playback.state.viewport_extent = float(record.i32(8)), float(record.i32(12))
+ return
+ if record_type == 12:
+ playback.state.viewport_origin = float(record.i32(8)), float(record.i32(12))
+ return
+ if record_type == 13:
+ playback.state.brush_origin = float(record.i32(8)), float(record.i32(12))
+ return
+ if record_type == 17:
+ playback.state.map_mode = record.i32(8)
+ return
+ if record_type == 18:
+ playback.state.background_mode = record.u32(8)
+ return
+ if record_type == 19:
+ playback.state.polygon_fill_mode = record.u32(8)
+ return
+ if record_type == 20:
+ rop2 = record.u32(8)
+ if not 1 <= rop2 <= 16:
+ playback.warn("unsupported_rop2", f"invalid ROP2 will use COPYPEN approximation: {rop2}")
+ rop2 = 13
+ playback.state.rop2 = rop2
+ return
+ if record_type == 21:
+ playback.state.stretch_mode = record.u32(8)
+ return
+ if record_type == 22:
+ playback.state.text_align = record.u32(8)
+ return
+ if record_type == 24:
+ playback.state.text_color = _parse_color(record.u32(8))
+ return
+ if record_type == 25:
+ playback.state.background_color = _parse_color(record.u32(8))
+ return
+ if record_type == 26:
+ offset = playback.map_vector((float(record.i32(8)), float(record.i32(12))))
+ translation = Matrix(e=offset[0], f=offset[1])
+ playback.state.clip = tuple(
+ replace(operation, path=transform_path(operation.path, translation)) for operation in playback.state.clip
+ )
+ return
+ if record_type == 27:
+ point = float(record.i32(8)), float(record.i32(12))
+ playback.move_to(point)
+ return
+ if record_type == 28:
+ playback.reset_clip()
+ return
+ if record_type in {29, 30}:
+ logical = _parse_rect_i32(record, 8)
+ mapped = transform_path(rectangle_path(logical), playback.logical_matrix())
+ playback.add_clip(mapped, _RGN_DIFF if record_type == 29 else _RGN_AND)
+ return
+ if record_type in {31, 32}:
+ x_num, x_den = record.i32(8), record.i32(12)
+ y_num, y_den = record.i32(16), record.i32(20)
+ if x_den == 0 or y_den == 0:
+ playback.warn("zero_scale_denominator", "viewport/window scale record has a zero denominator")
+ return
+ if record_type == 31:
+ width, height = playback.state.viewport_extent
+ playback.state.viewport_extent = width * x_num / x_den, height * y_num / y_den
+ else:
+ width, height = playback.state.window_extent
+ playback.state.window_extent = width * x_num / x_den, height * y_num / y_den
+ return
+ if record_type == 33:
+ playback.save_dc()
+ return
+ if record_type == 34:
+ playback.restore_dc(record.i32(8))
+ return
+ if record_type == 35:
+ playback.state.world_transform = _parse_xform(record, 8)
+ return
+ if record_type == 36:
+ transform = _parse_xform(record, 8)
+ mode = record.u32(32)
+ if mode == 1:
+ playback.state.world_transform = Matrix()
+ elif mode == 2:
+ playback.state.world_transform = playback.state.world_transform.then(transform)
+ elif mode == 3:
+ playback.state.world_transform = transform.then(playback.state.world_transform)
+ elif mode == 4:
+ playback.state.world_transform = transform
+ else:
+ playback.warn("unsupported_transform_mode", f"unsupported ModifyWorldTransform mode: {mode}")
+ return
+ if record_type == 37:
+ playback.select_emf_handle(record.u32(8))
+ return
+ if record_type == 38:
+ handle = record.u32(8)
+ _validate_emf_handle(handle)
+ playback.emf_objects[handle] = _make_pen(record.u32(12), float(record.i32(16)), record.u32(24))
+ return
+ if record_type == 39:
+ handle = record.u32(8)
+ _validate_emf_handle(handle)
+ playback.emf_objects[handle] = _make_brush(record.u32(12), record.u32(16), record.u32(20))
+ return
+ if record_type == 40:
+ playback.emf_objects.pop(record.u32(8), None)
+ return
+ if record_type == 57:
+ playback.state.arc_direction = record.u32(8)
+ return
+ if record_type == 58:
+ value = record.f32(8)
+ if isfinite(value) and value > 0:
+ playback.state.miter_limit = value
+ else:
+ playback.warn("invalid_miter_limit", f"invalid miter limit: {value}")
+ return
+
+ if record_type == 15:
+ point = playback.map_point((float(record.i32(8)), float(record.i32(12))))
+ color = _parse_color(record.u32(16))
+ playback.append_command(
+ DrawPathCommand(
+ path=rectangle_path(Rect(point[0], point[1], point[0] + 1.0, point[1] + 1.0)),
+ pen=Pen(null=True),
+ brush=Brush(color=color),
+ stroke=False,
+ fill=True,
+ fill_rule="evenodd",
+ clip=playback.state.clip,
+ rop2=13,
+ )
+ )
+ return
+ if record_type == 54:
+ endpoint = float(record.i32(8)), float(record.i32(12))
+ playback.line_to(endpoint)
+ return
+ if record_type in {42, 43, 44}:
+ rect = _parse_rect_i32(record, 8)
+ if record_type == 42:
+ path = ellipse_path(rect)
+ elif record_type == 44:
+ path = round_rectangle_path(rect, abs(record.i32(24)) / 2.0, abs(record.i32(28)) / 2.0)
+ else:
+ path = rectangle_path(rect)
+ playback.emit_logical_path(path, stroke=True, fill=True)
+ return
+ if record_type in {45, 46, 47, 55}:
+ rect = _parse_rect_i32(record, 8)
+ start = float(record.i32(24)), float(record.i32(28))
+ end = float(record.i32(32)), float(record.i32(36))
+ close_mode = "chord" if record_type == 46 else "pie" if record_type == 47 else "open"
+ path = arc_path(rect, start, end, direction=playback.state.arc_direction, close_mode=close_mode)
+ playback.emit_logical_path(path, stroke=True, fill=close_mode != "open")
+ if record_type == 55:
+ playback.state.current_position = end
+ return
+ if record_type == 41:
+ center = float(record.i32(8)), float(record.i32(12))
+ radius = abs(float(record.u32(16)))
+ start_angle = record.f32(20)
+ sweep_angle = record.f32(24)
+ from math import cos, radians, sin
+
+ start = (
+ center[0] + radius * cos(radians(start_angle)),
+ center[1] - radius * sin(radians(start_angle)),
+ )
+ end_angle = start_angle + sweep_angle
+ end = (
+ center[0] + radius * cos(radians(end_angle)),
+ center[1] - radius * sin(radians(end_angle)),
+ )
+ direction = 2 if sweep_angle >= 0 else 1
+ playback.emit_logical_path(
+ arc_path(
+ Rect(center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius),
+ start,
+ end,
+ direction=direction,
+ ),
+ stroke=True,
+ fill=False,
+ )
+ return
+
+ if record_type == 59:
+ playback.begin_path()
+ return
+ if record_type == 60:
+ playback.end_path()
+ return
+ if record_type == 61:
+ if playback.path_active and playback.path_builder.figure_open:
+ playback.path_builder.close()
+ else:
+ playback.warn("close_figure_without_path", "CloseFigure ignored without an active path")
+ return
+ if record_type in {62, 63, 64}:
+ path = playback.consume_path()
+ if record_type == 63:
+ path = close_open_subpaths(path)
+ playback.emit_path(path, stroke=record_type in {63, 64}, fill=record_type in {62, 63})
+ return
+ if record_type == 67:
+ path = playback.consume_path()
+ if path.segments:
+ playback.add_clip(path, record.u32(8))
+ return
+ if record_type == 68:
+ playback.path_builder.clear()
+ playback.path_active = False
+ playback.path_ready = False
+ return
+
+ if record_type == 75:
+ _handle_emf_region_clip(record, playback)
+ return
+ if record_type in {76, 77, 80, 81, 114}:
+ _handle_emf_bitmap(record_type, record, playback)
+ return
+ if record_type == 82:
+ handle = record.u32(8)
+ _validate_emf_handle(handle)
+ playback.emf_objects[handle] = _parse_emf_font(record)
+ return
+ if record_type in {83, 84}:
+ _handle_emf_text(record_type, record, playback)
+ return
+ if record_type == 94:
+ handle = record.u32(8)
+ _validate_emf_handle(handle)
+ cb_bmi, cb_bits = record.u32(20), record.u32(28)
+ pattern = b""
+ if cb_bmi + cb_bits <= MAX_EMBEDDED_BITMAP_BYTES:
+ pattern = record.bytes(record.u32(16), cb_bmi) + record.bytes(record.u32(24), cb_bits)
+ playback.emf_objects[handle] = Brush(kind="pattern", pattern=pattern)
+ playback.warn("pattern_brush_approximation", "DIB pattern brush will use a solid-color approximation")
+ return
+ if record_type == 95:
+ handle = record.u32(8)
+ _validate_emf_handle(handle)
+ style = record.u32(28)
+ width = float(record.u32(32))
+ pen = _make_pen(style, width, record.u32(40), extended=True)
+ style_count = record.u32(48)
+ if style_count and style_count <= record.remaining(52) // 4:
+ dashes = tuple(max(1.0, float(record.u32(52 + index * 4))) for index in range(style_count))
+ pen = replace(pen, dashes=dashes)
+ playback.emf_objects[handle] = pen
+ return
+ if record_type == 120:
+ playback.state.brush = replace(playback.state.brush, color=_parse_color(record.u32(8)))
+ return
+ if record_type == 121:
+ playback.state.pen = replace(playback.state.pen, color=_parse_color(record.u32(8)))
+ return
+
+ harmless_state_records = {
+ 16,
+ 23,
+ 48,
+ 49,
+ 50,
+ 51,
+ 52,
+ 98,
+ 99,
+ 100,
+ 101,
+ 104,
+ 107,
+ 109,
+ 110,
+ 111,
+ 112,
+ 113,
+ 115,
+ 117,
+ 119,
+ }
+ if record_type in harmless_state_records:
+ playback.warn("ignored_state_record", f"EMF state/control record was ignored: {record_type}", partial=False)
+ return
+ playback.warn("unsupported_emf_record", f"unsupported EMF record was skipped: {record_type}")
+
+
+def _validate_emf_handle(handle: int) -> None:
+ """拒绝保留 handle、stock handle 和超出固定对象预算的值。"""
+ if handle == 0 or handle & 0x80000000 or handle > MAX_OBJECTS:
+ raise MetafileResourceLimitError(f"invalid or excessive EMF object handle: {handle}")
+
+
+def _handle_emf_region_clip(record: BoundedReader, playback: _Playback) -> None:
+ """解析 EMR_EXTSELECTCLIPRGN 的矩形 region 数据。"""
+ data_size = record.u32(8)
+ mode = record.u32(12)
+ if data_size == 0:
+ if mode == _RGN_COPY:
+ playback.reset_clip()
+ else:
+ playback.warn("empty_clip_region", f"empty clip region used with combine mode {mode}")
+ return
+ if data_size > record.remaining(16) or data_size < 32:
+ raise MetafileMalformedError(f"EMF region data exceeds record boundary: size={data_size}")
+ region = record.subreader(16, data_size)
+ header_size = region.u32(0)
+ region_type = region.u32(4)
+ rectangle_count = region.u32(8)
+ region_bytes = region.u32(12)
+ if header_size < 32 or region_type != 1:
+ raise MetafileMalformedError("EMF region header is invalid")
+ if rectangle_count > MAX_POINTS_PER_RECORD or region_bytes > region.remaining(header_size):
+ raise MetafileMalformedError("EMF region rectangle data exceeds its declared boundary")
+ if rectangle_count > region.remaining(header_size) // 16:
+ raise MetafileMalformedError("EMF region rectangle count exceeds record boundary")
+ playback.charge_points(rectangle_count * 4)
+ builder = PathBuilder()
+ for index in range(rectangle_count):
+ rect = _parse_rect_i32(region, header_size + index * 16)
+ builder.extend(transform_path(rectangle_path(rect), playback.logical_matrix()))
+ path = builder.build()
+ if path.segments:
+ playback.add_clip(path, mode)
+
+
+def _handle_emf_bitmap(record_type: int, record: BoundedReader, playback: _Playback) -> None:
+ """解析常见 EMF DIB、BitBlt、StretchBlt 与 AlphaBlend 记录。"""
+ if record_type in {76, 77}:
+ destination = Rect(
+ float(record.i32(24)),
+ float(record.i32(28)),
+ float(record.i32(24) + record.i32(32)),
+ float(record.i32(28) + record.i32(36)),
+ )
+ source_width = record.i32(100) if record_type == 77 and len(record) >= 108 else record.i32(32)
+ source_height = record.i32(104) if record_type == 77 and len(record) >= 108 else record.i32(36)
+ source = Rect(
+ float(record.i32(44)),
+ float(record.i32(48)),
+ float(record.i32(44) + source_width),
+ float(record.i32(48) + source_height),
+ )
+ _append_image_command(
+ playback,
+ record,
+ off_bmi=record.u32(84),
+ cb_bmi=record.u32(88),
+ off_bits=record.u32(92),
+ cb_bits=record.u32(96),
+ destination=destination,
+ source=source,
+ rop=record.u32(40),
+ )
+ return
+ if record_type == 81:
+ destination = Rect(
+ float(record.i32(24)),
+ float(record.i32(28)),
+ float(record.i32(24) + record.i32(72)),
+ float(record.i32(28) + record.i32(76)),
+ )
+ source = Rect(
+ float(record.i32(32)),
+ float(record.i32(36)),
+ float(record.i32(32) + record.i32(40)),
+ float(record.i32(36) + record.i32(44)),
+ )
+ _append_image_command(
+ playback,
+ record,
+ off_bmi=record.u32(48),
+ cb_bmi=record.u32(52),
+ off_bits=record.u32(56),
+ cb_bits=record.u32(60),
+ destination=destination,
+ source=source,
+ rop=record.u32(68),
+ )
+ return
+ if record_type == 80:
+ width, height = record.i32(40), record.i32(44)
+ destination = Rect(
+ float(record.i32(24)),
+ float(record.i32(28)),
+ float(record.i32(24) + width),
+ float(record.i32(28) + height),
+ )
+ source = Rect(
+ float(record.i32(32)),
+ float(record.i32(36)),
+ float(record.i32(32) + width),
+ float(record.i32(36) + height),
+ )
+ _append_image_command(
+ playback,
+ record,
+ off_bmi=record.u32(48),
+ cb_bmi=record.u32(52),
+ off_bits=record.u32(56),
+ cb_bits=record.u32(60),
+ destination=destination,
+ source=source,
+ rop=_SRCCOPY,
+ )
+ return
+ destination = Rect(
+ float(record.i32(24)),
+ float(record.i32(28)),
+ float(record.i32(24) + record.i32(32)),
+ float(record.i32(28) + record.i32(36)),
+ )
+ source = Rect(
+ float(record.i32(44)),
+ float(record.i32(48)),
+ float(record.i32(44) + record.i32(100)),
+ float(record.i32(48) + record.i32(104)),
+ )
+ _append_image_command(
+ playback,
+ record,
+ off_bmi=record.u32(84),
+ cb_bmi=record.u32(88),
+ off_bits=record.u32(92),
+ cb_bits=record.u32(96),
+ destination=destination,
+ source=source,
+ rop=_SRCCOPY,
+ constant_alpha=record.u8(42),
+ use_source_alpha=bool(record.u8(43) & 1),
+ )
+
+
+def _handle_emf_text(record_type: int, record: BoundedReader, playback: _Playback) -> None:
+ """解析 EMR_EXTTEXTOUTA/W 文字、bounds 与显式 advance。"""
+ if len(record) < 76:
+ raise MetafileMalformedError("EMF ExtTextOut record is truncated")
+ reference = float(record.i32(36)), float(record.i32(40))
+ character_count = record.u32(44)
+ if character_count > MAX_POINTS_PER_RECORD:
+ raise MetafileResourceLimitError(f"EMF text exceeds max characters={MAX_POINTS_PER_RECORD}")
+ string_offset = record.u32(48)
+ options = record.u32(52)
+ bounds = _parse_rect_i32(record, 56)
+ dx_offset = record.u32(72)
+ char_bytes = 2 if record_type == 84 else 1
+ raw = record.bytes(string_offset, character_count * char_bytes)
+ text = (
+ raw.decode("utf-16le", errors="replace") if record_type == 84 else _decode_ansi_text(raw, playback.state.font.charset)
+ )
+ advances: list[Point] | None = None
+ if dx_offset:
+ values_per_character = 2 if options & _ETO_PDY else 1
+ value_count = character_count * values_per_character
+ if value_count > record.remaining(dx_offset) // 4:
+ raise MetafileMalformedError("EMF ExtTextOut advance array exceeds record boundary")
+ advances = []
+ for index in range(character_count):
+ dx = float(record.i32(dx_offset + index * values_per_character * 4))
+ dy = float(record.i32(dx_offset + (index * values_per_character + 1) * 4)) if values_per_character == 2 else 0.0
+ advances.append((dx, dy))
+ playback.charge_points(character_count)
+ _emit_text(
+ playback,
+ text=text,
+ reference=reference,
+ options=options,
+ bounds=bounds,
+ advances=advances,
+ )
+
+
+def _handle_wmf_record(function: int, payload: BoundedReader, playback: _Playback) -> None:
+ """分派并执行单条 WMF record,未知绘图记录按规范跳过。"""
+ if function == 0:
+ return
+ if function == 0x0201:
+ playback.state.background_color = _parse_color(payload.u32(0))
+ return
+ if function == 0x0102:
+ playback.state.background_mode = payload.u16(0)
+ return
+ if function == 0x0103:
+ playback.state.map_mode = payload.i16(0)
+ return
+ if function == 0x0104:
+ rop2 = payload.u16(0)
+ if not 1 <= rop2 <= 16:
+ playback.warn("unsupported_rop2", f"invalid WMF ROP2 will use COPYPEN approximation: {rop2}")
+ rop2 = 13
+ playback.state.rop2 = rop2
+ return
+ if function == 0x0106:
+ playback.state.polygon_fill_mode = payload.u16(0)
+ return
+ if function == 0x0107:
+ playback.state.stretch_mode = payload.u16(0)
+ return
+ if function == 0x0209:
+ playback.state.text_color = _parse_color(payload.u32(0))
+ return
+ if function == 0x020B:
+ playback.state.window_origin = float(payload.i16(2)), float(payload.i16(0))
+ return
+ if function == 0x020C:
+ playback.state.window_extent = float(payload.i16(2)), float(payload.i16(0))
+ return
+ if function == 0x020D:
+ playback.state.viewport_origin = float(payload.i16(2)), float(payload.i16(0))
+ return
+ if function == 0x020E:
+ playback.state.viewport_extent = float(payload.i16(2)), float(payload.i16(0))
+ return
+ if function == 0x020F:
+ x, y = playback.state.window_origin
+ playback.state.window_origin = x + payload.i16(2), y + payload.i16(0)
+ return
+ if function == 0x0211:
+ x, y = playback.state.viewport_origin
+ playback.state.viewport_origin = x + payload.i16(2), y + payload.i16(0)
+ return
+ if function in {0x0410, 0x0412}:
+ y_num, y_den, x_num, x_den = payload.i16(0), payload.i16(2), payload.i16(4), payload.i16(6)
+ if x_den == 0 or y_den == 0:
+ playback.warn("zero_scale_denominator", "WMF viewport/window scale record has a zero denominator")
+ return
+ if function == 0x0410:
+ width, height = playback.state.window_extent
+ playback.state.window_extent = width * x_num / x_den, height * y_num / y_den
+ else:
+ width, height = playback.state.viewport_extent
+ playback.state.viewport_extent = width * x_num / x_den, height * y_num / y_den
+ return
+ if function == 0x001E:
+ playback.save_dc()
+ return
+ if function == 0x0127:
+ playback.restore_dc(payload.i16(0))
+ return
+ if function == 0x012E:
+ playback.state.text_align = payload.u16(0)
+ return
+ if function == 0x012D:
+ playback.select_wmf_handle(payload.u16(0))
+ return
+ if function == 0x01F0:
+ handle = payload.u16(0)
+ if handle < len(playback.wmf_objects):
+ playback.wmf_objects[handle] = None
+ return
+ if function == 0x02FA:
+ playback.create_wmf_object(_make_pen(payload.u16(0), float(payload.i16(2)), payload.u32(6)))
+ return
+ if function == 0x02FC:
+ playback.create_wmf_object(_make_brush(payload.u16(0), payload.u32(2), payload.u16(6)))
+ return
+ if function == 0x02FB:
+ playback.create_wmf_object(_parse_wmf_font(payload))
+ return
+
+ if function == 0x0214:
+ point = float(payload.i16(2)), float(payload.i16(0))
+ playback.move_to(point)
+ return
+ if function == 0x0213:
+ endpoint = float(payload.i16(2)), float(payload.i16(0))
+ playback.line_to(endpoint)
+ return
+ if function in {0x0324, 0x0325}:
+ count = payload.u16(0)
+ playback.charge_points(count)
+ points = _read_wmf_points(payload, count, 2)
+ playback.emit_path(
+ _path_from_device_points([playback.map_point(point) for point in points], close=function == 0x0324),
+ stroke=True,
+ fill=function == 0x0324,
+ )
+ return
+ if function == 0x0538:
+ polygon_count = payload.u16(0)
+ if polygon_count > MAX_POINTS_PER_RECORD or polygon_count > payload.remaining(2) // 2:
+ raise MetafileMalformedError("WMF PolyPolygon count array exceeds record boundary")
+ counts = [payload.u16(2 + index * 2) for index in range(polygon_count)]
+ total_count = sum(counts)
+ playback.charge_points(total_count)
+ points = _read_wmf_points(payload, total_count, 2 + polygon_count * 2)
+ builder = PathBuilder()
+ cursor = 0
+ for count in counts:
+ builder.extend(
+ _path_from_device_points(
+ [playback.map_point(point) for point in points[cursor : cursor + count]],
+ close=True,
+ )
+ )
+ cursor += count
+ playback.emit_path(builder.build(), stroke=True, fill=True)
+ return
+ if function in {0x0418, 0x041B, 0x061C}:
+ rect = Rect(float(payload.i16(6)), float(payload.i16(4)), float(payload.i16(2)), float(payload.i16(0)))
+ if function == 0x0418:
+ path = ellipse_path(rect)
+ elif function == 0x061C:
+ path = round_rectangle_path(rect, abs(payload.i16(10)) / 2.0, abs(payload.i16(8)) / 2.0)
+ else:
+ path = rectangle_path(rect)
+ playback.emit_logical_path(path, stroke=True, fill=True)
+ return
+ if function in {0x0817, 0x081A, 0x0830}:
+ end = float(payload.i16(2)), float(payload.i16(0))
+ start = float(payload.i16(6)), float(payload.i16(4))
+ rect = Rect(float(payload.i16(14)), float(payload.i16(12)), float(payload.i16(10)), float(payload.i16(8)))
+ close_mode = "pie" if function == 0x081A else "chord" if function == 0x0830 else "open"
+ playback.emit_logical_path(
+ arc_path(rect, start, end, direction=2, close_mode=close_mode),
+ stroke=True,
+ fill=close_mode != "open",
+ )
+ return
+ if function == 0x041F:
+ point = playback.map_point((float(payload.i16(6)), float(payload.i16(4))))
+ color = _parse_color(payload.u32(0))
+ playback.append_command(
+ DrawPathCommand(
+ path=rectangle_path(Rect(point[0], point[1], point[0] + 1.0, point[1] + 1.0)),
+ pen=Pen(null=True),
+ brush=Brush(color=color),
+ stroke=False,
+ fill=True,
+ fill_rule="evenodd",
+ clip=playback.state.clip,
+ rop2=13,
+ )
+ )
+ return
+ if function in {0x0415, 0x0416}:
+ rect = Rect(float(payload.i16(6)), float(payload.i16(4)), float(payload.i16(2)), float(payload.i16(0)))
+ playback.add_clip(
+ transform_path(rectangle_path(rect), playback.logical_matrix()),
+ _RGN_DIFF if function == 0x0415 else _RGN_AND,
+ )
+ return
+
+ if function in {0x0521, 0x0A32}:
+ _handle_wmf_text(function, payload, playback)
+ return
+ if function == 0x0F43:
+ _handle_wmf_stretchdib(payload, playback)
+ return
+ if function in {0x0940, 0x0B41}:
+ playback.warn("unsupported_wmf_dib_record", f"WMF DIB record will be skipped: {function:#x}")
+ return
+
+ harmless_records = {
+ 0x0108,
+ 0x020A,
+ 0x0231,
+ 0x0626,
+ 0x0234,
+ 0x0035,
+ 0x0436,
+ 0x0037,
+ 0x0139,
+ }
+ if function in harmless_records:
+ playback.warn("ignored_wmf_state_record", f"WMF state/control record was ignored: {function:#x}", partial=False)
+ return
+ playback.warn("unsupported_wmf_record", f"unsupported WMF record was skipped: {function:#x}")
+
+
+def _handle_wmf_text(function: int, payload: BoundedReader, playback: _Playback) -> None:
+ """解析 WMF TextOut/ExtTextOut 字符串、矩形和 advance。"""
+ if function == 0x0521:
+ count = payload.u16(0)
+ if count > payload.remaining(2):
+ raise MetafileMalformedError("WMF TextOut string exceeds record boundary")
+ raw = payload.bytes(2, count)
+ coordinate_offset = 2 + count + (count & 1)
+ reference = float(payload.i16(coordinate_offset + 2)), float(payload.i16(coordinate_offset))
+ playback.charge_points(count)
+ _emit_text(
+ playback,
+ text=_decode_ansi_text(raw, playback.state.font.charset),
+ reference=reference,
+ options=0,
+ bounds=None,
+ advances=None,
+ )
+ return
+ reference = float(payload.i16(2)), float(payload.i16(0))
+ count = payload.u16(4)
+ options = payload.u16(6)
+ offset = 8
+ bounds: Rect | None = None
+ if options & (_ETO_OPAQUE | _ETO_CLIPPED):
+ bounds = _parse_rect_i16(payload, offset)
+ offset += 8
+ if count > payload.remaining(offset):
+ raise MetafileMalformedError("WMF ExtTextOut string exceeds record boundary")
+ raw = payload.bytes(offset, count)
+ offset += count + (count & 1)
+ advances: list[Point] | None = None
+ if payload.remaining(offset) >= count * 2:
+ advances = [(float(payload.i16(offset + index * 2)), 0.0) for index in range(count)]
+ playback.charge_points(count)
+ _emit_text(
+ playback,
+ text=_decode_ansi_text(raw, playback.state.font.charset),
+ reference=reference,
+ options=options,
+ bounds=bounds,
+ advances=advances,
+ )
+
+
+def _handle_wmf_stretchdib(payload: BoundedReader, playback: _Playback) -> None:
+ """解析 META_STRETCHDIB 的内联 DIB 与源/目标矩形。"""
+ if len(payload) < 22:
+ raise MetafileMalformedError("WMF StretchDIB record is truncated")
+ rop = payload.u32(0)
+ source_height, source_width = payload.i16(6), payload.i16(8)
+ source_y, source_x = payload.i16(10), payload.i16(12)
+ destination_height, destination_width = payload.i16(14), payload.i16(16)
+ destination_y, destination_x = payload.i16(18), payload.i16(20)
+ dib = payload.bytes(22, payload.remaining(22))
+ if len(dib) < 12:
+ raise MetafileMalformedError("WMF StretchDIB payload does not contain a DIB header")
+ header_size = struct.unpack_from("<I", dib, 0)[0]
+ if header_size < 12 or header_size > len(dib):
+ raise MetafileMalformedError(f"invalid WMF DIB header size: {header_size}")
+ bits_offset = _dib_bits_offset(dib)
+ if bits_offset > len(dib):
+ raise MetafileMalformedError("WMF DIB pixel offset exceeds record boundary")
+ header = dib[:bits_offset]
+ bits = dib[bits_offset:]
+ corners = (
+ playback.map_point((float(destination_x), float(destination_y))),
+ playback.map_point((float(destination_x + destination_width), float(destination_y))),
+ playback.map_point((float(destination_x + destination_width), float(destination_y + destination_height))),
+ playback.map_point((float(destination_x), float(destination_y + destination_height))),
+ )
+ playback.append_command(
+ DrawImageCommand(
+ dib_header=header,
+ bits=bits,
+ destination=corners,
+ source=Rect(
+ float(source_x),
+ float(source_y),
+ float(source_x + source_width),
+ float(source_y + source_height),
+ ),
+ rop=rop,
+ stretch_mode=playback.state.stretch_mode,
+ clip=playback.state.clip,
+ )
+ )
+
+
+def _dib_bits_offset(dib: bytes) -> int:
+ """根据 DIB header、bit depth 和 palette 推导像素起始偏移。"""
+ reader = BoundedReader(dib)
+ header_size = reader.u32(0)
+ if header_size == 12:
+ bit_count = reader.u16(10)
+ palette_entries = 1 << bit_count if bit_count <= 8 else 0
+ return header_size + palette_entries * 3
+ if header_size < 40:
+ return header_size
+ bit_count = reader.u16(14)
+ compression = reader.u32(16)
+ colors_used = reader.u32(32)
+ palette_entries = colors_used or ((1 << bit_count) if bit_count <= 8 else 0)
+ bitfields = 12 if compression == 3 and header_size == 40 else 16 if compression == 6 and header_size == 40 else 0
+ return header_size + bitfields + palette_entries * 4
+
+
+__all__ = ["parse_metafile"]
diff --git a/mineru/model/flash/office/metafile/render.py b/mineru/model/flash/office/metafile/render.py
new file mode 100644
index 00000000..2c455894
--- /dev/null
+++ b/mineru/model/flash/office/metafile/render.py
@@ -0,0 +1,1135 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""统一 WMF/EMF 图元文档的 Pillow 与安全 SVG 后端。"""
+
+from __future__ import annotations
+
+import base64
+from functools import lru_cache
+from html import escape
+from io import BytesIO
+from math import ceil, floor, hypot
+from pathlib import Path
+import platform
+
+from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont, UnidentifiedImageError
+import pyclipper
+
+from .geometry import FlattenBudget, flatten_path, transform_path
+from .limits import MAX_CANVAS_PIXELS, MAX_EMBEDDED_BITMAP_BYTES, MAX_RENDER_WORK_PIXELS
+from .models import (
+ Brush,
+ ClipOperation,
+ ClipStack,
+ Color,
+ DrawImageCommand,
+ DrawPathCommand,
+ DrawTextCommand,
+ GraphicsPath,
+ Matrix,
+ MetafileDocument,
+ MetafileMalformedError,
+ MetafileOutputFormat,
+ MetafileResourceLimitError,
+ Pen,
+ Point,
+ Rect,
+)
+
+
+_SRCCOPY = 0x00CC0020
+_SRCAND = 0x008800C6
+_SRCPAINT = 0x00EE0086
+_SRCINVERT = 0x00660046
+_DSTINVERT = 0x00550009
+_BLACKNESS = 0x00000042
+_WHITENESS = 0x00FF0062
+
+_TA_RIGHT = 0x0002
+_TA_CENTER = 0x0006
+_TA_BOTTOM = 0x0008
+_TA_BASELINE = 0x0018
+
+_CLIPPER_SCALE = 256
+_CLIPPER_COORD_LIMIT = (1 << 61) / _CLIPPER_SCALE
+
+
+def _document_matrix(document: MetafileDocument, *, raster_scale: int = 1) -> Matrix:
+ """把统一 device 坐标映射到最终输出像素。"""
+ bounds = document.bounds.normalized()
+ scale_x = document.width * raster_scale / bounds.width
+ scale_y = document.height * raster_scale / bounds.height
+ return Matrix(a=scale_x, d=scale_y, e=-bounds.left * scale_x, f=-bounds.top * scale_y)
+
+
+def _mapped_rect(rect: Rect, matrix: Matrix) -> Rect:
+ """把矩形四角变换后返回轴对齐像素包围盒。"""
+ corners = [
+ matrix.transform_point((rect.left, rect.top)),
+ matrix.transform_point((rect.right, rect.top)),
+ matrix.transform_point((rect.right, rect.bottom)),
+ matrix.transform_point((rect.left, rect.bottom)),
+ ]
+ return Rect(
+ min(point[0] for point in corners),
+ min(point[1] for point in corners),
+ max(point[0] for point in corners),
+ max(point[1] for point in corners),
+ )
+
+
+def _dib_to_bmp(command: DrawImageCommand) -> bytes:
+ """为分离的 DIB header 和像素数据补齐 BMP 文件头。"""
+ if len(command.dib_header) < 4:
+ raise MetafileMalformedError("DIB header is truncated")
+ pixel_offset = 14 + len(command.dib_header)
+ total_size = pixel_offset + len(command.bits)
+ if total_size > MAX_EMBEDDED_BITMAP_BYTES + 14:
+ raise MetafileResourceLimitError("decoded BMP exceeds the embedded bitmap byte budget")
+ import struct
+
+ return b"BM" + struct.pack("<IHHI", total_size, 0, 0, pixel_offset) + command.dib_header + command.bits
+
+
+def _decode_raw_alpha_dib(command: DrawImageCommand) -> Image.Image | None:
+ """对 AC_SRC_ALPHA 的常见 32 位 DIB 保留原始 alpha 字节。"""
+ header = command.dib_header
+ if len(header) < 40:
+ return None
+ import struct
+
+ header_size, width, signed_height = struct.unpack_from("<Iii", header, 0)
+ bit_count = struct.unpack_from("<H", header, 14)[0]
+ compression = struct.unpack_from("<I", header, 16)[0]
+ if header_size < 40 or width <= 0 or signed_height == 0 or bit_count != 32 or compression not in {0, 3, 6}:
+ return None
+ height = abs(signed_height)
+ if width * height > MAX_CANVAS_PIXELS or len(command.bits) < width * height * 4:
+ raise MetafileResourceLimitError("32-bit DIB exceeds pixel budget or is truncated")
+ orientation = -1 if signed_height > 0 else 1
+ try:
+ return Image.frombytes(
+ "RGBA",
+ (width, height),
+ command.bits[: width * height * 4],
+ "raw",
+ "BGRA",
+ width * 4,
+ orientation,
+ )
+ except (OSError, ValueError) as exc:
+ raise MetafileMalformedError("32-bit DIB alpha payload cannot be decoded") from exc
+
+
+def _validate_dib_dimensions(header: bytes) -> None:
+ """在进入 Pillow decoder 前验证 DIB 声明尺寸与固定像素预算。"""
+ if len(header) < 12:
+ raise MetafileMalformedError("DIB header is truncated")
+ import struct
+
+ header_size = struct.unpack_from("<I", header, 0)[0]
+ if header_size == 12:
+ width, height = struct.unpack_from("<HH", header, 4)
+ elif header_size >= 40 and len(header) >= 40:
+ width, signed_height = struct.unpack_from("<ii", header, 4)
+ height = abs(signed_height)
+ else:
+ raise MetafileMalformedError(f"unsupported or truncated DIB header size: {header_size}")
+ if width <= 0 or height <= 0 or width * height > MAX_CANVAS_PIXELS:
+ raise MetafileResourceLimitError(f"DIB dimensions exceed pixel budget: {width}x{height}")
+
+
+def _decode_dib(command: DrawImageCommand) -> Image.Image:
+ """严格解码 DIB,并在需要时恢复源 alpha。"""
+ _validate_dib_dimensions(command.dib_header)
+ if command.use_source_alpha:
+ raw_alpha = _decode_raw_alpha_dib(command)
+ if raw_alpha is not None:
+ return raw_alpha
+ try:
+ with Image.open(BytesIO(_dib_to_bmp(command))) as image:
+ width, height = image.size
+ if width <= 0 or height <= 0 or width * height > MAX_CANVAS_PIXELS:
+ raise MetafileResourceLimitError(f"DIB dimensions exceed pixel budget: {width}x{height}")
+ image.load()
+ decoded = image.convert("RGBA")
+ except MetafileResourceLimitError:
+ raise
+ except (Image.DecompressionBombError, UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
+ raise MetafileMalformedError("embedded DIB cannot be decoded by Pillow") from exc
+ if not command.use_source_alpha:
+ decoded.putalpha(255)
+ return decoded
+
+
+def _font_search_roots() -> tuple[Path, ...]:
+ """返回当前平台常见字体目录,不在模块导入时访问文件系统。"""
+ system = platform.system()
+ roots: list[Path] = []
+ if system == "Darwin":
+ roots.extend((Path("/System/Library/Fonts"), Path("/Library/Fonts"), Path.home() / "Library/Fonts"))
+ elif system == "Windows":
+ import os
+
+ windows_dir = Path(os.environ.get("WINDIR", "C:/Windows"))
+ roots.append(windows_dir / "Fonts")
+ else:
+ roots.extend(
+ (
+ Path("/usr/share/fonts"),
+ Path("/usr/local/share/fonts"),
+ Path.home() / ".fonts",
+ Path.home() / ".local/share/fonts",
+ )
+ )
+ return tuple(root for root in roots if root.is_dir())
+
+
+@lru_cache(maxsize=1)
+def _font_file_index() -> dict[str, str]:
+ """惰性建立字体文件名索引,避免 import 时扫描系统目录。"""
+ index: dict[str, str] = {}
+ for root in _font_search_roots():
+ try:
+ candidates = root.rglob("*")
+ for candidate in candidates:
+ if candidate.suffix.lower() not in {".ttf", ".ttc", ".otf"}:
+ continue
+ index.setdefault(candidate.stem.casefold().replace(" ", ""), str(candidate))
+ except OSError:
+ continue
+ return index
+
+
+def _font_aliases(face_name: str, charset: int) -> tuple[str, ...]:
+ """返回 Windows 字体名在 Linux/macOS 上的固定替代顺序。"""
+ normalized = face_name.casefold().replace(" ", "")
+ alias_map = {
+ "arial": ("Arial", "LiberationSans-Regular", "DejaVuSans"),
+ "calibri": ("Calibri", "Carlito-Regular", "Arial", "DejaVuSans"),
+ "cambria": ("Cambria", "Caladea-Regular", "DejaVuSerif"),
+ "timesnewroman": ("Times New Roman", "LiberationSerif-Regular", "DejaVuSerif"),
+ "couriernew": ("Courier New", "LiberationMono-Regular", "DejaVuSansMono"),
+ "simsun": ("SimSun", "Songti SC", "NotoSerifCJKsc-Regular", "DejaVuSans"),
+ "microsoftyahei": ("Microsoft YaHei", "PingFang SC", "NotoSansCJKsc-Regular", "DejaVuSans"),
+ }
+ aliases = alias_map.get(normalized, (face_name,))
+ if charset in {128, 129, 134, 136}:
+ aliases = (*aliases, "PingFang SC", "NotoSansCJKsc-Regular", "NotoSansCJK-Regular", "DejaVuSans")
+ return tuple(dict.fromkeys((*aliases, "DejaVuSans")))
+
+
+@lru_cache(maxsize=256)
+def _load_font(
+ face_name: str,
+ size: int,
+ weight: int,
+ italic: bool,
+ charset: int,
+) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
+ """按字体名、别名和文件索引加载 Pillow 字体。"""
+ normalized_size = max(1, min(size, 4096))
+ index = _font_file_index()
+ for alias in _font_aliases(face_name, charset):
+ keys = [alias.casefold().replace(" ", "")]
+ if weight >= 700:
+ keys.insert(0, f"{keys[0]}bold")
+ if italic:
+ keys.insert(0, f"{keys[0]}italic")
+ candidates = [alias, f"{alias}.ttf", *(index[key] for key in keys if key in index)]
+ for candidate in candidates:
+ try:
+ return ImageFont.truetype(candidate, normalized_size)
+ except OSError:
+ continue
+ return ImageFont.load_default(size=normalized_size)
+
+
+def _clipper_paths(subpaths: list[tuple[list[Point], bool]]) -> list[list[tuple[int, int]]]:
+ """把浮点子路径量化为 Clipper 闭合轮廓并过滤退化输入。"""
+ result: list[list[tuple[int, int]]] = []
+ for points, _closed in subpaths:
+ converted: list[tuple[int, int]] = []
+ for x, y in points:
+ if abs(x) > _CLIPPER_COORD_LIMIT or abs(y) > _CLIPPER_COORD_LIMIT:
+ raise MetafileResourceLimitError("flattened path coordinate exceeds Clipper range")
+ point = round(x * _CLIPPER_SCALE), round(y * _CLIPPER_SCALE)
+ if not converted or converted[-1] != point:
+ converted.append(point)
+ if converted and converted[0] == converted[-1]:
+ converted.pop()
+ if len(converted) >= 3:
+ result.append(converted)
+ return result
+
+
+def _paint_polytree(mask: Image.Image, tree: pyclipper.PyPolyNode, budget: FlattenBudget | None = None) -> None:
+ """按 PolyTree 层级依次绘制外轮廓、孔洞和孔洞中的岛。"""
+ draw = ImageDraw.Draw(mask)
+
+ def paint(node: pyclipper.PyPolyNode) -> None:
+ """递归绘制当前节点的全部子轮廓。"""
+ for child in node.Childs:
+ if budget is not None:
+ budget.charge(len(child.Contour))
+ points = [(x / _CLIPPER_SCALE, y / _CLIPPER_SCALE) for x, y in child.Contour]
+ if len(points) >= 3:
+ draw.polygon(points, fill=0 if child.IsHole else 255)
+ paint(child)
+
+ paint(tree)
+
+
+def _path_mask(
+ path: GraphicsPath,
+ matrix: Matrix,
+ size: tuple[int, int],
+ fill_rule: str,
+ budget: FlattenBudget | None = None,
+) -> Image.Image:
+ """按 GDI winding/alternate 规则把复合路径转换为 L 模式 mask。"""
+ transformed = transform_path(path, matrix)
+ subpaths = flatten_path(transformed, budget=budget)
+ mask = Image.new("L", size, 0)
+ paths = _clipper_paths(subpaths)
+ if not paths:
+ return mask
+ fill_type = pyclipper.PFT_EVENODD if fill_rule == "evenodd" else pyclipper.PFT_NONZERO
+ try:
+ clipper = pyclipper.Pyclipper()
+ clipper.AddPaths(paths, pyclipper.PT_SUBJECT, True)
+ tree = clipper.Execute2(pyclipper.CT_UNION, fill_type, fill_type)
+ except pyclipper.ClipperException as exc:
+ raise MetafileMalformedError("compound path cannot be resolved") from exc
+ _paint_polytree(mask, tree, budget)
+ return mask
+
+
+def _clip_mask(
+ clip: ClipStack,
+ matrix: Matrix,
+ size: tuple[int, int],
+ budget: FlattenBudget | None = None,
+) -> Image.Image | None:
+ """按 GDI combine mode 顺序合成最终裁剪 mask。"""
+ if not clip:
+ return None
+ current = Image.new("L", size, 255)
+ for operation in clip:
+ incoming = _path_mask(operation.path, matrix, size, operation.fill_rule, budget)
+ if operation.mode == "copy":
+ current = incoming
+ elif operation.mode == "and":
+ current = ImageChops.multiply(current, incoming)
+ elif operation.mode == "or":
+ current = ImageChops.lighter(current, incoming)
+ elif operation.mode == "xor":
+ current = ImageChops.logical_xor(current.convert("1"), incoming.convert("1")).convert("L")
+ else:
+ current = ImageChops.subtract(current, incoming)
+ return current
+
+
+def _apply_clip(layer: Image.Image, clip: ClipStack, matrix: Matrix, budget: FlattenBudget | None = None) -> None:
+ """把命令级裁剪 mask 乘入 RGBA layer 的 alpha 通道。"""
+ mask = _clip_mask(clip, matrix, layer.size, budget)
+ if mask is None:
+ return
+ alpha = layer.getchannel("A")
+ layer.putalpha(ImageChops.multiply(alpha, mask))
+
+
+def _hatch_layer(size: tuple[int, int], brush: Brush) -> Image.Image:
+ """为常见 GDI hatch brush 生成确定性 RGBA 图案层。"""
+ layer = Image.new("RGBA", size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(layer)
+ color = brush.color.rgba()
+ spacing = 8
+ width, height = size
+ if brush.hatch in {0, 4, 5}:
+ for y in range(0, height + spacing, spacing):
+ draw.line((0, y, width, y), fill=color)
+ if brush.hatch in {1, 4, 5}:
+ for x in range(0, width + spacing, spacing):
+ draw.line((x, 0, x, height), fill=color)
+ if brush.hatch in {2, 4}:
+ for offset in range(-height, width + height, spacing):
+ draw.line((offset, 0, offset + height, height), fill=color)
+ if brush.hatch in {3, 5}:
+ for offset in range(0, width + height * 2, spacing):
+ draw.line((offset, 0, offset - height, height), fill=color)
+ return layer
+
+
+def _dash_polyline(
+ points: list[Point],
+ *,
+ dashes: tuple[float, ...],
+ closed: bool,
+) -> list[list[Point]]:
+ """按连续路径长度把折线切分为需要描绘的 dash 子段。"""
+ if len(points) < 2:
+ return []
+ if not dashes:
+ return [points]
+ pattern = tuple(max(0.5, value) for value in dashes)
+ pattern_index = 0
+ pattern_remaining = pattern[0]
+ drawing = True
+ visible: list[list[Point]] = []
+ current: list[Point] | None = None
+ for start, end in zip(points, points[1:]):
+ delta_x, delta_y = end[0] - start[0], end[1] - start[1]
+ length = hypot(delta_x, delta_y)
+ if length <= 1e-9:
+ continue
+ consumed = 0.0
+ while consumed < length:
+ advance = min(pattern_remaining, length - consumed)
+ if drawing and advance > 0:
+ first = (
+ start[0] + delta_x * consumed / length,
+ start[1] + delta_y * consumed / length,
+ )
+ second = (
+ start[0] + delta_x * (consumed + advance) / length,
+ start[1] + delta_y * (consumed + advance) / length,
+ )
+ if current is None:
+ current = [first]
+ elif current[-1] != first:
+ current.append(first)
+ current.append(second)
+ consumed += advance
+ pattern_remaining -= advance
+ if pattern_remaining <= 1e-9:
+ if drawing and current is not None:
+ visible.append(current)
+ current = None
+ pattern_index = (pattern_index + 1) % len(pattern)
+ pattern_remaining = pattern[pattern_index]
+ drawing = not drawing
+ if current is not None:
+ visible.append(current)
+ if closed and len(visible) > 1 and visible[0][0] == points[0] and visible[-1][-1] == points[-1]:
+ visible[0] = [*visible[-1][:-1], *visible[0]]
+ visible.pop()
+ return visible
+
+
+def _quantize_stroke_path(points: list[Point], *, closed: bool) -> list[tuple[int, int]]:
+ """把描边折线量化为 Clipper 坐标并移除重复端点。"""
+ converted: list[tuple[int, int]] = []
+ for x, y in points:
+ if abs(x) > _CLIPPER_COORD_LIMIT or abs(y) > _CLIPPER_COORD_LIMIT:
+ raise MetafileResourceLimitError("stroke coordinate exceeds Clipper range")
+ point = round(x * _CLIPPER_SCALE), round(y * _CLIPPER_SCALE)
+ if not converted or converted[-1] != point:
+ converted.append(point)
+ if closed and len(converted) > 1 and converted[0] == converted[-1]:
+ converted.pop()
+ return converted
+
+
+def _offset_stroke_path(
+ points: list[Point],
+ *,
+ closed: bool,
+ width: float,
+ pen: Pen,
+ miter_limit: float,
+ size: tuple[int, int],
+ budget: FlattenBudget,
+) -> Image.Image:
+ """把单条折线扩张成遵守 GDI cap、join 和 miter limit 的描边 mask。"""
+ mask = Image.new("L", size, 0)
+ converted = _quantize_stroke_path(points, closed=closed)
+ if len(converted) < (3 if closed else 2):
+ return mask
+ join_type = {
+ "round": pyclipper.JT_ROUND,
+ "bevel": pyclipper.JT_SQUARE,
+ "miter": pyclipper.JT_MITER,
+ }[pen.join]
+ end_type = (
+ pyclipper.ET_CLOSEDLINE
+ if closed
+ else {
+ "round": pyclipper.ET_OPENROUND,
+ "square": pyclipper.ET_OPENSQUARE,
+ "flat": pyclipper.ET_OPENBUTT,
+ }[pen.cap]
+ )
+ try:
+ offset = pyclipper.PyclipperOffset(max(miter_limit, 1.0), _CLIPPER_SCALE * 0.1)
+ offset.AddPath(converted, join_type, end_type)
+ tree = offset.Execute2(max(width, 1.0) * _CLIPPER_SCALE / 2.0)
+ except pyclipper.ClipperException as exc:
+ raise MetafileMalformedError("stroke path cannot be widened") from exc
+ _paint_polytree(mask, tree, budget)
+ return mask
+
+
+def _stroke_mask(
+ subpaths: list[tuple[list[Point], bool]],
+ *,
+ size: tuple[int, int],
+ width: float,
+ pen: Pen,
+ dashes: tuple[float, ...],
+ miter_limit: float,
+ budget: FlattenBudget,
+) -> Image.Image:
+ """把全部描边子路径合成为统一 L 模式覆盖 mask。"""
+ mask = Image.new("L", size, 0)
+ for points, closed in subpaths:
+ visible = _dash_polyline(points, dashes=dashes, closed=closed)
+ for segment in visible:
+ segment_closed = closed and not dashes
+ current = _offset_stroke_path(
+ segment,
+ closed=segment_closed,
+ width=width,
+ pen=pen,
+ miter_limit=miter_limit,
+ size=size,
+ budget=budget,
+ )
+ mask = ImageChops.lighter(mask, current)
+ return mask
+
+
+def _render_path_command(
+ command: DrawPathCommand,
+ matrix: Matrix,
+ size: tuple[int, int],
+ raster_scale: int,
+ budget: FlattenBudget,
+) -> Image.Image:
+ """把单条路径命令绘制到独立透明 RGBA layer。"""
+ layer = Image.new("RGBA", size, (0, 0, 0, 0))
+ transformed = transform_path(command.path, matrix)
+ subpaths = flatten_path(transformed, budget=budget)
+ if command.fill and command.brush.kind != "null":
+ fill_mask = _path_mask(command.path, matrix, size, command.fill_rule, budget)
+ if command.brush.kind == "hatch":
+ fill_layer = _hatch_layer(size, command.brush)
+ fill_layer.putalpha(ImageChops.multiply(fill_layer.getchannel("A"), fill_mask))
+ else:
+ fill_layer = Image.new("RGBA", size, command.brush.color.rgba())
+ fill_layer.putalpha(ImageChops.multiply(fill_layer.getchannel("A"), fill_mask))
+ layer.alpha_composite(fill_layer)
+ if command.stroke and not command.pen.null:
+ scale = (abs(matrix.a) + abs(matrix.d)) / 2.0
+ pen_width = command.pen.width * raster_scale if command.pen.cosmetic else command.pen.width * max(scale, 1e-9)
+ width = max(1.0, min(pen_width, max(size) * 2.0))
+ dash_scale = raster_scale if command.pen.cosmetic else scale
+ stroke_mask = _stroke_mask(
+ subpaths,
+ size=size,
+ width=width,
+ pen=command.pen,
+ dashes=tuple(value * dash_scale for value in command.pen.dashes),
+ miter_limit=command.miter_limit,
+ budget=budget,
+ )
+ stroke_layer = Image.new("RGBA", size, command.pen.color.rgba())
+ stroke_layer.putalpha(ImageChops.multiply(stroke_layer.getchannel("A"), stroke_mask))
+ layer.alpha_composite(stroke_layer)
+ _apply_clip(layer, command.clip, matrix, budget)
+ return layer
+
+
+def _text_anchor(text_align: int) -> str:
+ """把 GDI TextAlignmentMode 转换为 Pillow anchor。"""
+ horizontal = "r" if text_align & _TA_CENTER == _TA_CENTER else "r" if text_align & _TA_RIGHT else "l"
+ if text_align & _TA_CENTER == _TA_CENTER:
+ horizontal = "m"
+ vertical = "s" if text_align & _TA_BASELINE == _TA_BASELINE else "d" if text_align & _TA_BOTTOM else "a"
+ return horizontal + vertical
+
+
+def _draw_rotated_text(
+ layer: Image.Image,
+ position: Point,
+ text: str,
+ *,
+ font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
+ fill: tuple[int, int, int, int],
+ anchor: str,
+ rotation: float,
+) -> tuple[int, int]:
+ """在指定 anchor 绘制可旋转文字,并返回未旋转文字尺寸。"""
+ draw = ImageDraw.Draw(layer)
+ bbox = draw.textbbox((0, 0), text, font=font, anchor=anchor)
+ width = max(1, bbox[2] - bbox[0])
+ height = max(1, bbox[3] - bbox[1])
+ if abs(rotation) < 1e-6:
+ draw.text(position, text, font=font, fill=fill, anchor=anchor)
+ return width, height
+ padding = max(4, ceil(max(width, height) * 0.1))
+ patch = Image.new("RGBA", (width + padding * 2, height + padding * 2), (0, 0, 0, 0))
+ patch_draw = ImageDraw.Draw(patch)
+ patch_draw.text((padding - bbox[0], padding - bbox[1]), text, font=font, fill=fill)
+ rotated = patch.rotate(-rotation, expand=True, resample=Image.Resampling.BICUBIC)
+ target = round(position[0] - rotated.width / 2), round(position[1] - rotated.height / 2)
+ layer.alpha_composite(rotated, target)
+ return width, height
+
+
+def _render_text_command(
+ command: DrawTextCommand,
+ matrix: Matrix,
+ size: tuple[int, int],
+ budget: FlattenBudget,
+) -> Image.Image:
+ """把单条文字命令绘制到独立透明 RGBA layer。"""
+ layer = Image.new("RGBA", size, (0, 0, 0, 0))
+ scale_y = max(abs(matrix.d), 1e-9)
+ font_size = max(1, round(command.font_height * scale_y))
+ font = _load_font(command.font.face_name, font_size, command.font.weight, command.font.italic, command.font.charset)
+ anchor = _text_anchor(command.text_align)
+ positions = (
+ [matrix.transform_point(position) for position in command.positions]
+ if command.positions
+ else [matrix.transform_point(command.origin)]
+ )
+ texts = tuple(command.text) if command.positions else (command.text,)
+ if command.opaque:
+ draw = ImageDraw.Draw(layer)
+ if command.bounds is not None:
+ rect = _mapped_rect(command.bounds, matrix).normalized()
+ background_bounds = rect.left, rect.top, rect.right, rect.bottom
+ else:
+ text_bounds = [draw.textbbox(position, text, font=font, anchor=anchor) for position, text in zip(positions, texts)]
+ background_bounds = (
+ min(bounds[0] for bounds in text_bounds),
+ min(bounds[1] for bounds in text_bounds),
+ max(bounds[2] for bounds in text_bounds),
+ max(bounds[3] for bounds in text_bounds),
+ )
+ draw.rectangle(background_bounds, fill=command.background_color.rgba())
+ if command.positions:
+ sizes: list[tuple[int, int]] = []
+ for position, character in zip(positions, command.text):
+ sizes.append(
+ _draw_rotated_text(
+ layer,
+ position,
+ character,
+ font=font,
+ fill=command.color.rgba(),
+ anchor=anchor,
+ rotation=command.rotation,
+ )
+ )
+ else:
+ position = positions[0]
+ sizes = [
+ _draw_rotated_text(
+ layer,
+ position,
+ command.text,
+ font=font,
+ fill=command.color.rgba(),
+ anchor=anchor,
+ rotation=command.rotation,
+ )
+ ]
+ if (command.font.underline or command.font.strikeout) and positions:
+ draw = ImageDraw.Draw(layer)
+ width = sizes[-1][0] if sizes else font_size
+ for position in positions:
+ if command.font.underline:
+ y = position[1] + max(1, font_size * 0.1)
+ draw.line((position[0], y, position[0] + width, y), fill=command.color.rgba(), width=max(1, font_size // 14))
+ if command.font.strikeout:
+ y = position[1] - font_size * 0.3
+ draw.line((position[0], y, position[0] + width, y), fill=command.color.rgba(), width=max(1, font_size // 14))
+ _apply_clip(layer, command.clip, matrix, budget)
+ return layer
+
+
+def _crop_source(image: Image.Image, source: Rect | None) -> Image.Image:
+ """按 GDI source rect 裁剪位图,并兼容负宽高翻转。"""
+ if source is None:
+ return image
+ flip_x = source.width < 0
+ flip_y = source.height < 0
+ normalized = source.normalized()
+ left = max(0, floor(normalized.left))
+ top = max(0, floor(normalized.top))
+ right = min(image.width, ceil(normalized.right))
+ bottom = min(image.height, ceil(normalized.bottom))
+ if right <= left or bottom <= top:
+ return image
+ cropped = image.crop((left, top, right, bottom))
+ if flip_x:
+ cropped = cropped.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
+ if flip_y:
+ cropped = cropped.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
+ return cropped
+
+
+def _affine_image_layer(
+ image: Image.Image,
+ destination: tuple[Point, Point, Point, Point],
+ matrix: Matrix,
+ size: tuple[int, int],
+ stretch_mode: int,
+) -> Image.Image:
+ """把源图片仿射映射到目标平行四边形。"""
+ first, second, _third, fourth = (matrix.transform_point(point) for point in destination)
+ axis_x = second[0] - first[0], second[1] - first[1]
+ axis_y = fourth[0] - first[0], fourth[1] - first[1]
+ determinant = axis_x[0] * axis_y[1] - axis_x[1] * axis_y[0]
+ if abs(determinant) < 1e-9:
+ return Image.new("RGBA", size, (0, 0, 0, 0))
+ inverse_00 = axis_y[1] / determinant
+ inverse_01 = -axis_y[0] / determinant
+ inverse_10 = -axis_x[1] / determinant
+ inverse_11 = axis_x[0] / determinant
+ scale_x = image.width
+ scale_y = image.height
+ a = inverse_00 * scale_x
+ b = inverse_01 * scale_x
+ c = -(inverse_00 * first[0] + inverse_01 * first[1]) * scale_x
+ d = inverse_10 * scale_y
+ e = inverse_11 * scale_y
+ f = -(inverse_10 * first[0] + inverse_11 * first[1]) * scale_y
+ resample = Image.Resampling.BICUBIC if stretch_mode == 4 else Image.Resampling.NEAREST
+ return image.transform(
+ size,
+ Image.Transform.AFFINE,
+ (a, b, c, d, e, f),
+ resample=resample,
+ fillcolor=(0, 0, 0, 0),
+ )
+
+
+def _render_image_command(
+ command: DrawImageCommand,
+ matrix: Matrix,
+ size: tuple[int, int],
+ budget: FlattenBudget,
+) -> Image.Image:
+ """解码、裁剪并仿射放置单条位图命令。"""
+ image = _crop_source(_decode_dib(command), command.source)
+ if command.constant_alpha < 255:
+ alpha = image.getchannel("A").point(lambda value: value * command.constant_alpha // 255)
+ image.putalpha(alpha)
+ layer = _affine_image_layer(image, command.destination, matrix, size, command.stretch_mode)
+ _apply_clip(layer, command.clip, matrix, budget)
+ return layer
+
+
+def _bitwise_channel_bytes(destination: bytes, source: bytes, operation: str) -> bytes:
+ """对等长 RGB 字节串执行精确 AND、OR、XOR 或反相。"""
+ if operation == "xor":
+ return bytes(left ^ right for left, right in zip(destination, source))
+ if operation == "and":
+ return bytes(left & right for left, right in zip(destination, source))
+ if operation == "or":
+ return bytes(left | right for left, right in zip(destination, source))
+ if operation == "not_or":
+ return bytes((~(left | right)) & 0xFF for left, right in zip(destination, source))
+ if operation == "and_not_source":
+ return bytes(left & (~right & 0xFF) for left, right in zip(destination, source))
+ if operation == "not_source":
+ return bytes(255 - value for value in source)
+ if operation == "source_and_not_destination":
+ return bytes(right & (~left & 0xFF) for left, right in zip(destination, source))
+ if operation == "not_and":
+ return bytes((~(left & right)) & 0xFF for left, right in zip(destination, source))
+ if operation == "not_xor":
+ return bytes((~(left ^ right)) & 0xFF for left, right in zip(destination, source))
+ if operation == "destination_or_not_source":
+ return bytes(left | (~right & 0xFF) for left, right in zip(destination, source))
+ if operation == "source_or_not_destination":
+ return bytes(right | (~left & 0xFF) for left, right in zip(destination, source))
+ if operation == "invert":
+ return bytes(255 - value for value in destination)
+ fill = 0 if operation == "black" else 255
+ return bytes([fill]) * len(destination)
+
+
+def _paste_bitwise(canvas: Image.Image, layer: Image.Image, operation: str) -> None:
+ """只在 layer 覆盖框内应用精确逐通道 GDI 逻辑合成。"""
+ mask = layer.getchannel("A")
+ bbox = mask.getbbox()
+ if bbox is None:
+ return
+ destination = canvas.crop(bbox).convert("RGB")
+ source = layer.crop(bbox).convert("RGB")
+ result = Image.frombytes(
+ "RGB",
+ destination.size,
+ _bitwise_channel_bytes(destination.tobytes(), source.tobytes(), operation),
+ ).convert("RGBA")
+ local_mask = mask.crop(bbox)
+ result.putalpha(ImageChops.lighter(canvas.getchannel("A").crop(bbox), local_mask))
+ canvas.paste(result, bbox[:2], local_mask)
+
+
+def _composite_path(canvas: Image.Image, layer: Image.Image, rop2: int) -> None:
+ """按常见 ROP2 或默认 source-over 合成路径层。"""
+ operations = {
+ 1: "black",
+ 2: "not_or",
+ 3: "and_not_source",
+ 4: "not_source",
+ 5: "source_and_not_destination",
+ 6: "invert",
+ 7: "xor",
+ 8: "not_and",
+ 9: "and",
+ 10: "not_xor",
+ 12: "destination_or_not_source",
+ 14: "source_or_not_destination",
+ 15: "or",
+ 16: "white",
+ }
+ if rop2 == 13:
+ canvas.alpha_composite(layer)
+ elif rop2 != 11:
+ _paste_bitwise(canvas, layer, operations.get(rop2, "xor"))
+
+
+def _composite_image(canvas: Image.Image, layer: Image.Image, rop: int) -> None:
+ """按常见 ROP3 或 AlphaBlend 结果合成位图层。"""
+ if rop in {_SRCCOPY, 0}:
+ canvas.alpha_composite(layer)
+ elif rop == _SRCAND:
+ _paste_bitwise(canvas, layer, "and")
+ elif rop == _SRCPAINT:
+ _paste_bitwise(canvas, layer, "or")
+ elif rop == _SRCINVERT:
+ _paste_bitwise(canvas, layer, "xor")
+ elif rop == _DSTINVERT:
+ _paste_bitwise(canvas, layer, "invert")
+ elif rop == _BLACKNESS:
+ _paste_bitwise(canvas, layer, "black")
+ elif rop == _WHITENESS:
+ _paste_bitwise(canvas, layer, "white")
+ else:
+ canvas.alpha_composite(layer)
+
+
+def _supersample_factor(document: MetafileDocument) -> int:
+ """在画布、工作量预算内为纯矢量文档选择 1×、2× 或 4×。"""
+ if any(isinstance(command, DrawImageCommand) for command in document.commands):
+ return 1
+ command_count = max(len(document.commands), 1)
+ for factor in (4, 2):
+ width = document.width * factor
+ height = document.height * factor
+ if (
+ width <= 8192
+ and height <= 8192
+ and width * height <= MAX_CANVAS_PIXELS
+ and width * height * command_count <= MAX_RENDER_WORK_PIXELS
+ ):
+ return factor
+ return 1
+
+
+def _render_pillow_once(document: MetafileDocument, raster_scale: int) -> Image.Image:
+ """按给定整数倍率执行一次不缩放的 Pillow 栅格化。"""
+ width = document.width * raster_scale
+ height = document.height * raster_scale
+ render_work = width * height * max(len(document.commands), 1)
+ if render_work > MAX_RENDER_WORK_PIXELS:
+ raise MetafileResourceLimitError(f"metafile exceeds max_render_work_pixels={MAX_RENDER_WORK_PIXELS}")
+ matrix = _document_matrix(document, raster_scale=raster_scale)
+ size = width, height
+ canvas = Image.new("RGBA", size, (255, 255, 255, 0))
+ budget = FlattenBudget()
+ for command in document.commands:
+ if isinstance(command, DrawPathCommand):
+ _composite_path(canvas, _render_path_command(command, matrix, size, raster_scale, budget), command.rop2)
+ elif isinstance(command, DrawTextCommand):
+ canvas.alpha_composite(_render_text_command(command, matrix, size, budget))
+ else:
+ _composite_image(canvas, _render_image_command(command, matrix, size, budget), command.rop)
+ return canvas
+
+
+def render_pillow(document: MetafileDocument) -> Image.Image:
+ """把统一图元文档以自适应超采样渲染为最终尺寸 RGBA 图片。"""
+ raster_scale = _supersample_factor(document)
+ canvas = _render_pillow_once(document, raster_scale)
+ if raster_scale == 1:
+ return canvas
+ resized = canvas.resize((document.width, document.height), Image.Resampling.LANCZOS)
+ return resized.filter(ImageFilter.UnsharpMask(radius=0.6, percent=100, threshold=2))
+
+
+def _svg_number(value: float) -> str:
+ """以稳定且紧凑的形式序列化 SVG 浮点数。"""
+ rounded = round(value, 4)
+ if rounded == int(rounded):
+ return str(int(rounded))
+ return f"{rounded:.4f}".rstrip("0").rstrip(".")
+
+
+def _svg_path_data(path: GraphicsPath, matrix: Matrix) -> str:
+ """把统一路径转换为安全 SVG path data。"""
+ parts: list[str] = []
+ for segment in transform_path(path, matrix).segments:
+ if segment.verb == "Z":
+ parts.append("Z")
+ continue
+ coordinates = " ".join(f"{_svg_number(point[0])} {_svg_number(point[1])}" for point in segment.points)
+ parts.append(f"{segment.verb} {coordinates}")
+ return " ".join(parts)
+
+
+def _svg_opacity(color: Color) -> str:
+ """返回仅在颜色半透明时需要的 SVG opacity 属性。"""
+ return "" if color.alpha == 255 else f' opacity="{_svg_number(color.alpha / 255.0)}"'
+
+
+def _svg_pen_attributes(pen: Pen, matrix: Matrix, miter_limit: float) -> str:
+ """把内部 Pen 转换为 SVG stroke 属性。"""
+ if pen.null:
+ return 'stroke="none"'
+ scale = (abs(matrix.a) + abs(matrix.d)) / 2.0
+ width = pen.width if pen.cosmetic else pen.width * max(scale, 1e-9)
+ attributes = [
+ f'stroke="{pen.color.svg()}"',
+ f'stroke-width="{_svg_number(max(width, 1.0))}"',
+ f'stroke-linecap="{pen.cap}"',
+ f'stroke-linejoin="{pen.join}"',
+ f'stroke-miterlimit="{_svg_number(max(miter_limit, 1.0))}"',
+ ]
+ if pen.color.alpha != 255:
+ attributes.append(f'stroke-opacity="{_svg_number(pen.color.alpha / 255.0)}"')
+ if pen.dashes:
+ dash_scale = 1.0 if pen.cosmetic else scale
+ attributes.append(f'stroke-dasharray="{" ".join(_svg_number(value * dash_scale) for value in pen.dashes)}"')
+ return " ".join(attributes)
+
+
+def _svg_brush_attributes(brush: Brush) -> str:
+ """把内部 Brush 转换为基础 SVG fill 属性。"""
+ if brush.kind == "null":
+ return 'fill="none"'
+ attributes = [f'fill="{brush.color.svg()}"']
+ if brush.color.alpha != 255:
+ attributes.append(f'fill-opacity="{_svg_number(brush.color.alpha / 255.0)}"')
+ return " ".join(attributes)
+
+
+def _svg_clip_definitions(document: MetafileDocument, matrix: Matrix) -> tuple[list[str], dict[ClipOperation, str]]:
+ """为只含 copy/and 的裁剪路径生成确定性 clipPath 定义。"""
+ definitions: list[str] = []
+ identifiers: dict[ClipOperation, str] = {}
+ ordinal = 0
+ for command in document.commands:
+ for operation in command.clip:
+ if operation in identifiers:
+ continue
+ ordinal += 1
+ identifier = f"mineru-clip-{ordinal}"
+ identifiers[operation] = identifier
+ definitions.append(
+ f'<clipPath id="{identifier}"><path d="{_svg_path_data(operation.path, matrix)}" '
+ f'fill-rule="{operation.fill_rule}"/></clipPath>'
+ )
+ return definitions, identifiers
+
+
+def _wrap_svg_clip(element: str, clip: ClipStack, identifiers: dict[ClipOperation, str]) -> str:
+ """按裁剪顺序用嵌套 SVG group 包裹单个图元。"""
+ wrapped = element
+ active: list[ClipOperation] = []
+ for operation in clip:
+ if operation.mode == "copy":
+ active = [operation]
+ elif operation.mode == "and":
+ active.append(operation)
+ for operation in reversed(active):
+ wrapped = f'<g clip-path="url(#{identifiers[operation]})">{wrapped}</g>'
+ return wrapped
+
+
+def _svg_text_anchor(text_align: int) -> tuple[str, str]:
+ """把 GDI 文字对齐转换为 SVG anchor 和 baseline。"""
+ horizontal = "middle" if text_align & _TA_CENTER == _TA_CENTER else "end" if text_align & _TA_RIGHT else "start"
+ vertical = (
+ "alphabetic"
+ if text_align & _TA_BASELINE == _TA_BASELINE
+ else "text-after-edge"
+ if text_align & _TA_BOTTOM
+ else "hanging"
+ )
+ return horizontal, vertical
+
+
+def _svg_text_elements(command: DrawTextCommand, matrix: Matrix) -> str:
+ """把统一文字命令转换为一个或多个安全 SVG text 元素。"""
+ anchor, baseline = _svg_text_anchor(command.text_align)
+ scale_y = max(abs(matrix.d), 1e-9)
+ font_size = max(1.0, command.font_height * scale_y)
+ decorations = []
+ if command.font.underline:
+ decorations.append("underline")
+ if command.font.strikeout:
+ decorations.append("line-through")
+ decoration_attr = f' text-decoration="{" ".join(decorations)}"' if decorations else ""
+ common = (
+ f'fill="{command.color.svg()}"{_svg_opacity(command.color)} '
+ f'font-family="{escape(command.font.face_name, quote=True)}" font-size="{_svg_number(font_size)}" '
+ f'font-weight="{command.font.weight}" font-style="{"italic" if command.font.italic else "normal"}" '
+ f'text-anchor="{anchor}" dominant-baseline="{baseline}"{decoration_attr}'
+ )
+ elements: list[str] = []
+ positions = command.positions or (command.origin,)
+ texts = tuple(command.text) if command.positions else (command.text,)
+ mapped_positions = tuple(matrix.transform_point(position) for position in positions)
+ for mapped, text in zip(mapped_positions, texts):
+ transform = ""
+ if abs(command.rotation) > 1e-6:
+ transform = (
+ f' transform="rotate({_svg_number(command.rotation)} {_svg_number(mapped[0])} {_svg_number(mapped[1])})"'
+ )
+ elements.append(
+ f'<text x="{_svg_number(mapped[0])}" y="{_svg_number(mapped[1])}" {common}{transform}>{escape(text)}</text>'
+ )
+ background = ""
+ if command.opaque:
+ if command.bounds is not None:
+ rect = _mapped_rect(command.bounds, matrix).normalized()
+ else:
+ approximate_widths = tuple(max(font_size * 0.6 * len(text), font_size * 0.25) for text in texts)
+ left = min(position[0] for position in mapped_positions)
+ right = max(position[0] + width for position, width in zip(mapped_positions, approximate_widths))
+ top = min(position[1] - font_size for position in mapped_positions)
+ bottom = max(position[1] + font_size * 0.25 for position in mapped_positions)
+ rect = Rect(left, top, right, bottom)
+ background = (
+ f'<rect x="{_svg_number(rect.left)}" y="{_svg_number(rect.top)}" width="{_svg_number(rect.width)}" '
+ f'height="{_svg_number(rect.height)}" fill="{command.background_color.svg()}"'
+ f"{_svg_opacity(command.background_color)}/>"
+ )
+ return background + "".join(elements)
+
+
+def _svg_image_element(command: DrawImageCommand, matrix: Matrix) -> str:
+ """把 DIB 转成内嵌 PNG 并以 SVG affine matrix 放置。"""
+ image = _crop_source(_decode_dib(command), command.source)
+ if command.constant_alpha < 255:
+ image.putalpha(image.getchannel("A").point(lambda value: value * command.constant_alpha // 255))
+ output = BytesIO()
+ image.save(output, format="PNG")
+ encoded = base64.b64encode(output.getvalue()).decode("ascii")
+ first, second, _third, fourth = (matrix.transform_point(point) for point in command.destination)
+ a = (second[0] - first[0]) / max(image.width, 1)
+ b = (second[1] - first[1]) / max(image.width, 1)
+ c = (fourth[0] - first[0]) / max(image.height, 1)
+ d = (fourth[1] - first[1]) / max(image.height, 1)
+ transform = " ".join(_svg_number(value) for value in (a, b, c, d, first[0], first[1]))
+ return (
+ f'<image width="{image.width}" height="{image.height}" transform="matrix({transform})" '
+ f'href="data:image/png;base64,{encoded}"/>'
+ )
+
+
+def _svg_requires_raster(document: MetafileDocument) -> bool:
+ """判断 SVG 是否需要用整图 PNG 包装保留复杂合成语义。"""
+ for command in document.commands:
+ if any(operation.mode not in {"copy", "and"} for operation in command.clip):
+ return True
+ if isinstance(command, DrawPathCommand) and command.rop2 != 13:
+ return True
+ if isinstance(command, DrawImageCommand) and command.rop not in {_SRCCOPY, 0}:
+ return True
+ return False
+
+
+def _svg_fallback_scale(document: MetafileDocument) -> int:
+ """为纯矢量 SVG fallback 选择最高 8× 的安全像素密度。"""
+ if any(isinstance(command, DrawImageCommand) for command in document.commands):
+ return 1
+ command_count = max(len(document.commands), 1)
+ for factor in (8, 4, 2):
+ width = document.width * factor
+ height = document.height * factor
+ if (
+ width <= 8192
+ and height <= 8192
+ and width * height <= MAX_CANVAS_PIXELS
+ and width * height * command_count <= MAX_RENDER_WORK_PIXELS
+ ):
+ return factor
+ return 1
+
+
+def _png_fallback_bytes(document: MetafileDocument, *, pixel_scale: int = 1) -> bytes:
+ """生成指定像素密度、带对应 DPI metadata 的 PNG fallback。"""
+ image = render_pillow(document) if pixel_scale == 1 else _render_pillow_once(document, pixel_scale)
+ output = BytesIO()
+ image.save(output, format="PNG", dpi=(96 * pixel_scale, 96 * pixel_scale))
+ return output.getvalue()
+
+
+def _svg_fallback_metadata(encoded_png: str) -> str:
+ """生成带固定标识的不可见 PNG fallback metadata。"""
+ return f'<metadata id="mineru-raster-fallback" data-mime="image/png">{encoded_png}</metadata>'
+
+
+def _raster_wrapped_svg(document: MetafileDocument) -> bytes:
+ """把 Pillow 结果封装为没有外部引用的单图片 SVG。"""
+ encoded = base64.b64encode(_png_fallback_bytes(document)).decode("ascii")
+ markup = (
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{document.width}" height="{document.height}" '
+ f'viewBox="0 0 {document.width} {document.height}" data-mineru-generated="wmf-emf">'
+ f"{_svg_fallback_metadata(encoded)}"
+ f'<image width="{document.width}" height="{document.height}" href="data:image/png;base64,{encoded}"/>'
+ "</svg>"
+ )
+ return markup.encode("utf-8")
+
+
+def render_svg(document: MetafileDocument) -> bytes:
+ """把统一图元文档渲染为安全、自包含 SVG 字节。"""
+ if _svg_requires_raster(document):
+ return _raster_wrapped_svg(document)
+ matrix = _document_matrix(document)
+ definitions, clip_ids = _svg_clip_definitions(document, matrix)
+ fallback_scale = _svg_fallback_scale(document)
+ fallback = base64.b64encode(_png_fallback_bytes(document, pixel_scale=fallback_scale)).decode("ascii")
+ elements: list[str] = []
+ for command in document.commands:
+ if isinstance(command, DrawPathCommand):
+ stroke = _svg_pen_attributes(command.pen, matrix, command.miter_limit) if command.stroke else 'stroke="none"'
+ fill = _svg_brush_attributes(command.brush) if command.fill else 'fill="none"'
+ element = f'<path d="{_svg_path_data(command.path, matrix)}" {stroke} {fill} fill-rule="{command.fill_rule}"/>'
+ elif isinstance(command, DrawTextCommand):
+ element = _svg_text_elements(command, matrix)
+ else:
+ element = _svg_image_element(command, matrix)
+ elements.append(_wrap_svg_clip(element, command.clip, clip_ids))
+ defs = f"<defs>{''.join(definitions)}</defs>" if definitions else ""
+ markup = (
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{document.width}" height="{document.height}" '
+ f'viewBox="0 0 {document.width} {document.height}" data-mineru-generated="wmf-emf">'
+ f"{_svg_fallback_metadata(fallback)}{defs}{''.join(elements)}</svg>"
+ )
+ return markup.encode("utf-8")
+
+
+def encode_document(document: MetafileDocument, output_format: MetafileOutputFormat) -> tuple[bytes, str]:
+ """按目标格式编码统一图元文档并返回 MIME。"""
+ if output_format == "svg":
+ return render_svg(document), "image/svg+xml"
+ if output_format == "png":
+ return _png_fallback_bytes(document), "image/png"
+ image = render_pillow(document)
+ output = BytesIO()
+ background = Image.new("RGB", image.size, (255, 255, 255))
+ background.paste(image.convert("RGB"), (0, 0), image.getchannel("A"))
+ background.save(output, format="JPEG", quality=90)
+ return output.getvalue(), "image/jpeg"
+
+
+__all__ = ["encode_document", "render_pillow", "render_svg"]
diff --git a/mineru/model/flash/office/ppt/parser.py b/mineru/model/flash/office/ppt/parser.py
index 1489be99..ed91cf0b 100644
--- a/mineru/model/flash/office/ppt/parser.py
+++ b/mineru/model/flash/office/ppt/parser.py
@@ -1493,6 +1493,7 @@ def _image_from_shape(
image.data,
part_name=f"picture.{image.extension}",
content_type=image.content_type,
+ render_size_emu=image.render_size_emu,
)
if not data_uri:
logger.warning(f"PPT_IMAGE_UNSUPPORTED: shape={shape.key}, type={image.content_type}")
diff --git a/mineru/model/flash/office/pptx/pptx_converter.py b/mineru/model/flash/office/pptx/pptx_converter.py
index 8d38671d..ea08b5bf 100644
--- a/mineru/model/flash/office/pptx/pptx_converter.py
+++ b/mineru/model/flash/office/pptx/pptx_converter.py
@@ -7,13 +7,12 @@ from typing import Any, BinaryIO, Final, Optional
from loguru import logger
from lxml import etree
-from PIL import Image
from pptx import Presentation, presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDER
from pptx.oxml.text import CT_TextLineBreak
from ..ooxml_chart import extract_chart_html_from_ooxml
-from ..image import PIL_IMAGE_LOAD_ERRORS, is_vector_image, serialize_vector_image_with_placeholder
+from ..image import serialize_office_image
from ..equation.image import (
OfficeImageEquationDecoder,
)
@@ -27,7 +26,6 @@ from .package_normalizer import normalize_pptx_package
from ..._shared.xycut import sort_entries
from .....types import BlockType
from ..rich_text import OfficeRichTextSegment, build_rich_text_from_segments, format_text_with_hyperlink
-from ..._shared.image import image_to_b64str
IGNORED_NOTES_PLACEHOLDER_TYPES: Final = {
PP_PLACEHOLDER.SLIDE_IMAGE,
@@ -904,7 +902,10 @@ class PptxConverter:
self.cur_page.append(image_block)
return
- img_base64 = self._serialize_picture_image_best_effort(image_bytes)
+ img_base64 = serialize_office_image(
+ image_bytes,
+ content_type=content_type,
+ )
if img_base64 is None:
return
@@ -927,32 +928,6 @@ class PptxConverter:
content_type=content_type,
)
- @classmethod
- def _serialize_picture_image_best_effort(cls, image_bytes: bytes) -> Optional[str]:
- """尽量序列化图片;损坏图片失败时降级跳过,避免中断整份 PPTX。"""
- try:
- return cls._serialize_picture_image(image_bytes)
- except PIL_IMAGE_LOAD_ERRORS as exc:
- logger.warning(f"Warning: image cannot be loaded by Pillow: {exc}")
- return None
-
- @staticmethod
- def _serialize_picture_image(image_bytes: bytes) -> str:
- """将单张 Pillow 支持的图片转为 Markdown 可用的 base64 字符串。"""
- pil_image = Image.open(BytesIO(image_bytes))
-
- if is_vector_image(pil_image):
- return serialize_vector_image_with_placeholder(pil_image)
-
- if pil_image.mode == "RGB":
- pil_image.load()
- return image_to_b64str(pil_image, image_format="JPEG")
-
- if pil_image.mode in {"RGBA", "LA"} or (pil_image.mode == "P" and "transparency" in pil_image.info):
- return image_to_b64str(pil_image.convert("RGBA"), image_format="PNG")
-
- return image_to_b64str(pil_image.convert("RGB"), image_format="JPEG")
-
@staticmethod
def _bytes_to_data_uri(image_bytes: bytes, content_type: str) -> str:
encoded = base64.b64encode(image_bytes).decode("utf-8")
diff --git a/mineru/model/flash/office/xls/parser.py b/mineru/model/flash/office/xls/parser.py
index 0d210266..a54d5d97 100644
--- a/mineru/model/flash/office/xls/parser.py
+++ b/mineru/model/flash/office/xls/parser.py
@@ -651,6 +651,7 @@ def _serialize_payload(payload: OfficeImagePayload) -> str | None:
payload.data,
part_name=f"picture.{payload.extension}",
content_type=payload.content_type,
+ render_size_emu=payload.render_size_emu,
)
diff --git a/mineru/model/flash/office/xlsx/xlsx_converter.py b/mineru/model/flash/office/xlsx/xlsx_converter.py
index 1ecc7f28..dbb998ed 100644
--- a/mineru/model/flash/office/xlsx/xlsx_converter.py
+++ b/mineru/model/flash/office/xlsx/xlsx_converter.py
@@ -13,8 +13,6 @@ from openpyxl import load_workbook
from openpyxl.drawing.image import Image as XlsImage
from openpyxl.utils.cell import range_to_tuple
from openpyxl.worksheet.worksheet import Worksheet
-from PIL import Image
-from ..image import is_vector_image, serialize_vector_image_with_placeholder
from ..image import serialize_office_image
from ..equation.image import (
OfficeImageEquationDecoder,
@@ -39,7 +37,6 @@ from .ooxml_ole import (
workbook_sheet_parts,
)
from .....types import BlockType
-from ..._shared.image import image_to_b64str
class XlsxConverter(SpreadsheetProjector):
@@ -712,19 +709,12 @@ class XlsxConverter(SpreadsheetProjector):
)
if latex:
return EQUATION_BOOKENDS.format(EQ=latex)
- with BytesIO(image_payload) as image_file:
- pil_image = Image.open(image_file)
- if is_vector_image(pil_image):
- img_base64 = serialize_vector_image_with_placeholder(pil_image)
- return rf'<img src="{img_base64}" />'
-
- pil_image.load()
-
- if pil_image.mode != "RGB":
- img_base64 = image_to_b64str(pil_image, image_format="PNG")
- else:
- img_base64 = image_to_b64str(pil_image, image_format="JPEG")
- return rf'<img src="{img_base64}" />'
+ img_base64 = serialize_office_image(
+ image_payload,
+ part_name=zip_target_path,
+ content_type=None,
+ )
+ return rf'<img src="{img_base64}" />' if img_base64 is not None else ""
except Exception as e:
logger.warning(f"读取单元格图片失败,image_id={image_id}, target={zip_target_path}, error={e}")
return ""
diff --git a/mineru/render/_internal/docx/assets.py b/mineru/render/_internal/docx/assets.py
index 8972ebd2..81832bf9 100644
--- a/mineru/render/_internal/docx/assets.py
+++ b/mineru/render/_internal/docx/assets.py
@@ -13,7 +13,11 @@ from PIL import Image, UnidentifiedImageError
from ...contracts import AssetResolver
from ....types import ImagePayloadBlock
-from ....utils.image_payload import parse_image_data_uri_strict, validate_image_sidecar_path
+from ....utils.image_payload import (
+ extract_mineru_generated_svg_fallback,
+ parse_image_data_uri_strict,
+ validate_image_sidecar_path,
+)
_PIL_FORMAT_EXTENSIONS = {
"BMP": "bmp",
@@ -43,6 +47,7 @@ class PreparedImage:
extension: str
width_px: int
height_px: int
+ svg_data: bytes | None = None
def prepare_block_image(
@@ -89,7 +94,18 @@ def prepare_image_bytes(
expected_extension = _normalize_extension(declared_extension)
if expected_extension == "svg" or _looks_like_svg(data):
- raise DocxAssetError("SVG images are not supported by the DOCX renderer")
+ try:
+ fallback, logical_width, logical_height = extract_mineru_generated_svg_fallback(data)
+ except ValueError as exc:
+ raise DocxAssetError("SVG images are not supported unless they are safely generated by MinerU") from exc
+ prepared = prepare_image_bytes(fallback, declared_extension="png")
+ return PreparedImage(
+ data=prepared.data,
+ extension=prepared.extension,
+ width_px=logical_width,
+ height_px=logical_height,
+ svg_data=data,
+ )
try:
with Image.open(BytesIO(data)) as image:
@@ -123,8 +139,6 @@ def _prepare_data_uri(data_uri: str) -> PreparedImage:
data, extension = parse_image_data_uri_strict(data_uri)
except ValueError as exc:
raise DocxAssetError(str(exc)) from exc
- if extension == "svg":
- raise DocxAssetError("SVG images are not supported by the DOCX renderer")
return prepare_image_bytes(data, declared_extension=extension)
diff --git a/mineru/render/_internal/docx/renderer.py b/mineru/render/_internal/docx/renderer.py
index 9e83c713..f184822d 100644
--- a/mineru/render/_internal/docx/renderer.py
+++ b/mineru/render/_internal/docx/renderer.py
@@ -14,6 +14,8 @@ from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_TAB_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
+from docx.opc.constants import RELATIONSHIP_TYPE as RT
+from docx.opc.part import Part
from docx.shared import Emu, Mm, Pt, Twips
from docx.table import _Cell
from docx.text.paragraph import Paragraph
@@ -94,6 +96,9 @@ from ....types import (
TitleBlockBase,
)
+_SVG_BLIP_NAMESPACE = "http://schemas.microsoft.com/office/drawing/2016/SVG/main"
+_SVG_BLIP_EXTENSION_URI = "{96DAC541-7B7A-43D3-8B79-37D633B846F1}"
+
_HTML_TABLE_RE = re.compile(r"<table\b", re.IGNORECASE)
_ANNOTATION_CAPTION_TYPES = {
BlockType.IMAGE_CAPTION,
@@ -475,6 +480,8 @@ class _DocxRenderer:
BytesIO(prepared.data),
width=Emu(max(1, desired_width)),
)
+ if prepared.svg_data is not None:
+ self._attach_native_svg(shape._inline, target_paragraph.part, prepared.svg_data)
description = sanitize_xml_text(
re.sub(r"\s+", " ", alt_text).strip()[:2048],
context=context,
@@ -482,6 +489,34 @@ class _DocxRenderer:
if description:
shape._inline.docPr.set("descr", description)
+ @staticmethod
+ def _attach_native_svg(inline: etree._Element, target_part: Part, svg_data: bytes) -> None:
+ """为 fallback PNG 的 a:blip 添加 Office 2016 原生 SVG relationship。"""
+ package = target_part.package
+ svg_part = Part(
+ package.next_partname("/word/media/image%d.svg"),
+ "image/svg+xml",
+ svg_data,
+ package,
+ )
+ relationship_id = target_part.relate_to(svg_part, RT.IMAGE)
+ blip = inline.find(f".//{qn('a:blip')}")
+ if blip is None:
+ raise ValueError("DOCX picture does not contain an a:blip element")
+ extension_list = blip.find(qn("a:extLst"))
+ if extension_list is None:
+ extension_list = OxmlElement("a:extLst")
+ blip.append(extension_list)
+ extension = OxmlElement("a:ext")
+ extension.set("uri", _SVG_BLIP_EXTENSION_URI)
+ svg_blip = etree.SubElement(
+ extension,
+ f"{{{_SVG_BLIP_NAMESPACE}}}svgBlip",
+ nsmap={"asvg": _SVG_BLIP_NAMESPACE},
+ )
+ svg_blip.set(qn("r:embed"), relationship_id)
+ extension_list.append(extension)
+
def _append_html_tables(
self,
markup: str,
diff --git a/mineru/render/_internal/html/sanitizer.py b/mineru/render/_internal/html/sanitizer.py
index 50d098bb..38c8aee4 100644
--- a/mineru/render/_internal/html/sanitizer.py
+++ b/mineru/render/_internal/html/sanitizer.py
@@ -10,7 +10,7 @@ from urllib.parse import quote, unquote, urlsplit
import nh3
from bs4 import BeautifulSoup, NavigableString, Tag
-from ....utils.image_payload import parse_image_data_uri_strict
+from ....utils.image_payload import extract_mineru_generated_svg_fallback, parse_image_data_uri_strict
_ALLOWED_TAGS = {
@@ -245,18 +245,19 @@ def _sanitize_absolute_image_url(source: str) -> str | None:
def _sanitize_raster_data_uri(source: str) -> str | None:
- """同时校验 MIME、base64 与文件签名,只接受受支持的栅格图。"""
+ """校验栅格图或 MinerU 生成的安全 SVG data URI。"""
match = _DATA_IMAGE_RE.fullmatch(source)
if match is None:
return None
- if match.group("mime").lower() == "image/svg+xml":
- return None
try:
- _, extension = parse_image_data_uri_strict(source)
+ payload, extension = parse_image_data_uri_strict(source)
except ValueError:
return None
if extension == "svg":
- return None
+ try:
+ extract_mineru_generated_svg_fallback(payload)
+ except ValueError:
+ return None
return source
diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.py
index e4f4b849..275460af 100644
--- a/mineru/utils/image_payload.py
+++ b/mineru/utils/image_payload.py
@@ -9,6 +9,48 @@ import re
import xml.etree.ElementTree as ElementTree
INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;\"']+);base64,([^\"']+)", re.DOTALL)
+_SVG_NAMESPACE = "http://www.w3.org/2000/svg"
+_MINERU_SVG_MARKER = "wmf-emf"
+_MINERU_SVG_FALLBACK_ID = "mineru-raster-fallback"
+_MAX_GENERATED_SVG_BYTES = 64 * 1024 * 1024
+_MAX_GENERATED_SVG_NODES = 100_000
+_SAFE_SVG_ATTRIBUTES: dict[str, set[str]] = {
+ "svg": {"width", "height", "viewBox", "data-mineru-generated"},
+ "metadata": {"id", "data-mime"},
+ "defs": set(),
+ "clipPath": {"id"},
+ "path": {
+ "d",
+ "fill",
+ "fill-rule",
+ "fill-opacity",
+ "opacity",
+ "stroke",
+ "stroke-width",
+ "stroke-linecap",
+ "stroke-linejoin",
+ "stroke-miterlimit",
+ "stroke-opacity",
+ "stroke-dasharray",
+ },
+ "g": {"clip-path"},
+ "image": {"width", "height", "transform", "href"},
+ "text": {
+ "x",
+ "y",
+ "fill",
+ "opacity",
+ "font-family",
+ "font-size",
+ "font-weight",
+ "font-style",
+ "text-anchor",
+ "dominant-baseline",
+ "text-decoration",
+ "transform",
+ },
+ "rect": {"x", "y", "width", "height", "fill", "opacity"},
+}
def normalize_image_extension(fmt: str) -> str:
@@ -61,6 +103,87 @@ def parse_image_data_uri_strict(data_uri: str) -> tuple[bytes, str]:
return payload, extension
+def _decode_png_data_uri(value: str) -> bytes:
+ """严格解码生成 SVG 内嵌的 PNG data URI。"""
+ match = re.fullmatch(r"data:image/png;base64,([A-Za-z0-9+/]*={0,2})", value)
+ if match is None:
+ raise ValueError("Generated SVG image href must contain a PNG data URI")
+ try:
+ payload = base64.b64decode(match.group(1), validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise ValueError("Generated SVG contains invalid PNG base64") from exc
+ if not payload.startswith(b"\x89PNG\r\n\x1a\n"):
+ raise ValueError("Generated SVG fallback does not contain a PNG")
+ return payload
+
+
+def _validate_generated_svg_attribute(tag: str, name: str, value: str) -> None:
+ """校验生成 SVG 属性只使用静态数值、颜色、本地 clip 或 PNG。"""
+ if name not in _SAFE_SVG_ATTRIBUTES[tag] or "\x00" in value or name.lower().startswith("on"):
+ raise ValueError(f"Generated SVG contains an unsafe attribute: {tag}.{name}")
+ normalized = value.strip().casefold()
+ if "javascript:" in normalized or "data:text" in normalized or "url(" in normalized and name != "clip-path":
+ raise ValueError(f"Generated SVG contains an unsafe attribute value: {tag}.{name}")
+ if name == "href":
+ _decode_png_data_uri(value)
+ elif name == "clip-path" and re.fullmatch(r"url\(#mineru-clip-\d+\)", value) is None:
+ raise ValueError("Generated SVG clip-path must reference a local MinerU clip")
+ elif name == "transform" and re.fullmatch(r"(?:matrix|rotate)\([0-9eE+.,\- ]+\)", value) is None:
+ raise ValueError("Generated SVG transform is outside the supported subset")
+ elif name == "d" and re.fullmatch(r"[MmLlCcZz0-9eE+.,\- ]*", value) is None:
+ raise ValueError("Generated SVG path data is outside the supported subset")
+
+
+def extract_mineru_generated_svg_fallback(payload: bytes) -> tuple[bytes, int, int]:
+ """验证 MinerU 生成 SVG,并返回 PNG fallback 与逻辑像素尺寸。"""
+ if not isinstance(payload, bytes) or not payload or len(payload) > _MAX_GENERATED_SVG_BYTES:
+ raise ValueError("Generated SVG payload is empty or exceeds its byte limit")
+ lowered_prefix = payload[:4096].lower()
+ if b"<!doctype" in lowered_prefix or b"<!entity" in lowered_prefix:
+ raise ValueError("Generated SVG must not contain a DTD or entity declaration")
+ try:
+ root = ElementTree.fromstring(payload)
+ except ElementTree.ParseError as exc:
+ raise ValueError("Generated SVG payload is not valid XML") from exc
+ if root.tag != f"{{{_SVG_NAMESPACE}}}svg" or root.get("data-mineru-generated") != _MINERU_SVG_MARKER:
+ raise ValueError("SVG is not marked as a MinerU generated metafile")
+ try:
+ width = int(root.get("width", ""))
+ height = int(root.get("height", ""))
+ except ValueError as exc:
+ raise ValueError("Generated SVG dimensions must be integers") from exc
+ if width <= 0 or height <= 0 or width > 8192 or height > 8192 or root.get("viewBox") != f"0 0 {width} {height}":
+ raise ValueError("Generated SVG dimensions or viewBox are outside the supported bounds")
+
+ fallback: bytes | None = None
+ node_count = 0
+ for element in root.iter():
+ node_count += 1
+ if node_count > _MAX_GENERATED_SVG_NODES:
+ raise ValueError("Generated SVG exceeds its node limit")
+ if not isinstance(element.tag, str) or not element.tag.startswith(f"{{{_SVG_NAMESPACE}}}"):
+ raise ValueError("Generated SVG contains a foreign namespace")
+ tag = element.tag.rsplit("}", 1)[-1]
+ if tag not in _SAFE_SVG_ATTRIBUTES:
+ raise ValueError(f"Generated SVG contains an unsupported element: {tag}")
+ for attribute_name, attribute_value in element.attrib.items():
+ if "}" in attribute_name:
+ raise ValueError("Generated SVG contains a namespaced attribute")
+ _validate_generated_svg_attribute(tag, attribute_name, attribute_value)
+ if element.tail and element.tail.strip():
+ raise ValueError("Generated SVG contains unexpected tail text")
+ if tag == "metadata":
+ if element.get("id") != _MINERU_SVG_FALLBACK_ID or element.get("data-mime") != "image/png" or fallback is not None:
+ raise ValueError("Generated SVG fallback metadata is invalid or duplicated")
+ encoded = (element.text or "").strip()
+ fallback = _decode_png_data_uri(f"data:image/png;base64,{encoded}")
+ elif tag != "text" and element.text and element.text.strip():
+ raise ValueError(f"Generated SVG element must not contain text: {tag}")
+ if fallback is None:
+ raise ValueError("Generated SVG does not contain a PNG fallback")
+ return fallback, width, height
+
+
def image_path_from_key(path_key: str, image_format: str = "JPEG") -> str:
"""复用旧裁图路径哈希规则,根据逻辑路径生成稳定图片文件名。"""
ext = normalize_image_extension(image_format)
diff --git a/tests/unittest/_metafile_test_utils.py b/tests/unittest/_metafile_test_utils.py
new file mode 100644
index 00000000..95f1f7d0
--- /dev/null
+++ b/tests/unittest/_metafile_test_utils.py
@@ -0,0 +1,299 @@
+"""构造确定性 WMF/EMF 测试载荷。"""
+
+from __future__ import annotations
+
+import struct
+
+
+def _pad4(data: bytes) -> bytes:
+ """把 EMF payload 填充到 4 字节边界。"""
+ return data + b"\x00" * (-len(data) % 4)
+
+
+def emf_record(record_type: int, payload: bytes = b"") -> bytes:
+ """构造带通用头部和 4 字节对齐的 EMF record。"""
+ aligned = _pad4(payload)
+ return struct.pack("<II", record_type, 8 + len(aligned)) + aligned
+
+
+def _emf_header(
+ total_bytes: int,
+ record_count: int,
+ *,
+ bounds: tuple[int, int, int, int],
+ frame: tuple[int, int, int, int],
+) -> bytes:
+ """构造满足 EMR_HEADER 基础版本的 88 字节头部。"""
+ header = bytearray(88)
+ struct.pack_into("<II", header, 0, 1, 88)
+ struct.pack_into("<4i", header, 8, *bounds)
+ struct.pack_into("<4i", header, 24, *frame)
+ struct.pack_into("<I", header, 40, 0x464D4520)
+ struct.pack_into("<I", header, 44, 0x00010000)
+ struct.pack_into("<II", header, 48, total_bytes, record_count)
+ struct.pack_into("<HH", header, 56, 16, 0)
+ struct.pack_into("<III", header, 60, 0, 0, 0)
+ struct.pack_into("<2i", header, 72, 1000, 1000)
+ struct.pack_into("<2i", header, 80, 254, 254)
+ return bytes(header)
+
+
+def build_emf(
+ records: list[bytes],
+ *,
+ bounds: tuple[int, int, int, int] = (0, 0, 100, 100),
+ frame: tuple[int, int, int, int] = (0, 0, 2540, 2540),
+) -> bytes:
+ """为给定 records 补齐 EMR_HEADER 与 EMR_EOF。"""
+ eof = emf_record(14, struct.pack("<III", 0, 0, 20))
+ body = b"".join(records) + eof
+ total_bytes = 88 + len(body)
+ return _emf_header(total_bytes, len(records) + 2, bounds=bounds, frame=frame) + body
+
+
+def emf_create_pen(handle: int, colorref: int, *, width: int = 1, style: int = 0) -> bytes:
+ """构造 EMR_CREATEPEN。"""
+ return emf_record(38, struct.pack("<IIiiI", handle, style, width, 0, colorref))
+
+
+def emf_create_brush(handle: int, colorref: int, *, style: int = 0) -> bytes:
+ """构造 EMR_CREATEBRUSHINDIRECT。"""
+ return emf_record(39, struct.pack("<IIII", handle, style, colorref, 0))
+
+
+def emf_select_object(handle: int) -> bytes:
+ """构造 EMR_SELECTOBJECT。"""
+ return emf_record(37, struct.pack("<I", handle))
+
+
+def emf_rectangle(left: int, top: int, right: int, bottom: int) -> bytes:
+ """构造 EMR_RECTANGLE。"""
+ return emf_record(43, struct.pack("<4i", left, top, right, bottom))
+
+
+def emf_savedc() -> bytes:
+ """构造 EMR_SAVEDC。"""
+ return emf_record(33)
+
+
+def emf_restoredc(level: int = -1) -> bytes:
+ """构造 EMR_RESTOREDC。"""
+ return emf_record(34, struct.pack("<i", level))
+
+
+def emf_set_world_transform(matrix: tuple[float, float, float, float, float, float]) -> bytes:
+ """构造 EMR_SETWORLDTRANSFORM。"""
+ return emf_record(35, struct.pack("<6f", *matrix))
+
+
+def emf_move_to(x: int, y: int) -> bytes:
+ """构造 EMR_MOVETOEX。"""
+ return emf_record(27, struct.pack("<2i", x, y))
+
+
+def emf_line_to(x: int, y: int) -> bytes:
+ """构造 EMR_LINETO。"""
+ return emf_record(54, struct.pack("<2i", x, y))
+
+
+def emf_begin_path() -> bytes:
+ """构造 EMR_BEGINPATH。"""
+ return emf_record(59)
+
+
+def emf_end_path() -> bytes:
+ """构造 EMR_ENDPATH。"""
+ return emf_record(60)
+
+
+def emf_close_figure() -> bytes:
+ """构造 EMR_CLOSEFIGURE。"""
+ return emf_record(61)
+
+
+def emf_fill_path() -> bytes:
+ """构造 EMR_FILLPATH。"""
+ return emf_record(62)
+
+
+def emf_stroke_and_fill_path() -> bytes:
+ """构造 EMR_STROKEANDFILLPATH。"""
+ return emf_record(63)
+
+
+def emf_stroke_path() -> bytes:
+ """构造 EMR_STROKEPATH。"""
+ return emf_record(64)
+
+
+def _emf_compact_poly_record(record_type: int, points: list[tuple[int, int]]) -> bytes:
+ """构造使用 PointS 数组的紧凑 EMF poly record。"""
+ if points:
+ xs = [point[0] for point in points]
+ ys = [point[1] for point in points]
+ bounds = min(xs), min(ys), max(xs), max(ys)
+ else:
+ bounds = (0, 0, 0, 0)
+ payload = struct.pack("<4iI", *bounds, len(points))
+ payload += b"".join(struct.pack("<2h", *point) for point in points)
+ return emf_record(record_type, payload)
+
+
+def emf_polyline_to(points: list[tuple[int, int]]) -> bytes:
+ """构造 EMR_POLYLINETO16。"""
+ return _emf_compact_poly_record(89, points)
+
+
+def emf_polybezier(points: list[tuple[int, int]], *, to: bool) -> bytes:
+ """构造 EMR_POLYBEZIER16 或 EMR_POLYBEZIERTO16。"""
+ return _emf_compact_poly_record(88 if to else 85, points)
+
+
+def emf_set_polyfill_mode(mode: int) -> bytes:
+ """构造 EMR_SETPOLYFILLMODE。"""
+ return emf_record(19, struct.pack("<I", mode))
+
+
+def emf_set_miter_limit(value: float) -> bytes:
+ """构造 EMR_SETMITERLIMIT。"""
+ return emf_record(58, struct.pack("<f", value))
+
+
+def emf_font(handle: int, face_name: str = "DejaVu Sans", *, height: int = -14) -> bytes:
+ """构造只填充常用 LOGFONTW 字段的 EMR_EXTCREATEFONTINDIRECTW。"""
+ logfont = bytearray(92)
+ struct.pack_into("<iiiii", logfont, 0, height, 0, 0, 0, 400)
+ logfont[23] = 1
+ encoded = face_name.encode("utf-16le")[:62]
+ logfont[28 : 28 + len(encoded)] = encoded
+ return emf_record(82, struct.pack("<I", handle) + bytes(logfont))
+
+
+def emf_text(text: str, x: int, y: int, *, dx: int = 12) -> bytes:
+ """构造带显式 Dx 数组的 EMR_EXTTEXTOUTW。"""
+ encoded = text.encode("utf-16le")
+ record = bytearray(76)
+ struct.pack_into("<II", record, 0, 84, 0)
+ struct.pack_into("<4i", record, 8, x, y - 20, x + max(1, len(text)) * dx, y + 5)
+ struct.pack_into("<Iff", record, 24, 1, 1.0, 1.0)
+ struct.pack_into("<2i", record, 36, x, y)
+ struct.pack_into("<I", record, 44, len(text))
+ struct.pack_into("<I", record, 48, 76)
+ struct.pack_into("<I", record, 52, 0)
+ struct.pack_into("<4i", record, 56, 0, 0, -1, -1)
+ string_and_padding = _pad4(encoded)
+ dx_offset = 76 + len(string_and_padding)
+ struct.pack_into("<I", record, 72, dx_offset)
+ record.extend(string_and_padding)
+ record.extend(struct.pack(f"<{len(text)}i", *([dx] * len(text))))
+ struct.pack_into("<I", record, 4, len(record))
+ return bytes(record)
+
+
+def emf_stretch_dib() -> bytes:
+ """构造含红绿蓝白四像素的 EMR_STRETCHDIBITS。"""
+ header = bytearray(40)
+ struct.pack_into("<IiiHHIIiiII", header, 0, 40, 2, -2, 1, 32, 0, 16, 0, 0, 0, 0)
+ bits = bytes(
+ (
+ 0,
+ 0,
+ 255,
+ 255,
+ 0,
+ 255,
+ 0,
+ 255,
+ 255,
+ 0,
+ 0,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ )
+ )
+ record = bytearray(80)
+ struct.pack_into("<II", record, 0, 81, 80 + len(header) + len(bits))
+ struct.pack_into("<4i", record, 8, 10, 10, 90, 90)
+ struct.pack_into("<6i", record, 24, 10, 10, 0, 0, 2, 2)
+ struct.pack_into("<4I", record, 48, 80, len(header), 80 + len(header), len(bits))
+ struct.pack_into("<IIii", record, 64, 0, 0x00CC0020, 80, 80)
+ record.extend(header)
+ record.extend(bits)
+ return bytes(record)
+
+
+def emfplus_comment(*, dual: bool) -> bytes:
+ """构造只含 EMF+ Header 的 EMR_COMMENT。"""
+ plus = struct.pack("<IHHII", 0x2B464D45, 0x4001, 1 if dual else 0, 12, 0)
+ return emf_record(70, struct.pack("<I", len(plus)) + plus)
+
+
+def wmf_record(function: int, payload: bytes = b"") -> bytes:
+ """构造按 WORD 计长的 WMF record。"""
+ if len(payload) % 2:
+ payload += b"\x00"
+ return struct.pack("<IH", (6 + len(payload)) // 2, function) + payload
+
+
+def build_placeable_wmf(records: list[bytes], *, bbox: tuple[int, int, int, int] = (0, 0, 1000, 1000)) -> bytes:
+ """构造带 Aldus placeable header 的标准 WMF。"""
+ eof = wmf_record(0)
+ body = b"".join(records) + eof
+ standard = struct.pack("<HHHIHIH", 1, 9, 0x0300, (18 + len(body)) // 2, 16, max(3, len(body) // 2), 0)
+ placeable = bytearray(struct.pack("<IHhhhhHI", 0x9AC6CDD7, 0, *bbox, 1000, 0))
+ checksum = 0
+ for offset in range(0, 20, 2):
+ checksum ^= struct.unpack_from("<H", placeable, offset)[0]
+ placeable.extend(struct.pack("<H", checksum))
+ return bytes(placeable) + standard + body
+
+
+def basic_wmf() -> bytes:
+ """构造包含画笔、画刷、矩形与多边形的 placeable WMF。"""
+ records = [
+ wmf_record(0x02FA, struct.pack("<HhhI", 0, 8, 0, 0x000000FF)),
+ wmf_record(0x02FC, struct.pack("<HIH", 0, 0x0000FF00, 0)),
+ wmf_record(0x012D, struct.pack("<H", 0)),
+ wmf_record(0x012D, struct.pack("<H", 1)),
+ wmf_record(0x041B, struct.pack("<hhhh", 800, 800, 200, 200)),
+ wmf_record(
+ 0x0324,
+ struct.pack("<Hhhhhhh", 3, 100, 900, 500, 100, 900, 900),
+ ),
+ ]
+ return build_placeable_wmf(records)
+
+
+__all__ = [
+ "basic_wmf",
+ "build_emf",
+ "build_placeable_wmf",
+ "emf_create_brush",
+ "emf_create_pen",
+ "emf_begin_path",
+ "emf_close_figure",
+ "emf_end_path",
+ "emf_fill_path",
+ "emf_font",
+ "emf_line_to",
+ "emf_move_to",
+ "emf_polybezier",
+ "emf_polyline_to",
+ "emf_record",
+ "emf_rectangle",
+ "emf_restoredc",
+ "emf_savedc",
+ "emf_select_object",
+ "emf_set_miter_limit",
+ "emf_set_polyfill_mode",
+ "emf_set_world_transform",
+ "emf_stroke_and_fill_path",
+ "emf_stroke_path",
+ "emf_stretch_dib",
+ "emf_text",
+ "emfplus_comment",
+ "wmf_record",
+]
diff --git a/tests/unittest/test_docx_assets.py b/tests/unittest/test_docx_assets.py
index 823fbe2a..9beb41aa 100644
--- a/tests/unittest/test_docx_assets.py
+++ b/tests/unittest/test_docx_assets.py
@@ -34,6 +34,19 @@ def _data_uri(mime_subtype: str, payload: bytes) -> str:
return f"data:image/{mime_subtype};base64,{encoded}"
+def _generated_svg(*, logical_size: tuple[int, int] = (7, 5), fallback_size: tuple[int, int] = (56, 40)) -> bytes:
+ """构造带高密度 PNG fallback 的最小 MinerU SVG。"""
+ fallback = base64.b64encode(_image_bytes("PNG", size=fallback_size)).decode("ascii")
+ width, height = logical_size
+ return (
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
+ f'viewBox="0 0 {width} {height}" data-mineru-generated="wmf-emf">'
+ f'<metadata id="mineru-raster-fallback" data-mime="image/png">{fallback}</metadata>'
+ f'<path d="M 0 0 L {width} 0 L {width} {height} Z" fill="#000000"/>'
+ "</svg>"
+ ).encode()
+
+
def _image_block(**values: str | None) -> ImageBodyBlock:
"""构造最小图片 body block。"""
return ImageBodyBlock(type="image_body", index=0, content="", **values)
@@ -178,6 +191,20 @@ def test_svg_is_rejected_explicitly_for_data_uri_and_sidecar() -> None:
prepare_html_image("images/vector.svg", lambda _path: svg)
+def test_mineru_generated_svg_keeps_native_data_and_high_density_png_fallback() -> None:
+ """验证 DOCX 图片准备同时保留 SVG、逻辑尺寸与高密度 PNG。"""
+ svg = _generated_svg()
+
+ prepared = prepare_html_image(_data_uri("svg+xml", svg))
+
+ assert prepared.svg_data == svg
+ assert prepared.extension == "png"
+ assert (prepared.width_px, prepared.height_px) == (7, 5)
+ with Image.open(BytesIO(prepared.data)) as fallback:
+ assert fallback.format == "PNG"
+ assert fallback.size == (56, 40)
+
+
@pytest.mark.parametrize(
"action",
[
diff --git a/tests/unittest/test_docx_render.py b/tests/unittest/test_docx_render.py
index 325e386e..0c612152 100644
--- a/tests/unittest/test_docx_render.py
+++ b/tests/unittest/test_docx_render.py
@@ -65,6 +65,20 @@ def _png_uri(*, size: tuple[int, int] = (12, 8)) -> str:
return f"data:image/png;base64,{payload}"
+def _generated_svg_uri(*, logical_size: tuple[int, int] = (12, 8), fallback_size: tuple[int, int] = (96, 64)) -> str:
+ """生成带高密度 PNG fallback 的 MinerU SVG data URI。"""
+ width, height = logical_size
+ fallback = base64.b64encode(_png_bytes(size=fallback_size)).decode("ascii")
+ svg = (
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
+ f'viewBox="0 0 {width} {height}" data-mineru-generated="wmf-emf">'
+ f'<metadata id="mineru-raster-fallback" data-mime="image/png">{fallback}</metadata>'
+ f'<path d="M 0 0 L {width} 0 L {width} {height} Z" fill="#000000"/>'
+ "</svg>"
+ ).encode()
+ return f"data:image/svg+xml;base64,{base64.b64encode(svg).decode('ascii')}"
+
+
def _part(docx_bytes: bytes, name: str) -> str:
"""读取 DOCX ZIP 中一个 XML part。"""
with zipfile.ZipFile(BytesIO(docx_bytes)) as archive:
@@ -449,6 +463,46 @@ def test_image_alt_text_and_visual_child_order_are_preserved() -> None:
assert 'descr="diagram description"' in document_xml
+def test_mineru_svg_writes_native_svg_relationship_with_png_fallback() -> None:
+ """验证 DOCX DrawingML 同时引用原生 SVG 与高密度 PNG fallback。"""
+ image = ImageBlock.model_validate(
+ {
+ "type": "image",
+ "index": 0,
+ "content": [
+ {
+ "type": "image_body",
+ "index": 0,
+ "content": "vector formula",
+ "image_base64": _generated_svg_uri(),
+ }
+ ],
+ }
+ )
+
+ result = render_docx(_middle(_page(0, image)))
+ with zipfile.ZipFile(BytesIO(result)) as archive:
+ media = sorted(name for name in archive.namelist() if name.startswith("word/media/"))
+ document_xml = etree.fromstring(archive.read("word/document.xml"))
+ relationships = etree.fromstring(archive.read("word/_rels/document.xml.rels"))
+ content_types = archive.read("[Content_Types].xml").decode("utf-8")
+
+ assert any(name.endswith(".png") for name in media)
+ assert any(name.endswith(".svg") for name in media)
+ namespace = {
+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
+ "asvg": "http://schemas.microsoft.com/office/drawing/2016/SVG/main",
+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
+ }
+ fallback_id = document_xml.xpath("string(.//a:blip/@r:embed)", namespaces=namespace)
+ svg_id = document_xml.xpath("string(.//asvg:svgBlip/@r:embed)", namespaces=namespace)
+ targets = {relationship.get("Id"): relationship.get("Target") for relationship in relationships}
+ assert fallback_id != svg_id
+ assert targets[fallback_id].endswith(".png")
+ assert targets[svg_id].endswith(".svg")
+ assert "image/svg+xml" in content_types
+
+
def test_html_table_materializes_merges_inline_content_link_and_image() -> None:
"""验证复杂 HTML 表格生成合并几何,并复用单元格行内与素材 visitor。"""
html = (
diff --git a/tests/unittest/test_flash_office_metafile.py b/tests/unittest/test_flash_office_metafile.py
new file mode 100644
index 00000000..900fc08c
--- /dev/null
+++ b/tests/unittest/test_flash_office_metafile.py
@@ -0,0 +1,775 @@
+"""验证 Office WMF/EMF 跨平台渲染能力。"""
+
+from __future__ import annotations
+
+import base64
+from io import BytesIO
+from pathlib import Path
+import struct
+from unittest.mock import Mock
+import zlib
+from zipfile import ZIP_DEFLATED, ZipFile
+
+from PIL import Image
+import pytest
+import pptx
+
+from mineru.model.flash import (
+ DocModel,
+ DocxModel,
+ OdpModel,
+ OdsModel,
+ OdtModel,
+ PptModel,
+ PptxModel,
+ RtfModel,
+ XlsModel,
+ XlsxModel,
+)
+from mineru.model.flash.office import image as office_image
+from mineru.model.flash.office.metafile import (
+ MetafileMalformedError,
+ MetafileError,
+ MetafileUnsupportedError,
+ MetafileResourceLimitError,
+ render_metafile,
+)
+from mineru.model.flash.office.metafile import parser as metafile_parser
+from mineru.model.flash.office.metafile import render as metafile_render
+from mineru.model.flash.office.metafile.geometry import FlattenBudget, PathBuilder, flatten_path
+from mineru.model.flash.office.metafile.models import ClipOperation, DrawPathCommand, GraphicsPath, Matrix, Pen
+from mineru.model.flash.office.legacy.officeart import OfficeArtRecord, decode_blip
+from mineru.model.flash.office.pptx.pptx_converter import PptxConverter
+from mineru.model.flash.office.xlsx.xlsx_converter import XlsxConverter
+from mineru.utils.image_payload import extract_mineru_generated_svg_fallback
+
+from _metafile_test_utils import (
+ basic_wmf,
+ build_emf,
+ emf_begin_path,
+ emf_close_figure,
+ emf_create_brush,
+ emf_create_pen,
+ emf_end_path,
+ emf_font,
+ emf_line_to,
+ emf_move_to,
+ emf_polybezier,
+ emf_polyline_to,
+ emf_record,
+ emf_rectangle,
+ emf_restoredc,
+ emf_savedc,
+ emf_select_object,
+ emf_set_miter_limit,
+ emf_set_world_transform,
+ emf_stroke_and_fill_path,
+ emf_stroke_path,
+ emf_stretch_dib,
+ emf_text,
+ emfplus_comment,
+)
+from _legacy_ppt_test_utils import build_equation_ppt
+from _legacy_xls_test_utils import build_equation_xls
+from _mtef_test_utils import build_equation_doc
+from _office_image_mtef_test_utils import build_image_docx, build_image_pptx, build_image_xlsx
+from _odf_test_utils import build_odp_fixture, build_ods_fixture, build_odt_fixture
+
+
+def _open_result(payload: bytes) -> Image.Image:
+ """解码渲染结果并返回脱离 BytesIO 生命周期的 RGBA 图片。"""
+ with Image.open(BytesIO(payload)) as image:
+ image.load()
+ return image.convert("RGBA")
+
+
+def _svg_data_uri_fallback(data_uri: str) -> tuple[Image.Image, tuple[int, int], bytes]:
+ """解析 MinerU SVG data URI,并返回 fallback 图片、逻辑尺寸和 SVG。"""
+ assert data_uri.startswith("data:image/svg+xml;base64,")
+ svg = base64.b64decode(data_uri.split(",", 1)[1])
+ fallback, logical_width, logical_height = extract_mineru_generated_svg_fallback(svg)
+ return _open_result(fallback), (logical_width, logical_height), svg
+
+
+def _basic_emf_records() -> list[bytes]:
+ """返回覆盖画笔、画刷、文字和 DIB 的基础 EMF records。"""
+ return [
+ emf_create_pen(1, 0x00FF0000, width=2),
+ emf_create_brush(2, 0x0000FF00),
+ emf_select_object(1),
+ emf_select_object(2),
+ emf_rectangle(5, 5, 95, 95),
+ emf_stretch_dib(),
+ emf_font(3),
+ emf_select_object(3),
+ emf_text("EMF", 20, 50, dx=18),
+ ]
+
+
+def _collect_image_data_uris(value: object) -> list[str]:
+ """递归收集 raw model-list 中的 image_base64 字段。"""
+ if isinstance(value, dict):
+ result = [value["image_base64"]] if isinstance(value.get("image_base64"), str) else []
+ for item in value.values():
+ result.extend(_collect_image_data_uris(item))
+ return result
+ if isinstance(value, list):
+ result: list[str] = []
+ for item in value:
+ result.extend(_collect_image_data_uris(item))
+ return result
+ return []
+
+
+def _replace_zip_member(package: bytes, member_name: str, payload: bytes) -> bytes:
+ """替换测试 ZIP 中的单个成员并保留其他成员及压缩方式。"""
+ output = BytesIO()
+ with ZipFile(BytesIO(package)) as source, ZipFile(output, "w") as target:
+ for info in source.infolist():
+ target.writestr(info, payload if info.filename == member_name else source.read(info.filename))
+ return output.getvalue()
+
+
+def _compound_square_path(*, inner_reversed: bool, include_island: bool = False) -> GraphicsPath:
+ """构造用于验证 winding 与 even-odd 的嵌套方形复合路径。"""
+ builder = PathBuilder()
+ for point in ((10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)):
+ if builder.current is None:
+ builder.move_to(point)
+ else:
+ builder.line_to(point)
+ builder.close()
+ inner = (
+ ((25.0, 25.0), (25.0, 75.0), (75.0, 75.0), (75.0, 25.0))
+ if inner_reversed
+ else ((25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0))
+ )
+ builder.move_to(inner[0])
+ for point in inner[1:]:
+ builder.line_to(point)
+ builder.close()
+ if include_island:
+ builder.move_to((40.0, 40.0))
+ builder.line_to((60.0, 40.0))
+ builder.line_to((60.0, 60.0))
+ builder.line_to((40.0, 60.0))
+ builder.close()
+ return builder.build()
+
+
+def _build_doc_with_wmf_preview(payload: bytes) -> bytes:
+ """构造 Native 失败后使用 WMF PICF 预览的 DOC。"""
+ return build_equation_doc(
+ [(1, b"invalid")],
+ preview_storage_ids={1},
+ preview_payloads={1: payload},
+ )
+
+
+def _build_ppt_with_wmf_preview(payload: bytes) -> bytes:
+ """构造 Native 失败后使用 OfficeArt WMF 预览的 PPT。"""
+ return build_equation_ppt([b"invalid"], preview_payload=payload)
+
+
+def _build_xls_with_wmf_preview(payload: bytes) -> bytes:
+ """构造 Native 失败后使用 OfficeArt WMF 预览的 XLS。"""
+ return build_equation_xls([(1, b"invalid")], preview_payload=payload)
+
+
+def test_emf_renders_png_jpeg_and_safe_svg() -> None:
+ """验证同一 EMF 可输出三种格式且 SVG 不含活动或外部内容。"""
+ data = build_emf(_basic_emf_records())
+
+ png = render_metafile(data, output_format="png")
+ jpeg = render_metafile(data, output_format="jpeg")
+ svg = render_metafile(data, output_format="svg")
+
+ assert png.media_type == "image/png"
+ assert png.data.startswith(b"\x89PNG\r\n\x1a\n")
+ assert jpeg.media_type == "image/jpeg"
+ assert jpeg.data.startswith(b"\xff\xd8\xff")
+ assert svg.media_type == "image/svg+xml"
+ assert svg.data.startswith(b'<svg xmlns="http://www.w3.org/2000/svg"')
+ assert b"<script" not in svg.data
+ assert b"http://" not in svg.data.replace(b"http://www.w3.org/2000/svg", b"")
+ assert b"https://" not in svg.data
+ assert (png.width, png.height) == (144, 144)
+ assert not png.partial
+
+ image = _open_result(png.data)
+ assert image.getbbox() is not None
+ assert image.getpixel((30, 30))[:3] == (255, 0, 0)
+ assert image.getpixel((100, 30))[:3] == (0, 255, 0)
+ assert image.getpixel((30, 110))[:3] == (0, 0, 255)
+ assert image.getpixel((100, 110))[:3] == (255, 255, 255)
+ assert image.getpixel((30, 90))[:3] == (255, 255, 255)
+
+
+def test_emf_save_restore_preserves_selected_objects_and_transform() -> None:
+ """验证 SaveDC/RestoreDC 同时恢复 transform 与选中画刷。"""
+ records = [
+ emf_create_brush(1, 0x000000FF),
+ emf_create_brush(2, 0x00FF0000),
+ emf_select_object(1),
+ emf_rectangle(0, 0, 20, 20),
+ emf_savedc(),
+ emf_set_world_transform((1, 0, 0, 1, 50, 0)),
+ emf_select_object(2),
+ emf_rectangle(0, 0, 20, 20),
+ emf_restoredc(),
+ emf_rectangle(25, 0, 45, 20),
+ ]
+ image = _open_result(render_metafile(build_emf(records)).data)
+
+ assert image.getpixel((14, 14))[0] > 200
+ assert image.getpixel((50, 14))[0] > 200
+ assert image.getpixel((86, 14))[2] > 200
+
+
+def test_emf_to_records_append_to_one_path_figure_and_update_current_position() -> None:
+ """验证 Path bracket 内 To records 连续追加且 CloseFigure 后新建 figure。"""
+ data = build_emf(
+ [
+ emf_begin_path(),
+ emf_move_to(10, 50),
+ emf_polyline_to([(20, 50), (30, 50)]),
+ emf_polybezier([(40, 50), (50, 50), (60, 50)], to=True),
+ emf_close_figure(),
+ emf_line_to(70, 70),
+ emf_end_path(),
+ emf_stroke_path(),
+ emf_line_to(90, 90),
+ ]
+ )
+
+ document = metafile_parser.parse_metafile(data)
+ commands = [command for command in document.commands if isinstance(command, DrawPathCommand)]
+
+ assert [segment.verb for segment in commands[0].path.segments] == ["M", "L", "L", "C", "Z", "M", "L"]
+ assert commands[0].path.segments[5].points == ((60.0, 50.0),)
+ assert commands[1].path.segments[0].points == ((70.0, 70.0),)
+
+
+def test_emf_non_to_polybezier_does_not_change_gdi_current_position() -> None:
+ """验证 PolyBezier 不像 PolyBezierTo 那样更新 DC current position。"""
+ data = build_emf(
+ [
+ emf_move_to(5, 5),
+ emf_begin_path(),
+ emf_polybezier([(20, 20), (30, 0), (50, 0), (60, 20)], to=False),
+ emf_end_path(),
+ emf_stroke_path(),
+ emf_line_to(10, 5),
+ ]
+ )
+
+ document = metafile_parser.parse_metafile(data)
+ commands = [command for command in document.commands if isinstance(command, DrawPathCommand)]
+
+ assert commands[1].path.segments[0].points == ((5.0, 5.0),)
+
+
+def test_emf_stroke_and_fill_closes_every_open_figure() -> None:
+ """验证 StrokeAndFillPath 在描边前显式闭合全部开放 figure。"""
+ data = build_emf(
+ [
+ emf_begin_path(),
+ emf_move_to(10, 10),
+ emf_polyline_to([(40, 10), (40, 40)]),
+ emf_move_to(60, 60),
+ emf_polyline_to([(90, 60), (90, 90)]),
+ emf_end_path(),
+ emf_stroke_and_fill_path(),
+ ]
+ )
+
+ command = next(command for command in metafile_parser.parse_metafile(data).commands if isinstance(command, DrawPathCommand))
+
+ assert [segment.verb for segment in command.path.segments] == ["M", "L", "L", "Z", "M", "L", "L", "Z"]
+
+
+def test_compound_path_masks_preserve_nonzero_and_evenodd_topology() -> None:
+ """验证 winding、alternate、孔洞和孔洞内岛屿的 mask 拓扑。"""
+ opposite = _compound_square_path(inner_reversed=True)
+ same = _compound_square_path(inner_reversed=False)
+ island = _compound_square_path(inner_reversed=True, include_island=True)
+ self_intersecting_builder = PathBuilder()
+ self_intersecting_builder.move_to((10.0, 10.0))
+ self_intersecting_builder.line_to((90.0, 90.0))
+ self_intersecting_builder.line_to((10.0, 90.0))
+ self_intersecting_builder.line_to((90.0, 10.0))
+ self_intersecting_builder.close()
+
+ winding_hole = metafile_render._path_mask(opposite, Matrix(), (100, 100), "nonzero")
+ winding_filled = metafile_render._path_mask(same, Matrix(), (100, 100), "nonzero")
+ evenodd_hole = metafile_render._path_mask(same, Matrix(), (100, 100), "evenodd")
+ nested_island = metafile_render._path_mask(island, Matrix(), (100, 100), "nonzero")
+ self_intersecting = metafile_render._path_mask(self_intersecting_builder.build(), Matrix(), (100, 100), "evenodd")
+
+ assert winding_hole.getpixel((20, 20)) == 255
+ assert winding_hole.getpixel((30, 30)) == 0
+ assert winding_filled.getpixel((50, 50)) == 255
+ assert evenodd_hole.getpixel((50, 50)) == 0
+ assert nested_island.getpixel((30, 30)) == 0
+ assert nested_island.getpixel((50, 50)) == 255
+ assert self_intersecting.getbbox() is not None
+ assert self_intersecting.getpixel((50, 25)) == 255
+
+
+def test_clip_mask_reuses_compound_path_topology_and_combine_modes() -> None:
+ """验证裁剪 copy/and/or/xor/diff 与路径填充共享同一 winding 结果。"""
+ outer = _compound_square_path(inner_reversed=False)
+ inner_builder = PathBuilder()
+ inner_builder.move_to((35.0, 35.0))
+ inner_builder.line_to((65.0, 35.0))
+ inner_builder.line_to((65.0, 65.0))
+ inner_builder.line_to((35.0, 65.0))
+ inner_builder.close()
+ inner = inner_builder.build()
+ copy_outer = ClipOperation(outer, "copy", "nonzero")
+ copy_inner = ClipOperation(inner, "copy", "nonzero")
+
+ intersection = metafile_render._clip_mask((copy_outer, ClipOperation(inner, "and", "nonzero")), Matrix(), (100, 100))
+ union = metafile_render._clip_mask((copy_inner, ClipOperation(outer, "or", "nonzero")), Matrix(), (100, 100))
+ xor = metafile_render._clip_mask((copy_inner, ClipOperation(outer, "xor", "nonzero")), Matrix(), (100, 100))
+ difference = metafile_render._clip_mask((copy_outer, ClipOperation(inner, "diff", "nonzero")), Matrix(), (100, 100))
+
+ assert intersection is not None and intersection.getpixel((50, 50)) == 255 and intersection.getpixel((20, 20)) == 0
+ assert union is not None and union.getpixel((50, 50)) == 255 and union.getpixel((20, 20)) == 255
+ assert xor is not None and xor.getpixel((50, 50)) == 0 and xor.getpixel((20, 20)) == 255
+ assert difference is not None and difference.getpixel((50, 50)) == 0 and difference.getpixel((20, 20)) == 255
+
+
+def test_adaptive_cubic_flattening_respects_error_and_point_budget() -> None:
+ """验证更严格 flatness 产生更多点且离散点预算可以稳定终止。"""
+ builder = PathBuilder()
+ builder.move_to((0.0, 0.0))
+ builder.cubic_to((0.0, 100.0), (100.0, 100.0), (100.0, 0.0))
+ path = builder.build()
+
+ coarse = flatten_path(path, flatness=10.0)[0][0]
+ fine = flatten_path(path, flatness=0.1)[0][0]
+
+ assert fine[-1] == coarse[-1] == (100.0, 0.0)
+ assert len(fine) > len(coarse)
+ with pytest.raises(MetafileResourceLimitError, match="max_flattened_points=2"):
+ flatten_path(path, flatness=0.1, budget=FlattenBudget(limit=2))
+
+
+def test_stroke_mask_honors_caps_and_svg_miter_limit() -> None:
+ """验证 flat/square/round 端帽差异以及 SVG 保留 DC miter limit。"""
+ subpaths = [([(20.0, 50.0), (80.0, 50.0)], False)]
+ flat = metafile_render._stroke_mask(
+ subpaths,
+ size=(100, 100),
+ width=10.0,
+ pen=Pen(cap="flat"),
+ dashes=(),
+ miter_limit=10.0,
+ budget=FlattenBudget(),
+ )
+ square = metafile_render._stroke_mask(
+ subpaths,
+ size=(100, 100),
+ width=10.0,
+ pen=Pen(cap="square"),
+ dashes=(),
+ miter_limit=10.0,
+ budget=FlattenBudget(),
+ )
+ round_cap = metafile_render._stroke_mask(
+ subpaths,
+ size=(100, 100),
+ width=10.0,
+ pen=Pen(cap="round"),
+ dashes=(),
+ miter_limit=10.0,
+ budget=FlattenBudget(),
+ )
+ dashed = metafile_render._stroke_mask(
+ subpaths,
+ size=(100, 100),
+ width=6.0,
+ pen=Pen(cap="flat"),
+ dashes=(10.0, 10.0),
+ miter_limit=10.0,
+ budget=FlattenBudget(),
+ )
+ corner = [([(20.0, 80.0), (50.0, 20.0), (80.0, 80.0)], False)]
+ miter = metafile_render._stroke_mask(
+ corner,
+ size=(100, 100),
+ width=12.0,
+ pen=Pen(cap="flat", join="miter"),
+ dashes=(),
+ miter_limit=10.0,
+ budget=FlattenBudget(),
+ )
+ bevel = metafile_render._stroke_mask(
+ corner,
+ size=(100, 100),
+ width=12.0,
+ pen=Pen(cap="flat", join="bevel"),
+ dashes=(),
+ miter_limit=10.0,
+ budget=FlattenBudget(),
+ )
+ svg = render_metafile(
+ build_emf(
+ [
+ emf_set_miter_limit(3.5),
+ emf_begin_path(),
+ emf_move_to(10, 10),
+ emf_line_to(90, 90),
+ emf_end_path(),
+ emf_stroke_path(),
+ ]
+ ),
+ output_format="svg",
+ ).data
+
+ assert flat.getpixel((16, 50)) == 0
+ assert square.getpixel((16, 50)) == 255
+ assert round_cap.getpixel((16, 50)) == 255
+ assert dashed.getpixel((25, 50)) == 255
+ assert dashed.getpixel((35, 50)) == 0
+ assert miter.getbbox() is not None and bevel.getbbox() is not None
+ assert miter.getbbox()[1] < bevel.getbbox()[1]
+ assert b'stroke-miterlimit="3.5"' in svg
+
+
+def test_placeable_wmf_renders_vector_content() -> None:
+ """验证 placeable WMF 的 checksum、对象表和逻辑尺寸进入 PNG。"""
+ result = render_metafile(basic_wmf())
+ image = _open_result(result.data)
+
+ assert result.source_format == "wmf"
+ assert (result.width, result.height) == (144, 144)
+ assert not result.partial
+ assert image.getbbox() is not None
+ assert image.getpixel((72, 72))[1] > 150
+
+
+def test_vector_only_metafile_uses_4x_antialiasing_and_8x_svg_fallback() -> None:
+ """验证矢量公式保持逻辑尺寸,同时使用 4× 栅格和 8× DOCX fallback。"""
+ document = metafile_parser.parse_metafile(basic_wmf())
+ svg = render_metafile(basic_wmf(), output_format="svg").data
+ fallback, logical_width, logical_height = extract_mineru_generated_svg_fallback(svg)
+
+ assert metafile_render._supersample_factor(document) == 4
+ assert metafile_render._svg_fallback_scale(document) == 8
+ assert (logical_width, logical_height) == (144, 144)
+ with Image.open(BytesIO(fallback)) as image:
+ assert image.size == (1152, 1152)
+ assert image.info["dpi"][0] == pytest.approx(768, abs=1)
+
+
+def test_emfplus_dual_uses_emf_fallback_and_only_is_rejected() -> None:
+ """验证 EMF+ Dual 播放 EMF fallback,Only 返回稳定不支持错误。"""
+ records = [emfplus_comment(dual=True), emf_create_brush(1, 0x0000FF00), emf_select_object(1), emf_rectangle(5, 5, 95, 95)]
+ dual = render_metafile(build_emf(records))
+
+ assert dual.emfplus_mode == "dual"
+ assert _open_result(dual.data).getbbox() is not None
+
+ only_data = build_emf([emfplus_comment(dual=False), emf_rectangle(5, 5, 95, 95)])
+ with pytest.raises(MetafileUnsupportedError, match=r"EMF\+ Only"):
+ render_metafile(only_data)
+
+
+def test_unknown_drawing_record_keeps_partial_result() -> None:
+ """验证未知绘图 record 被跳过但其他内容继续输出。"""
+ data = build_emf([emf_record(118, b"\x00" * 16), emf_rectangle(5, 5, 95, 95)])
+ result = render_metafile(data)
+
+ assert result.partial
+ assert any(diagnostic.code == "unsupported_emf_record" for diagnostic in result.diagnostics)
+ assert _open_result(result.data).getbbox() is not None
+
+
+def test_malformed_record_and_emf_signature_fail_closed() -> None:
+ """验证截断 record 与伪造签名均返回稳定 malformed 错误。"""
+ valid = bytearray(build_emf([emf_rectangle(5, 5, 95, 95)]))
+ valid[92:96] = (0x7FFFFFFC).to_bytes(4, "little")
+ with pytest.raises(MetafileMalformedError):
+ render_metafile(bytes(valid))
+ with pytest.raises(MetafileMalformedError):
+ render_metafile(b"not-a-metafile")
+
+
+def test_canvas_is_downscaled_to_fixed_pixel_budget() -> None:
+ """验证巨大物理 frame 只会触发等比缩放而不会分配无界画布。"""
+ data = build_emf([emf_rectangle(0, 0, 100, 100)], frame=(0, 0, 254000, 254000))
+ result = render_metafile(data)
+
+ assert result.width * result.height <= 16_000_000
+ assert max(result.width, result.height) <= 8192
+ assert any(diagnostic.code == "canvas_downscaled" for diagnostic in result.diagnostics)
+
+
+def test_fixed_record_point_and_state_limits_are_enforced(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证点数和 SaveDC 深度使用 metafile 专属固定安全预算。"""
+ polygon_payload = (
+ b"\x00" * 16
+ + (3).to_bytes(4, "little")
+ + b"".join(value.to_bytes(4, "little", signed=True) for value in (0, 0, 50, 0, 25, 50))
+ )
+ monkeypatch.setattr(metafile_parser, "MAX_POINTS_PER_RECORD", 2)
+ with pytest.raises(MetafileResourceLimitError, match="max_points_per_record"):
+ render_metafile(build_emf([emf_record(3, polygon_payload)]))
+
+ monkeypatch.setattr(metafile_parser, "MAX_POINTS_PER_RECORD", 1_000_000)
+ monkeypatch.setattr(metafile_parser, "MAX_STATE_DEPTH", 1)
+ with pytest.raises(MetafileResourceLimitError, match="max_state_depth"):
+ render_metafile(build_emf([emf_savedc(), emf_savedc(), emf_rectangle(1, 1, 10, 10)]))
+
+ oversized_dib = bytearray(emf_stretch_dib())
+ oversized_dib[84:88] = (100_000).to_bytes(4, "little", signed=True)
+ oversized_dib[88:92] = (100_000).to_bytes(4, "little", signed=True)
+ with pytest.raises(MetafileResourceLimitError, match="DIB dimensions"):
+ render_metafile(build_emf([bytes(oversized_dib)]))
+
+ monkeypatch.setattr(metafile_render, "MAX_RENDER_WORK_PIXELS", 1)
+ with pytest.raises(MetafileResourceLimitError, match="max_render_work_pixels"):
+ render_metafile(build_emf([emf_rectangle(1, 1, 10, 10)]))
+
+
+def test_svg_text_escapes_markup_characters() -> None:
+ """验证 EMF 文字无法把脚本或 XML 标签注入 SVG。"""
+ data = build_emf([emf_font(1), emf_select_object(1), emf_text("<script>&", 5, 30)])
+ svg = render_metafile(data, output_format="svg").data
+
+ assert b"<script>" not in svg
+ assert b"&lt;" in svg
+ assert b"&gt;" in svg
+ assert b"&amp;" in svg
+ assert svg.index(b"<rect") < svg.index(b"<text")
+
+
+def test_raster_operations_use_exact_bitwise_channels() -> None:
+ """验证常见 ROP2/ROP3 不使用颜色明暗近似替代位运算。"""
+ destination = bytes((0x0F, 0x55, 0xAA))
+ source = bytes((0x33, 0x0F, 0xF0))
+
+ assert metafile_render._bitwise_channel_bytes(destination, source, "xor") == bytes((0x3C, 0x5A, 0x5A))
+ assert metafile_render._bitwise_channel_bytes(destination, source, "and") == bytes((0x03, 0x05, 0xA0))
+ assert metafile_render._bitwise_channel_bytes(destination, source, "or") == bytes((0x3F, 0x5F, 0xFA))
+ assert metafile_render._bitwise_channel_bytes(destination, source, "not_source") == bytes((0xCC, 0xF0, 0x0F))
+ assert metafile_render._bitwise_channel_bytes(destination, source, "not_xor") == bytes((0xC3, 0xA5, 0xA5))
+
+
+def test_non_windows_office_serializer_returns_generated_svg(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证非 Windows Office 图片入口返回安全 SVG 和 PNG fallback。"""
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+ data_uri = office_image.serialize_office_image(
+ build_emf(_basic_emf_records()),
+ part_name="/word/media/image1.emf",
+ content_type="image/x-emf",
+ )
+
+ assert data_uri is not None
+ fallback, logical_size, svg = _svg_data_uri_fallback(data_uri)
+ assert logical_size == (144, 144)
+ assert fallback.getbbox() is not None
+ assert b"<path" in svg
+
+
+def test_officeart_emu_size_controls_standard_wmf_output(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证无 placeable header 的 OfficeArt WMF 使用 ptSize EMU 定标。"""
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+ standard_wmf = basic_wmf()[22:]
+ data_uri = office_image.serialize_office_image(
+ standard_wmf,
+ part_name="picture.wmf",
+ content_type="image/wmf",
+ render_size_emu=(914_400, 457_200),
+ )
+
+ assert data_uri is not None
+ fallback, logical_size, _svg = _svg_data_uri_fallback(data_uri)
+ assert logical_size == (144, 72)
+ assert fallback.size == (1152, 576)
+
+
+def test_officeart_metafile_header_preserves_payload_and_emu_size() -> None:
+ """验证 BLIP 解包保留 WMF bytes,并读取规范 ptSize EMU。"""
+ standard_wmf = basic_wmf()[22:]
+ compressed = zlib.compress(standard_wmf)
+ metafile_header = bytearray(34)
+ struct.pack_into("<I", metafile_header, 0, len(standard_wmf))
+ struct.pack_into("<ii", metafile_header, 20, 914_400, 457_200)
+ struct.pack_into("<I", metafile_header, 28, len(compressed))
+ metafile_header[32:34] = b"\x00\xfe"
+ record = OfficeArtRecord(
+ offset=0,
+ version=0,
+ instance=0,
+ record_type=0xF01B,
+ payload=b"\x00" * 16 + bytes(metafile_header) + compressed,
+ )
+
+ decoded = decode_blip(record)
+
+ assert decoded is not None
+ assert decoded.data == standard_wmf
+ assert decoded.render_size_emu == (914_400, 457_200)
+
+
+def test_windows_office_serializer_prefers_svg_then_uses_native_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 Windows 优先保留 SVG,并在引擎失败时调用原生 GDI。"""
+ data = build_emf(_basic_emf_records())
+ native = Mock(return_value="data:image/png;base64,native")
+ generated = Mock(return_value="data:image/svg+xml;base64,generated")
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: True)
+ monkeypatch.setattr(office_image, "_serialize_native_metafile", native)
+ monkeypatch.setattr(office_image, "_serialize_cross_platform_metafile", generated)
+
+ assert office_image.serialize_office_image(data) == "data:image/svg+xml;base64,generated"
+ native.assert_not_called()
+
+ generated.return_value = None
+ assert office_image.serialize_office_image(data) == "data:image/png;base64,native"
+ native.assert_called_once()
+
+
+def test_pptx_picture_path_uses_cross_platform_metafile_renderer(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 PPTX 普通 picture 不再绕过共享 WMF/EMF 序列化入口。"""
+ converter = PptxConverter()
+ data = build_emf(_basic_emf_records())
+
+ def fake_image_data(_shape: object) -> tuple[bytes, str]:
+ """返回固定 EMF 载荷以隔离 shape relationship 解析。"""
+ return data, "image/x-emf"
+
+ monkeypatch.setattr(converter, "_get_shape_image_data", fake_image_data)
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+ converter._handle_pictures(object())
+
+ assert converter.cur_page[0]["image_base64"].startswith("data:image/svg+xml;base64,")
+
+
+def test_xlsx_wps_cell_image_uses_cross_platform_metafile_renderer(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 WPS DISPIMG 的 cell-image 分支统一调用 Office 图片序列化器。"""
+ package = BytesIO()
+ with ZipFile(package, "w", ZIP_DEFLATED) as archive:
+ archive.writestr("xl/media/image1.emf", build_emf(_basic_emf_records()))
+ converter = XlsxConverter()
+ converter.zf = ZipFile(BytesIO(package.getvalue()))
+ converter.cell_image_map = {"image-id": "media/image1.emf"}
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+ try:
+ html = converter._resolve_cell_image('DISPIMG("image-id")')
+ finally:
+ converter.zf.close()
+
+ assert html.startswith('<img src="data:image/svg+xml;base64,')
+
+
+ ("model", "builder"),
+ [
+ (DocxModel(), build_image_docx),
+ (PptxModel(), build_image_pptx),
+ (XlsxModel(), build_image_xlsx),
+ ],
+ ids=["docx", "pptx", "xlsx"],
+)
+def test_modern_office_models_emit_rendered_emf_svg(
+ model: object,
+ builder: object,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 DOCX/PPTX/XLSX 完整模型链都产出安全 EMF SVG。"""
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+ package = builder(build_emf(_basic_emf_records())) # type: ignore[operator]
+ pages = model.predict(BytesIO(package)) # type: ignore[attr-defined]
+ images = _collect_image_data_uris(pages)
+
+ assert images
+ assert all(image.startswith("data:image/svg+xml;base64,") for image in images)
+ _fallback, logical_size, _svg = _svg_data_uri_fallback(images[0])
+ assert logical_size == (144, 144)
+
+
+ ("model", "builder"),
+ [
+ (DocModel(), _build_doc_with_wmf_preview),
+ (PptModel(), _build_ppt_with_wmf_preview),
+ (XlsModel(), _build_xls_with_wmf_preview),
+ ],
+ ids=["doc", "ppt", "xls"],
+)
+def test_legacy_office_models_emit_rendered_wmf_svg(
+ model: object,
+ builder: object,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 DOC/PPT/XLS 的 OfficeArt/PICF WMF 预览进入跨平台 SVG。"""
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+ pages = model.predict(BytesIO(builder(basic_wmf()))) # type: ignore[attr-defined,operator]
+ images = _collect_image_data_uris(pages)
+
+ assert images
+ assert all(image.startswith("data:image/svg+xml;base64,") for image in images)
+ fallback, logical_size, _svg = _svg_data_uri_fallback(images[0])
+ assert logical_size == (144, 144)
+ assert fallback.size == (1152, 1152)
+
+
+def test_rtf_model_emf_picture_emits_rendered_svg(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 RTF emfblip 从 pict 捕获一路进入跨平台 SVG。"""
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+ emf = build_emf(_basic_emf_records())
+ rtf = b"{\\rtf1 before {\\pict\\emfblip " + emf.hex().encode("ascii") + b"} after\\par}"
+ images = _collect_image_data_uris(RtfModel().predict(BytesIO(rtf)))
+
+ assert images
+ assert all(image.startswith("data:image/svg+xml;base64,") for image in images)
+
+
+ ("model", "builder"),
+ [
+ (OdtModel(), build_odt_fixture),
+ (OdsModel(), build_ods_fixture),
+ (OdpModel(), build_odp_fixture),
+ ],
+ ids=["odt", "ods", "odp"],
+)
+def test_odf_models_emit_rendered_emf_svg(
+ model: object,
+ builder: object,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 ODT/ODS/ODP 包内 WMF/EMF 图片都复用统一渲染入口。"""
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+ package = builder() # type: ignore[operator]
+ package = _replace_zip_member(package, "Pictures/pixel.png", build_emf(_basic_emf_records()))
+ images = _collect_image_data_uris(model.predict(BytesIO(package))) # type: ignore[attr-defined]
+
+ assert images
+ assert all(image.startswith("data:image/svg+xml;base64,") for image in images)
+
+
[email protected]("data", [build_emf([emf_rectangle(5, 5, 95, 95)]), basic_wmf()])
+def test_every_truncated_prefix_fails_without_unexpected_exception(data: bytes) -> None:
+ """验证每个截断位置都只产生稳定格式错误,不泄漏 struct/Pillow 异常。"""
+ for size in range(len(data)):
+ with pytest.raises(MetafileError):
+ render_metafile(data[:size])
+
+
[email protected]("name", ["docx-icon.emf", "generic-icon.emf", "pptx-icon.emf", "xlsx-icon.emf"])
+def test_real_python_pptx_emf_icons_render_without_partial_result(name: str) -> None:
+ """验证依赖包内真实 Office EMF 图标的文字、alpha 和裁剪组合。"""
+ template = Path(pptx.__file__).resolve().parent / "templates" / name
+ result = render_metafile(template.read_bytes())
+ image = _open_result(result.data)
+
+ assert not result.partial
+ assert result.diagnostics == ()
+ assert image.width >= 100
+ assert image.height >= 90
+ assert image.getbbox() is not None
+ assert image.getchannel("A").getextrema()[1] == 255
diff --git a/tests/unittest/test_html_security.py b/tests/unittest/test_html_security.py
index 9876460f..5c7edd8c 100644
--- a/tests/unittest/test_html_security.py
+++ b/tests/unittest/test_html_security.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import base64
+
import pytest
from bs4 import BeautifulSoup, Tag
@@ -10,6 +12,20 @@ from mineru.render._internal.html.sanitizer import (
sanitize_link_url,
)
+_SAFE_PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2l9sAAAAASUVORK5CYII="
+
+
+def _generated_svg_data_uri(extra_markup: str = "") -> str:
+ """构造带 PNG fallback 的最小 MinerU 安全 SVG data URI。"""
+ svg = (
+ '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1" viewBox="0 0 1 1" '
+ 'data-mineru-generated="wmf-emf">'
+ f'<metadata id="mineru-raster-fallback" data-mime="image/png">{_SAFE_PNG_BASE64}</metadata>'
+ '<path d="M 0 0 L 1 0 L 1 1 Z" fill="#000000"/>'
+ f"{extra_markup}</svg>"
+ ).encode()
+ return f"data:image/svg+xml;base64,{base64.b64encode(svg).decode('ascii')}"
+
@pytest.mark.parametrize(
"content",
@@ -248,16 +264,28 @@ def test_sanitize_html_fragment_repairs_list_colgroup_and_image_content_models()
assert soup.find("img").attrs == {"alt": "", "src": "images/a.png"}
-def test_svg_data_uri_is_rejected_before_strict_xml_parsing(monkeypatch: pytest.MonkeyPatch) -> None:
- """验证明确拒绝的 SVG 不进入通用图片 XML 解析器。"""
+def test_unmarked_svg_data_uri_is_rejected() -> None:
+ """验证普通或伪装 SVG 仍无法绕过 MinerU 安全子集。"""
+ assert sanitize_image_source("data:image/svg+xml;base64,PHN2Zz4=") is None
- def _unexpected_parse(_source: str) -> tuple[bytes, str]:
- """若被调用即证明 SVG 快速拒绝失效。"""
- raise AssertionError("SVG parser must not run")
- monkeypatch.setattr("mineru.render._internal.html.sanitizer.parse_image_data_uri_strict", _unexpected_parse)
+def test_mineru_generated_svg_data_uri_is_allowed() -> None:
+ """验证带严格 PNG fallback 的 MinerU SVG 可用于 HTML 图片。"""
+ source = _generated_svg_data_uri()
+ assert sanitize_image_source(source) == source
- assert sanitize_image_source("data:image/svg+xml;base64,PHN2Zz4=") is None
+
+ "extra_markup",
+ [
+ "<script>alert(1)</script>",
+ '<image width="1" height="1" href="https://evil.example/a.png"/>',
+ "<foreignObject><div>unsafe</div></foreignObject>",
+ ],
+)
+def test_mineru_svg_marker_does_not_bypass_active_content_checks(extra_markup: str) -> None:
+ """验证 MinerU marker 无法放行脚本、外链或 foreignObject。"""
+ assert sanitize_image_source(_generated_svg_data_uri(extra_markup)) is None
def test_sanitize_html_fragment_preserves_safe_equation_as_plain_text() -> None: