SPB Git

Repository Public

pdf_fixtures.py 4.6 KB 115 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/unit/extract/pdf_fixtures.py8# Module           : Tests9# Repository       : https://git.spboucher.ai/spider10# Project Website  : Not specified11# Created          : 2026-12-0412# Last Modified    : 2026-12-0413#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Hand-written minimal PDF builder used to generate the fixtures in ``tests/fixtures/extract``.4243Run ``python tests/unit/extract/pdf_fixtures.py`` to regenerate the files. No third-party library is44involved: the bytes (objects, xref table, trailer) are assembled here.45"""46from __future__ import annotations4748from pathlib import Path4950FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "extract"515253def build_pdf(pages: list[str | None], *, javascript: bool = False, title: str = "SPIDER fixture") -> bytes:54    """Build a PDF with one page per entry: a string is drawn as text, ``None`` gives a page with only55    a vector rectangle (no text layer, as a scanned page would be)."""56    objects: list[bytes] = []5758    def add(body: bytes) -> int:59        objects.append(body)60        return len(objects)6162    catalog_id = add(b"")  # placeholder, filled below63    pages_id = add(b"")64    font_id = add(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>")65    kids: list[int] = []66    for text in pages:67        if text is None:68            stream = b"0.5 g 72 600 200 100 re f"69        else:70            escaped = text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")71            stream = f"BT /F1 14 Tf 72 720 Td ({escaped}) Tj ET".encode("cp1252")72        content_id = add(b"<< /Length %d >>\nstream\n" % len(stream) + stream + b"\nendstream")73        page_id = add(b"<< /Type /Page /Parent %d 0 R /MediaBox [0 0 612 792] /Contents %d 0 R "74                      b"/Resources << /Font << /F1 %d 0 R >> >> >>" % (pages_id, content_id, font_id))75        kids.append(page_id)76    info_id = add(b"<< /Title (%s) /Producer (spider-tests) >>" % title.encode("cp1252"))77    extra = b""78    if javascript:79        js_id = add(b"<< /Type /Action /S /JavaScript /JS (app.alert\\('never executed'\\);) >>")80        extra = b" /OpenAction %d 0 R" % js_id81    objects[catalog_id - 1] = b"<< /Type /Catalog /Pages %d 0 R%s >>" % (pages_id, extra)82    objects[pages_id - 1] = b"<< /Type /Pages /Kids [%s] /Count %d >>" % (83        b" ".join(b"%d 0 R" % k for k in kids), len(kids))8485    out = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")86    offsets: list[int] = []87    for number, body in enumerate(objects, start=1):88        offsets.append(len(out))89        out += b"%d 0 obj\n" % number + body + b"\nendobj\n"90    xref = len(out)91    out += b"xref\n0 %d\n" % (len(objects) + 1)92    out += b"0000000000 65535 f \n"93    for offset in offsets:94        out += b"%010d 00000 n \n" % offset95    out += b"trailer\n<< /Size %d /Root %d 0 R /Info %d 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (96        len(objects) + 1, catalog_id, info_id, xref)97    return bytes(out)9899100FILES = {101    "text_and_scan.pdf": lambda: build_pdf(["Loyer mensuel : 1 250 $ - Monthly rent", None]),102    "with_javascript.pdf": lambda: build_pdf(["Page with an OpenAction"], javascript=True),103}104105106def main() -> None:107    FIXTURES.mkdir(parents=True, exist_ok=True)108    for name, builder in FILES.items():109        (FIXTURES / name).write_bytes(builder())110        print("wrote", FIXTURES / name)111112113if __name__ == "__main__":114    main()115
Files main
Menu

Theme