5

Hi I am trying to change the highlight color in a pdf but not able to do so. The default highlight color is yellow but i want to change it Following is my code:

    import fitz

    doc = fitz.open(r"path\input.pdf")

    page=doc[0]
    text="some text"
    text_instances = page.searchFor(text)


    for inst in text_instances:
        highlight = page.addHighlightAnnot(inst)
        highlight.setColors(colors='Red')
        highlight.update()


    doc.save(r"path\output.pdf")    

Also how do i search for the entire pdf together and not just one page

and how can i highlight text on an image given in a pdf

Gavya Mehta
  • 211
  • 6
  • 20
  • can you verify "page.addHighlightAnnot(inst)" is not returning None – Prasun Chakraborty Mar 06 '20 at 06:17
  • using 'page.addHighlightAnnot(inst)' is highlighting the text with yellow color .I tried the below steps to change the highlight color but it did not work... basically "highlight.setColors(colors='Red') highlight.update()" is not doing anything right now – Gavya Mehta Mar 06 '20 at 07:16
  • [Enda Crossan](https://stackoverflow.com/users/20478744/enda-crossan), Nov 17 at 16:07: If anyone is having issues with the above question, update: `text_instances = page.searchFor(text)` with `text_instances = page.search_for(text)`, as the instance name has been updated in later versions of fitz/PyMuPDF. – greybeard Nov 25 '22 at 23:13

2 Answers2

3

I think the setColors expects a dictionary, check the documentation here

import fitz

doc = fitz.open("test.pdf")


page = doc[0]

text = "result"

text_instances = page.searchFor(text)

for inst in text_instances:
    highlight = page.addHighlightAnnot(inst)
    highlight.setColors({"stroke":(0, 0, 1), "fill":(0.75, 0.8, 0.95)})
    highlight.update()


doc.save("output.pdf")

enter image description here

ybl
  • 1,510
  • 10
  • 16
2

I tried the following and it worked

import fitz

doc = fitz.open(r"path\to\pdf\file.pdf")
page = doc[6]
# highlighting a pre-determined coordinate
highlight = page.addHighlightAnnot((10, 628.9634743875279, 642.0, 640.9634743875279))
highlight.set_colors(stroke=[1, 0.8, 0.8]) # light red color (r, g, b)
highlight.update()

In this code snippet, I am just trying to annotate using coordinates of the text and I am getting these coordinates from external code. Some more colors I used:

highlight.set_colors(stroke=[0.5, 1, 1]) # light aqua
highlight.set_colors(stroke=[0.5, 0, 0]) # dark brown

Simple way to determine the color will be to multiply 255 to each of these values.

Divide 255 from each values for other way round (converting RGB to this notation)

Example:

stroke=[0.5, 1, 1] # RGB(255*0.5, 255*1, 255*1) = RGB(127, 255, 255)
sourin_karmakar
  • 389
  • 3
  • 10