""" tests/test_shipping_xfa_helpers.py 用途:XFA Phase 1 测试共用工具——合成 hybrid PDF、加载 fixture XML。 依赖:pypdf、fixtures/shipping_xfa。 逻辑:供 test_shipping_xfa_packets/dataset/structure_analysis 复用。 """ from __future__ import annotations from io import BytesIO from pathlib import Path from pypdf import PdfWriter from pypdf.generic import ArrayObject, DictionaryObject, NameObject, StreamObject FIXTURE_ROOT = Path(__file__).resolve().parent / 'fixtures' / 'shipping_xfa' def load_datasets_fixture() -> bytes: """读取 annotation datasets 样例 XML 字节。""" return (FIXTURE_ROOT / 'annotation' / 'datasets_sample.xml').read_bytes() def build_synthetic_xfa_hybrid_pdf( datasets_xml: bytes, *, template_xml: bytes | None = None, include_page: bool = True, ) -> bytes: """ 用 pypdf 合成最小 XFA hybrid PDF(含 template + datasets packet)。 Args: datasets_xml: datasets packet 字节。 template_xml: 可选 template packet;默认最小占位 template。 include_page: 是否添加空白页以标记 hybrid(相对 pure_xfa)。 Returns: 完整 PDF 字节。 """ writer = PdfWriter() if include_page: writer.add_blank_page(width=612, height=792) template_payload = template_xml or ( b'' b'' ) template_stream = StreamObject() template_stream.set_data(template_payload) datasets_stream = StreamObject() datasets_stream.set_data(datasets_xml) xfa_array = ArrayObject() xfa_array.append(NameObject('/template')) xfa_array.append(writer._add_object(template_stream)) xfa_array.append(NameObject('/datasets')) xfa_array.append(writer._add_object(datasets_stream)) acroform = DictionaryObject() acroform[NameObject('/XFA')] = xfa_array acroform[NameObject('/Fields')] = ArrayObject() writer._root_object[NameObject('/AcroForm')] = writer._add_object(acroform) buffer = BytesIO() writer.write(buffer) return buffer.getvalue() def build_plain_pdf() -> bytes: """合成无 AcroForm/XFA 的普通 PDF。""" writer = PdfWriter() writer.add_blank_page(width=612, height=792) buffer = BytesIO() writer.write(buffer) return buffer.getvalue()