1

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 1

3

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):

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think you need doc = None
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.