Skip to content

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

feat: add EMF/WMF text alignment and angle arc functions, enhance image handling

myhloli28fd645b633a
diff --git a/mineru/model/flash/office/doc/images.py b/mineru/model/flash/office/doc/images.py
index d90673a6..b1281859 100644
--- a/mineru/model/flash/office/doc/images.py
+++ b/mineru/model/flash/office/doc/images.py
@@ -34,31 +34,42 @@ class ImageStore:
"""按内容去重并限制 DOC 图片累计字节数。"""
total: int = 0
- cache: dict[bytes, DocImagePayload] = field(default_factory=dict)
+ cache: dict[tuple[bytes, tuple[int, int] | None], DocImagePayload] = field(default_factory=dict)
+ accounted_digests: set[bytes] = field(default_factory=set)
+ equation_cache: dict[bytes, str | None] = field(default_factory=dict)
equation_decoder: OfficeImageEquationDecoder = field(default_factory=OfficeImageEquationDecoder)
def add(self, payload: OfficeImagePayload) -> DocImagePayload:
"""计入一张唯一图片并返回内部载荷。"""
digest = hashlib.sha256(payload.data).digest()
- cached = self.cache.get(digest)
+ cache_key = digest, payload.render_size_emu
+ cached = self.cache.get(cache_key)
if cached is not None:
return cached
- if self.total + len(payload.data) > MAX_ASSET_TOTAL_BYTES:
+ is_new_payload = digest not in self.accounted_digests
+ if is_new_payload and self.total + len(payload.data) > MAX_ASSET_TOTAL_BYTES:
raise LegacyOfficeResourceLimitError(f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}")
+ if digest in self.equation_cache:
+ equation_latex = self.equation_cache[digest]
+ else:
+ equation_latex = self.equation_decoder.decode(
+ payload.data,
+ part_name=f"image.{payload.extension}",
+ content_type=payload.content_type,
+ )
converted = DocImagePayload(
payload.data,
payload.extension,
payload.content_type,
- self.equation_decoder.decode(
- payload.data,
- part_name=f"image.{payload.extension}",
- content_type=payload.content_type,
- ),
+ equation_latex,
render_size_emu=payload.render_size_emu,
)
- self.total += len(payload.data)
- self.cache[digest] = converted
+ if is_new_payload:
+ self.total += len(payload.data)
+ self.accounted_digests.add(digest)
+ self.equation_cache[digest] = equation_latex
+ self.cache[cache_key] = converted
return converted
diff --git a/mineru/model/flash/office/metafile/font.py b/mineru/model/flash/office/metafile/font.py
new file mode 100644
index 00000000..78a014d2
--- /dev/null
+++ b/mineru/model/flash/office/metafile/font.py
@@ -0,0 +1,111 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""WMF/EMF parser 与 renderer 共享的跨平台字体解析和度量。"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from pathlib import Path
+import platform
+
+from PIL import ImageFont
+
+from .models import Font
+
+
+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 measure_text_advance(font: Font, text: str) -> float:
+ """用 renderer 同款字体回退规则估算无显式 spacing 的逻辑 advance。"""
+ if not text:
+ return 0.0
+ font_size = max(1, round(abs(font.height or -12.0)))
+ loaded = load_font(font.face_name, font_size, font.weight, font.italic, font.charset)
+ advance = float(loaded.getlength(text))
+ if font.width:
+ natural_width = max(float(loaded.getlength("0")), 1e-9)
+ advance *= abs(font.width) / natural_width
+ return max(advance, 0.0)
+
+
+__all__ = ["load_font", "measure_text_advance"]
diff --git a/mineru/model/flash/office/metafile/parser.py b/mineru/model/flash/office/metafile/parser.py
index d701e269..c3bedce0 100644
--- a/mineru/model/flash/office/metafile/parser.py
+++ b/mineru/model/flash/office/metafile/parser.py
@@ -4,10 +4,11 @@
from __future__ import annotations
from dataclasses import dataclass, replace
-from math import atan2, degrees, isfinite
+from math import atan2, cos, degrees, isfinite, radians, sin
import struct
from .binary import BoundedReader
+from .font import measure_text_advance
from .geometry import (
PathBuilder,
arc_path,
@@ -390,6 +391,23 @@ class _Playback:
self.emit_path(builder.build(), stroke=True, fill=False)
self.state.current_position = remaining[-1]
+ def angle_arc(self, path: GraphicsPath, *, start: Point, end: Point) -> None:
+ """绘制 current-to-start 连线和 AngleArc,并把 current position 更新到终点。"""
+ mapped_path = transform_path(path, self.logical_matrix())
+ mapped_start = self.map_point(start)
+ tail = GraphicsPath(mapped_path.segments[1:])
+ if self.path_active:
+ self._ensure_active_path_current()
+ self.path_builder.line_to(mapped_start)
+ self.path_builder.extend(tail)
+ else:
+ builder = PathBuilder()
+ builder.move_to(self.map_point(self.state.current_position))
+ builder.line_to(mapped_start)
+ builder.extend(tail)
+ self.emit_path(builder.build(), stroke=True, fill=False)
+ self.state.current_position = end
+
def begin_path(self) -> None:
"""开始新的 GDI path bracket 并清除旧路径。"""
if self.path_active:
@@ -966,9 +984,11 @@ def _emit_text(
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
+ update_current = bool(playback.state.text_align & _TA_UPDATECP)
+ logical_origin = playback.state.current_position if update_current else reference
origin = playback.map_point(logical_origin)
positions: list[Point] = []
+ font = playback.state.font
if advances:
cursor_x, cursor_y = logical_origin
for index, _character in enumerate(text):
@@ -976,9 +996,15 @@ def _emit_text(
if index < len(advances):
cursor_x += advances[index][0]
cursor_y += advances[index][1]
- if playback.state.text_align & _TA_UPDATECP:
+ if update_current:
playback.state.current_position = (cursor_x, cursor_y)
- font = playback.state.font
+ elif update_current:
+ advance = measure_text_advance(font, text)
+ angle = radians(font.escapement / 10.0)
+ playback.state.current_position = (
+ logical_origin[0] + advance * cos(angle),
+ logical_origin[1] - advance * sin(angle),
+ )
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
@@ -1352,16 +1378,16 @@ def _handle_emf_record(record_type: int, record: BoundedReader, playback: _Playb
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(
+ direction = 1 if sweep_angle >= 0 else 2
+ playback.angle_arc(
arc_path(
Rect(center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius),
start,
end,
direction=direction,
),
- stroke=True,
- fill=False,
+ start=start,
+ end=end,
)
return
diff --git a/mineru/model/flash/office/metafile/render.py b/mineru/model/flash/office/metafile/render.py
index 2c455894..c36fd05c 100644
--- a/mineru/model/flash/office/metafile/render.py
+++ b/mineru/model/flash/office/metafile/render.py
@@ -4,16 +4,14 @@
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 .font import load_font
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 (
@@ -161,89 +159,6 @@ def _decode_dib(command: DrawImageCommand) -> Image.Image:
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]]] = []
@@ -586,7 +501,7 @@ def _render_text_command(
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)
+ 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]
diff --git a/tests/unittest/_metafile_test_utils.py b/tests/unittest/_metafile_test_utils.py
index 95f1f7d0..ac1986c8 100644
--- a/tests/unittest/_metafile_test_utils.py
+++ b/tests/unittest/_metafile_test_utils.py
@@ -96,6 +96,11 @@ def emf_line_to(x: int, y: int) -> bytes:
return emf_record(54, struct.pack("<2i", x, y))
+def emf_angle_arc(center_x: int, center_y: int, radius: int, start_angle: float, sweep_angle: float) -> bytes:
+ """构造 EMR_ANGLEARC。"""
+ return emf_record(41, struct.pack("<iiIff", center_x, center_y, radius, start_angle, sweep_angle))
+
+
def emf_begin_path() -> bytes:
"""构造 EMR_BEGINPATH。"""
return emf_record(59)
@@ -159,6 +164,11 @@ def emf_set_miter_limit(value: float) -> bytes:
return emf_record(58, struct.pack("<f", value))
+def emf_set_text_align(value: int) -> bytes:
+ """构造 EMR_SETTEXTALIGN。"""
+ return emf_record(22, struct.pack("<I", value))
+
+
def emf_font(handle: int, face_name: str = "DejaVu Sans", *, height: int = -14) -> bytes:
"""构造只填充常用 LOGFONTW 字段的 EMR_EXTCREATEFONTINDIRECTW。"""
logfont = bytearray(92)
@@ -169,12 +179,13 @@ def emf_font(handle: int, face_name: str = "DejaVu Sans", *, height: int = -14)
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。"""
+def emf_text(text: str, x: int, y: int, *, dx: int | None = 12) -> bytes:
+ """构造可选显式 Dx 数组的 EMR_EXTTEXTOUTW。"""
encoded = text.encode("utf-16le")
record = bytearray(76)
+ nominal_dx = dx if dx is not None else 12
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("<4i", record, 8, x, y - 20, x + max(1, len(text)) * nominal_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))
@@ -182,10 +193,11 @@ def emf_text(text: str, x: int, y: int, *, dx: int = 12) -> bytes:
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))))
+ if dx is not None:
+ dx_offset = 76 + len(string_and_padding)
+ struct.pack_into("<I", record, 72, dx_offset)
+ record.extend(struct.pack(f"<{len(text)}i", *([dx] * len(text))))
struct.pack_into("<I", record, 4, len(record))
return bytes(record)
@@ -238,6 +250,26 @@ def wmf_record(function: int, payload: bytes = b"") -> bytes:
return struct.pack("<IH", (6 + len(payload)) // 2, function) + payload
+def wmf_move_to(x: int, y: int) -> bytes:
+ """构造 META_MOVETO。"""
+ return wmf_record(0x0214, struct.pack("<hh", y, x))
+
+
+def wmf_set_text_align(value: int) -> bytes:
+ """构造 META_SETTEXTALIGN。"""
+ return wmf_record(0x012E, struct.pack("<H", value))
+
+
+def wmf_textout(text: str, x: int, y: int) -> bytes:
+ """构造没有显式字符 spacing 的 META_TEXTOUT。"""
+ encoded = text.encode("cp1252")
+ payload = struct.pack("<H", len(encoded)) + encoded
+ if len(encoded) & 1:
+ payload += b"\x00"
+ payload += struct.pack("<hh", y, x)
+ return wmf_record(0x0521, 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)
@@ -271,6 +303,7 @@ __all__ = [
"basic_wmf",
"build_emf",
"build_placeable_wmf",
+ "emf_angle_arc",
"emf_create_brush",
"emf_create_pen",
"emf_begin_path",
@@ -289,11 +322,15 @@ __all__ = [
"emf_select_object",
"emf_set_miter_limit",
"emf_set_polyfill_mode",
+ "emf_set_text_align",
"emf_set_world_transform",
"emf_stroke_and_fill_path",
"emf_stroke_path",
"emf_stretch_dib",
"emf_text",
"emfplus_comment",
+ "wmf_move_to",
"wmf_record",
+ "wmf_set_text_align",
+ "wmf_textout",
]
diff --git a/tests/unittest/test_flash_legacy_doc.py b/tests/unittest/test_flash_legacy_doc.py
index 08dbc7aa..481fa7fe 100644
--- a/tests/unittest/test_flash_legacy_doc.py
+++ b/tests/unittest/test_flash_legacy_doc.py
@@ -4,6 +4,7 @@ import asyncio
from collections import Counter
from io import BytesIO
from pathlib import Path
+from unittest.mock import Mock
from bs4 import BeautifulSoup
import pytest
@@ -13,6 +14,7 @@ from mineru.backend.postprocess.lists import fix_office_list_blocks
from mineru.model.flash import DocModel
from mineru.model.flash._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
from mineru.model.flash.office.doc.models import DocCharStyle, DocTableCell
+from mineru.model.flash.office.doc.images import ImageStore
from mineru.model.flash.office.doc.parser import _RawTableRow, _materialize_table_rows
from mineru.model.flash.office.doc.records import DocBudget
from mineru.model.flash.office.doc.sprm import apply_character_sprms
@@ -22,6 +24,7 @@ from mineru.model.flash.office.errors import (
LegacyOfficeMissingPartError,
LegacyOfficeResourceLimitError,
)
+from mineru.model.flash.office.legacy.officeart import OfficeImagePayload
from mineru.parser import parse
from mineru.types import BlockType, ChartBlock, MiddleJson, ModelJson, TableBlock
@@ -33,6 +36,25 @@ _PROJECT_ROOT = Path(__file__).resolve().parents[2]
_REAL_DOC = _PROJECT_ROOT / "demo" / "office_docs" / "docx_01.doc"
+def test_doc_image_store_distinguishes_render_size_without_double_accounting() -> None:
+ """验证相同图片的不同 ptSize 独立缓存,但原始 bytes 只计费和解码一次。"""
+ decoder = Mock()
+ decoder.decode.return_value = None
+ store = ImageStore(equation_decoder=decoder)
+ data = b"same-standard-wmf"
+
+ landscape = store.add(OfficeImagePayload(data, "wmf", "image/wmf", (914_400, 457_200)))
+ portrait = store.add(OfficeImagePayload(data, "wmf", "image/wmf", (457_200, 914_400)))
+ landscape_again = store.add(OfficeImagePayload(data, "wmf", "image/wmf", (914_400, 457_200)))
+
+ assert landscape.render_size_emu == (914_400, 457_200)
+ assert portrait.render_size_emu == (457_200, 914_400)
+ assert portrait is not landscape
+ assert landscape_again is landscape
+ assert store.total == len(data)
+ decoder.decode.assert_called_once()
+
+
def test_doc_model_preserves_empty_sections_and_ignores_page_breaks() -> None:
"""验证 section 是唯一分页来源,空 section 保留且分页符不额外切页。"""
diff --git a/tests/unittest/test_flash_office_metafile.py b/tests/unittest/test_flash_office_metafile.py
index 8ca26e5c..325d02d8 100644
--- a/tests/unittest/test_flash_office_metafile.py
+++ b/tests/unittest/test_flash_office_metafile.py
@@ -37,7 +37,15 @@ from mineru.model.flash.office.metafile import (
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, path_bounds
-from mineru.model.flash.office.metafile.models import ClipOperation, DrawPathCommand, GraphicsPath, Matrix, Pen, Rect
+from mineru.model.flash.office.metafile.models import (
+ ClipOperation,
+ DrawPathCommand,
+ DrawTextCommand,
+ GraphicsPath,
+ Matrix,
+ Pen,
+ Rect,
+)
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
@@ -47,6 +55,7 @@ from _metafile_test_utils import (
basic_wmf,
build_emf,
build_placeable_wmf,
+ emf_angle_arc,
emf_begin_path,
emf_close_figure,
emf_create_brush,
@@ -63,13 +72,17 @@ from _metafile_test_utils import (
emf_savedc,
emf_select_object,
emf_set_miter_limit,
+ emf_set_text_align,
emf_set_world_transform,
emf_stroke_and_fill_path,
emf_stroke_path,
emf_stretch_dib,
emf_text,
emfplus_comment,
+ wmf_move_to,
wmf_record,
+ wmf_set_text_align,
+ wmf_textout,
)
from _legacy_ppt_test_utils import build_equation_ppt
from _legacy_xls_test_utils import build_equation_xls
@@ -271,6 +284,59 @@ def test_emf_non_to_polybezier_does_not_change_gdi_current_position() -> None:
assert commands[1].path.segments[0].points == ((5.0, 5.0),)
+ "data",
+ [
+ build_emf(
+ [
+ emf_set_text_align(1),
+ emf_move_to(10, 50),
+ emf_text("first", 900, 900, dx=None),
+ emf_text("second", 800, 800, dx=None),
+ ]
+ ),
+ build_placeable_wmf(
+ [
+ wmf_set_text_align(1),
+ wmf_move_to(10, 50),
+ wmf_textout("first", 900, 900),
+ wmf_textout("second", 800, 800),
+ ]
+ ),
+ ],
+ ids=["emf", "wmf"],
+)
+def test_updatecp_text_without_explicit_spacing_advances_current_position(data: bytes) -> None:
+ """验证 EMF/WMF 无显式 spacing 的 TA_UPDATECP 文本不会相互覆盖。"""
+ commands = [command for command in metafile_parser.parse_metafile(data).commands if isinstance(command, DrawTextCommand)]
+
+ assert len(commands) == 2
+ assert commands[0].origin == (10.0, 50.0)
+ assert commands[1].origin[0] > commands[0].origin[0]
+ assert commands[1].origin[1] == pytest.approx(commands[0].origin[1])
+ assert not commands[0].positions
+ assert not commands[1].positions
+
+
[email protected](("sweep_angle", "expected_end_y"), [(90.0, -10.0), (-90.0, 10.0)])
+def test_emf_anglearc_uses_sweep_direction_and_updates_current_position(
+ sweep_angle: float,
+ expected_end_y: float,
+) -> None:
+ """验证 AngleArc 绘制起始连线、使用正确 sweep 方向并更新 current position。"""
+ data = build_emf(
+ [emf_angle_arc(0, 0, 10, 0.0, sweep_angle), emf_line_to(20, 20)],
+ bounds=(-20, -20, 30, 30),
+ )
+ commands = [command for command in metafile_parser.parse_metafile(data).commands if isinstance(command, DrawPathCommand)]
+
+ assert len(commands[0].path.segments) == 14
+ assert commands[0].path.segments[0].points == ((0.0, 0.0),)
+ assert commands[0].path.segments[1].points == ((10.0, 0.0),)
+ assert commands[0].path.segments[-1].points[0] == pytest.approx((0.0, expected_end_y))
+ assert commands[1].path.segments[0].points[0] == pytest.approx((0.0, expected_end_y))
+
+
def test_emf_stroke_and_fill_closes_every_open_figure() -> None:
"""验证 StrokeAndFillPath 在描边前显式闭合全部开放 figure。"""
data = build_emf(