0

I'm using PyMuPDF to replace images. But when I have a dictionary of images mapped to their bbox coordinates only the image in the first page gets replaced. How can I get all the images in the dictionary to be replaced? Here's my code: 'bbval' is the dictionary that looks like this: bbval dictionary

import fitz

src_pdf_filename = file_path
dst_pdf_filename = '/content/dest.pdf' #destination pdf
img_filename = '/content/logo.jpg' #the image that will be replacing the old ones


test=[]
val=0
for k in bbval:
  test.append(str(bbval[i])[5:int(str(bbval[i]).index(str(bbval[i])[-1]))])
  string=test[val].split(',')
  img_rect = fitz.Rect(float(string[0]),float(string[1]),float(string[2]),float(string[3]))#str(bbval[i])[5:int(str(bbval[i]).index(str(bbval[i])[-1]))]
  #print(bbval[k])
  document = fitz.open(src_pdf_filename)


  
  page = document[int(k[k.index('e')+1:k.index('-')])]
  #print('page: ',page)
  page.clean_contents()

  page.insertImage(img_rect, filename=img_filename,keep_proportion=False)
  val+=1

document.save(dst_pdf_filename)

document.close()
vbadwaj
  • 19
  • 2
  • 1
    `Rect(1.0, 1.0, -1.0, -1.0)` feels like some empty rectangle. Might that be the cause for no replacement? Just guessing from the information here, since there's no [mre] unfortunately. – HansHirse Jun 21 '21 at 09:55
  • Thank you very much, I fixed the empty rectangle part. The problem still persists. – vbadwaj Jun 21 '21 at 14:26

1 Answers1

0

I was crawling the internet for last two hours and found this working for me.

import fitz
image_path = "image1_0.png"
output_pdf = 'new_output.pdf'

pdf = fitz.open("bill.pdf")
page = pdf[0]

page.replace_image(xref=8,filename="image1_0.png")

# Save the modified PDF
pdf.save(output_pdf)
pdf.close()
halfer
  • 19,824
  • 17
  • 99
  • 186
Athar Gul
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 29 '23 at 20:39