Source code

Download source archive ↓

src/pypdf/_protocols.py

1"""Helpers for working with PDF types."""
2
3from abc import abstractmethod
4from collections.abc import Sequence
5from pathlib import Path
6from typing import IO, Any, Literal, Optional, Protocol
7
8from ._utils import StrByteType, StreamType
9
10
11class PdfObjectProtocol(Protocol):
12    indirect_reference: Any
13
14    def clone(
15        self,
16        pdf_dest: Any,
17        force_duplicate: bool = False,
18        ignore_fields: tuple[str, ...] | list[str] | None = (),
19    ) -> Any:
20        ...  # pragma: no cover
21
22    def _reference_clone(self, clone: Any, pdf_dest: Any) -> Any:
23        ...  # pragma: no cover
24
25    def get_object(self) -> Optional["PdfObjectProtocol"]:
26        ...  # pragma: no cover
27
28    def hash_value(self) -> bytes:
29        ...  # pragma: no cover
30
31    def write_to_stream(self, stream: StreamType) -> None:
32        ...  # pragma: no cover
33
34
35class XmpInformationProtocol(PdfObjectProtocol, Protocol):
36    pass
37
38
39class PdfCommonDocProtocol(Protocol):
40    @property
41    def pdf_header(self) -> str:
42        ...  # pragma: no cover
43
44    @property
45    def pages(self) -> Sequence[Any]:
46        ...  # pragma: no cover
47
48    @property
49    def root_object(self) -> PdfObjectProtocol:
50        ...  # pragma: no cover
51
52    def get_object(self, indirect_reference: Any) -> PdfObjectProtocol | None:
53        ...  # pragma: no cover
54
55    @property
56    def strict(self) -> bool:
57        ...  # pragma: no cover
58
59
60class PdfReaderProtocol(PdfCommonDocProtocol, Protocol):
61    @property
62    @abstractmethod
63    def xref(self) -> dict[int, dict[int, Any]]:
64        ...  # pragma: no cover
65
66    @property
67    @abstractmethod
68    def trailer(self) -> dict[str, Any]:
69        ...  # pragma: no cover
70
71
72class PdfWriterProtocol(PdfCommonDocProtocol, Protocol):
73    _objects: list[Any]
74    # The "PreventGC" entry holds the source document, keeping it alive while
75    # the translation table is in use.
76    _id_translated: dict[int, dict[int | Literal["PreventGC"], Any]]
77
78    incremental: bool
79    # Only populated in incremental mode, None otherwise.
80    _reader: Any | None  # PdfReader
81
82    @abstractmethod
83    def write(self, stream: Path | StrByteType) -> tuple[bool, IO[Any]]:
84        ...  # pragma: no cover
85
86    @abstractmethod
87    def _add_object(self, obj: Any) -> Any:
88        ...  # pragma: no cover