Skip to content

Commit

Permalink
Add test and make printing optional
Browse files Browse the repository at this point in the history
  • Loading branch information
Nifury committed May 4, 2024
1 parent ec38a0b commit b3ae07c
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
5 changes: 4 additions & 1 deletion pypdf/annotations/_markup_annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from abc import ABC
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union

from ..constants import AnnotationFlag
from ..generic import ArrayObject, DictionaryObject
from ..generic._base import (
BooleanObject,
Expand Down Expand Up @@ -233,20 +234,22 @@ def __init__(
rect: Union[RectangleObject, Tuple[float, float, float, float]],
quad_points: ArrayObject,
highlight_color: str = "ff0000",
printing: bool = False,
**kwargs: Any,
):
super().__init__(**kwargs)
self.update(
{
NameObject("/Subtype"): NameObject("/Highlight"),
NameObject("/F"): NumberObject(4),
NameObject("/Rect"): RectangleObject(rect),
NameObject("/QuadPoints"): quad_points,
NameObject("/C"): ArrayObject(
[FloatObject(n) for n in hex_to_rgb(highlight_color)]
),
}
)
if printing:
self.flags = AnnotationFlag.PRINT


class Ellipse(MarkupAnnotation):
Expand Down
5 changes: 4 additions & 1 deletion pypdf/generic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ def highlight(
rect: Union[RectangleObject, Tuple[float, float, float, float]],
quad_points: ArrayObject,
highlight_color: str = "ff0000",
printing: bool = False,
) -> DictionaryObject:
"""
Add a highlight annotation to the document.
Expand All @@ -319,6 +320,8 @@ def highlight(
quad_points: An ArrayObject of 8 FloatObjects. Must match a word or
a group of words, otherwise no highlight will be shown.
highlight_color: The color used for the highlight.
printing: Whether to print out the highlight annotation when the page
is printed.
Returns:
A dictionary object representing the annotation.
Expand All @@ -329,7 +332,7 @@ def highlight(
from ..annotations import Highlight

return Highlight(
rect=rect, quad_points=quad_points, highlight_color=highlight_color
rect=rect, quad_points=quad_points, highlight_color=highlight_color, printing=printing
)

@staticmethod
Expand Down
6 changes: 6 additions & 0 deletions tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,8 +883,14 @@ def test_annotation_builder_highlight(pdf_file_path):
FloatObject(705.4493),
]
),
printing=True,
)
writer.add_annotation(0, highlight_annotation)
for annot in writer.pages[0]["/Annots"]:
obj = annot.get_object()
subtype = obj["/Subtype"]
if subtype == "/Highlight":
assert obj["/F"] == NumberObject(4)

# Assert: You need to inspect the file manually
with open(pdf_file_path, "wb") as fp:
Expand Down

0 comments on commit b3ae07c

Please sign in to comment.