Search code examples
python-3.xpymupdf

PyMuPDF how do I remove annotations?


I am using PyMuPDF and trying to loop through a list of strings and highlight them before taking an image and moving to the next string.

The code below does what I need but the annotation remains after each loop and I would like to remove them after the image is taken.
An example image below shows the word "command" highlighted but the previous strings "Images" and "filename" are still highlighted, since I will have hundreds of these images compiled into a report, I would like to make it stand out more clearly.

Is there something like page.remove(highlight)?

pymupdf output sample image

for pi in range(doc.pageCount):
    page = doc[pi]
    for tag in text_list:

        text = tag
        text_instances = page.searchFor(text)

        five_percent_height = (page.rect.br.y - page.rect.tl.y)*0.05
        five_percent_width = (page.rect.br.x - page.rect.tl.x)*0.05

        for inst in text_instances:
            inst_counter += 1
            highlight = page.addSquigglyAnnot(inst)            

            tl_pt = fitz.Point(max(page.rect.tl.x, inst.tl.x - five_percent_width), max(page.rect.tl.y, inst.tl.y - five_percent_height))
            br_pt = fitz.Point(min(page.rect.br.x, inst.br.x + five_percent_width), min(page.rect.br.y, inst.br.y + five_percent_height))

            hl_clip = fitz.Rect(tl_pt, br_pt)

            zoom_mat = fitz.Matrix(4, 4)
            pix = page.getPixmap(matrix=zoom_mat, clip = hl_clip)
            >I want to remove the annotation here

Solution

  • I found an acceptable solution was to just set the opacity to 0% after taking the screenshot.

    pix = page.getPixmap(matrix=zoom_mat, clip = hl_clip)
    highlight.setOpacity(0)
    highlight.update()