Search code examples
pythonmupdfpymupdf

PyMuPDF - Scale a Quad from center in all directions


I'm searching for text in a pdf and extracting a quad and adding a polygon_annot around it. But I would like to scale the polygon_annot. How can I do that?

Below is my code:

for inst in text_instances:
    inst =  inst.transform(fitz.Matrix(2, 2))
    print(inst)
    print(inst.rect)
    # re-ordering the points in list counter-clockwise
    inst[2], inst[3] = inst[3], inst[2]
    highlight = page.add_polygon_annot(inst)

i'm currently scaling it with inst.transform(fitz.Matrix(2, 2)), but this is to simply multiply the values. How do I scale the values frfom the center of the quad?


Solution

  • You can use morph to scale the quad.
    Reference to documentation: https://pymupdf.readthedocs.io/en/latest/quad.html#Quad.morph

    Below is the function that I'm using to scale the morph by its center:

    def getPolygon(quad, scale=1):
        [sumX, sumY] = [0, 0]
        for point in quad:
            sumX += point[0]
            sumY += point[1]
        avgX = sumX/4
        avgY = sumY/4
    
        # Scale the rectange using Quad.morph(): https://pymupdf.readthedocs.io/en/latest/quad.html#Quad.morph
        quad= quad.morph(fitz.Point(avgX,  avgY), fitz.Matrix(scale, scale))
        return quad