I want to add an annotation to an existing PDF, specifically a highlight annotation.
This is displayed as a translucent rectangle, marking one or more pieces of text.
1 Answer
Disclaimer: I am the author of the library being used in this answer.
This answer uses borb a pure python PDF library.
Its code can be found here.
We start by reading the PDF:
doc = None
with open("input.pdf", "rb") as in_file_handle:
doc = PDF.loads(in_file_handle)
Next we add the annotation:
# add annotation
doc.get_page(0).append_highlight_annotation(
rectangle=Rectangle(
Decimal(72.86), Decimal(486.82), Decimal(129), Decimal(13)
),
contents="Lorem Ipsum Dolor Sit Amet",
color=X11Color("Yellow"),
)
Now we can store the PDF document again:
with open("output.pdf", "wb") as out_file_handle:
PDF.dumps(out_file_handle, doc)
The output should look something like this (at least the annotation part):
2 Comments
U13-Forward
I don't think you need
doc = NoneJoris Schellekens
I also try to minimize the warnings I get when running static code analysis. I got a warning that doc was potentially undefined. So I added the
doc = None