|
| 1 | +# SPDX-FileCopyrightText: 2024 James R. Barlow |
| 2 | +# SPDX-License-Identifier: MPL-2.0 |
| 3 | + |
| 4 | +"""OCRmyPDF PDF annotation cleanup.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import logging |
| 9 | + |
| 10 | +from pikepdf import Dictionary, Name, NameTree, Pdf |
| 11 | + |
| 12 | +log = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +def remove_broken_goto_annotations(pdf: Pdf) -> bool: |
| 16 | + """Remove broken goto annotations from a PDF. |
| 17 | +
|
| 18 | + If a PDF contains a GoTo Action that points to a named destination that does not |
| 19 | + exist, Ghostscript PDF/A conversion will fail. In any event, a named destination |
| 20 | + that is not defined is not useful. |
| 21 | +
|
| 22 | + Args: |
| 23 | + pdf: Opened PDF file. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + bool: True if the file was modified, False if not. |
| 27 | + """ |
| 28 | + modified = False |
| 29 | + |
| 30 | + # Check if there are any named destinations |
| 31 | + if Name.Names not in pdf.Root: |
| 32 | + return modified |
| 33 | + if Name.Dests not in pdf.Root[Name.Names]: |
| 34 | + return modified |
| 35 | + |
| 36 | + dests = pdf.Root[Name.Names][Name.Dests] |
| 37 | + if not isinstance(dests, Dictionary): |
| 38 | + return modified |
| 39 | + nametree = NameTree(dests) |
| 40 | + |
| 41 | + # Create a set of all named destinations |
| 42 | + names = set(k for k in nametree.keys()) |
| 43 | + |
| 44 | + for n, page in enumerate(pdf.pages): |
| 45 | + if Name.Annots not in page: |
| 46 | + continue |
| 47 | + for annot in page[Name.Annots]: |
| 48 | + if not isinstance(annot, Dictionary): |
| 49 | + continue |
| 50 | + if Name.A not in annot or Name.D not in annot[Name.A]: |
| 51 | + continue |
| 52 | + # We found an annotation that points to a named destination |
| 53 | + named_destination = str(annot[Name.A][Name.D]) |
| 54 | + if named_destination not in names: |
| 55 | + # If there is no corresponding named destination, remove the |
| 56 | + # annotation. Having no destination set is still valid and just |
| 57 | + # makes the link non-functional. |
| 58 | + log.warning( |
| 59 | + f"Disabling a hyperlink annotation on page {n + 1} to a " |
| 60 | + "non-existent named destination " |
| 61 | + f"{named_destination}." |
| 62 | + ) |
| 63 | + del annot[Name.A][Name.D] |
| 64 | + modified = True |
| 65 | + |
| 66 | + return modified |
0 commit comments