Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/generic/_link.py: 23%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# All rights reserved.
2#
3# Redistribution and use in source and binary forms, with or without
4# modification, are permitted provided that the following conditions are
5# met:
6#
7# * Redistributions of source code must retain the above copyright notice,
8# this list of conditions and the following disclaimer.
9# * Redistributions in binary form must reproduce the above copyright notice,
10# this list of conditions and the following disclaimer in the documentation
11# and/or other materials provided with the distribution.
12# * The name of the author may not be used to endorse or promote products
13# derived from this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25# POSSIBILITY OF SUCH DAMAGE.
28# This module contains code used by _writer.py to track links in pages
29# being added to the writer until the links can be resolved.
31from typing import TYPE_CHECKING, cast
33from .._utils import logger_warning
34from . import ArrayObject, DictionaryObject, IndirectObject, PdfObject, TextStringObject, is_null_or_none
36if TYPE_CHECKING:
37 from .._page import PageObject
38 from .._reader import PdfReader
39 from .._writer import PdfWriter
42class NamedReferenceLink:
43 """Named reference link being preserved until we can resolve it correctly."""
45 def __init__(self, reference: TextStringObject, source_pdf: "PdfReader") -> None:
46 """reference: TextStringObject with named reference"""
47 self._reference = reference
48 self._source_pdf = source_pdf
50 def find_referenced_page(self) -> IndirectObject | None:
51 destination = self._source_pdf.named_destinations.get(str(self._reference))
52 return destination.page if destination else None
54 def patch_reference(
55 self,
56 target_pdf: "PdfWriter",
57 new_page: IndirectObject,
58 *,
59 known_names: set[str] | None = None,
60 ) -> None:
61 """
62 Add the named destination of the link to the new page, unless it exists.
64 Args:
65 target_pdf: PdfWriter which the new link went into.
66 new_page: IndirectObject representing the new page in the target PDF.
67 known_names: Names of the named destinations of target_pdf, kept up to
68 date by this method. Collecting them from target_pdf is expensive,
69 thus callers patching many links should pass them.
70 """
71 name = str(self._reference)
72 if known_names is None:
73 known_names = set(target_pdf.named_destinations)
74 # point named destination in new PDF to the new page
75 if name not in known_names:
76 target_pdf.add_named_destination(name, new_page.page_number)
77 known_names.add(name)
80class DirectReferenceLink:
81 """Direct reference link being preserved until we can resolve it correctly."""
83 def __init__(self, reference: ArrayObject) -> None:
84 """reference: an ArrayObject whose first element is the Page indirect object"""
85 self._reference = reference
87 def find_referenced_page(self) -> IndirectObject | None:
88 if not self._reference:
89 return None
90 return cast(IndirectObject, self._reference[0])
92 def patch_reference(self, target_pdf: "PdfWriter", new_page: IndirectObject) -> None:
93 """target_pdf: PdfWriter which the new link went into"""
94 self._reference[0] = new_page
97ReferenceLink = NamedReferenceLink | DirectReferenceLink
100def extract_links(new_page: "PageObject", old_page: "PageObject") -> list[tuple[ReferenceLink, ReferenceLink]]:
101 """Extracts links from two pages on the assumption that the two pages are
102 the same. Produces one list of (new link, old link) tuples.
104 Non-link annotations are ignored before pairing to avoid dropping valid
105 links when one page includes additional non-link annotation entries.
106 """
107 new_annotations = new_page.get("/Annots", ArrayObject()).get_object()
108 old_annotations = old_page.get("/Annots", ArrayObject()).get_object()
109 if is_null_or_none(new_annotations):
110 new_annotations = ArrayObject()
111 if is_null_or_none(old_annotations):
112 old_annotations = ArrayObject()
113 if not isinstance(new_annotations, ArrayObject) or not isinstance(old_annotations, ArrayObject):
114 malformed = new_annotations if isinstance(old_annotations, ArrayObject) else old_annotations
115 page_index = old_page.page_number
116 logger_warning(
117 "Ignoring the links on %(page)s: its /Annots is a %(annotations_type)s, not an array.",
118 source=__name__,
119 page="a page" if page_index is None else f"the page with index {page_index}",
120 annotations_type=type(malformed).__name__,
121 )
122 return []
123 new_links = [
124 link
125 for annotation in new_annotations
126 if (link := _build_link(annotation, new_page)) is not None
127 ]
128 old_links = [
129 link
130 for annotation in old_annotations
131 if (link := _build_link(annotation, old_page)) is not None
132 ]
134 if len(new_links) != len(old_links):
135 logger_warning(
136 "Annotation sizes differ: %(old_count)d vs. %(new_count)d",
137 source=__name__,
138 old_count=len(old_links),
139 new_count=len(new_links),
140 )
142 return list(zip(new_links, old_links))
145def _build_link(indirect_object: IndirectObject, page: "PageObject") -> ReferenceLink | None:
146 src = cast("PdfReader", page.pdf)
147 link = cast(DictionaryObject, indirect_object.get_object())
148 if (not isinstance(link, DictionaryObject)) or link.get("/Subtype") != "/Link":
149 return None
151 if "/A" in link:
152 action = cast(DictionaryObject, link["/A"])
153 if action.get("/S") != "/GoTo":
154 return None
156 if "/D" not in action:
157 return None
158 return _create_link(action["/D"], src)
160 if "/Dest" in link:
161 return _create_link(link["/Dest"], src)
163 return None # Nothing to do here
166def _create_link(reference: PdfObject, source_pdf: "PdfReader") -> ReferenceLink | None:
167 if isinstance(reference, TextStringObject):
168 return NamedReferenceLink(reference, source_pdf)
169 if isinstance(reference, ArrayObject):
170 return DirectReferenceLink(reference)
171 return None