I need to change the color of the rectangles with the fitz library in python

29 Views Asked by At

I have made this code in Python with the Fitz library, what I want is to change the color of the rectangles and to do so it accesses the fill part but it does not change it, if someone can help me

I was trying with this code, but you don't change it for me

import fitz

Ruta del archivo PDF
pdf_path = "rectangulos.pdf"

Abrir el archivo PDF
pdf_document = fitz.open(pdf_path)

Recorrer cada página del PDF
for page_number in range(len(pdf_document)):
Obtener la página actual
page = pdf_document[page_number]
page_drawings = page.get_drawings()

for drawing in page_drawings:

if drawing['items'][0][0] == 're':

drawing['fill'] = (1, 1, 1)

Guardar los cambios en un nuevo archivo PDF    
output_pdf_path = "rectangulos_modificados.pdf"
pdf_document.save(output_pdf_path)

print("¡Se ha modificado el color de todos los rectángulos a rojo en el archivo PDF!")]</kbd>`
1

There are 1 best solutions below

0
JustinH On

The problem involves what is being returned by page.get_drawings(), which is just a list of dictionaries (see the fitz docs). Essentially, modifying a dictionary only effects the dictionary (there are no side effects from this modification in the page or fitz objects). To create a modified version you will need to modify a fitz Page object (either from the existing pdf_document or a new fitz object). A simple example of adding a shape to a page is

for page in pdf_document:
   shape = page.new_shape()

   shape.drawRect(fitz.Rect(x0, y0, x1, y1))
   shape.finish(fill=(1, 1, 1))
   shape.commit()  # Apply the changes to the page

Notice the very purposeful commit to apply changes to shape, which is 'owned' by the Page object. You'd want to use the existing shapes to inform the geometry of the new shapes. Hopefully this sets you in the right direction! Keep making things =)

I'm also assuming the correctly formatted code is the following

import fitz

# Ruta del archivo PDF
pdf_path = "rectangulos.pdf"

# Abrir el archivo PDF
pdf_document = fitz.open(pdf_path)

# Recorrer cada página del PDF
for page_number in range(len(pdf_document)):
    # Obtener la página actual
    page = pdf_document[page_number]
    page_drawings = page.get_drawings()

    for drawing in page_drawings:
        if drawing['items'][0][0] == 're':
            drawing['fill'] = (1, 1, 1)

# Guardar los cambios en un nuevo archivo PDF
output_pdf_path = "rectangulos_modificados.pdf"
pdf_document.save(output_pdf_path)