0

I'am trying to add a png sign to the PDF by using a python code and the code that i am running is I am using PyMuPDF and have used fitz library.

import fitz

input_file = "example.pdf"
output_file = "example-with-sign.pdf"
barcode_file = "sign.png"

# define the position (upper-right corner)
image_rectangle = fitz.Rect(450,20,550,120)

# retrieve the first page of the PDF
file_handle = fitz.open(input_file)
first_page = file_handle[0]

# add the image
first_page.insertImage(image_rectangle, fileName=barcode_file)

file_handle.save(output_file)
  • shouldn't it be `insert_image` (with underline): https://pymupdf.readthedocs.io/en/latest/page.html#Page.insert_image – Sajad Sep 07 '22 at 09:50
  • 2
    [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – asynts Sep 07 '22 at 09:57
  • 1
    I don't think this really matters for this question anymore, because the comment from @Sajad probably answered it (did it?). But for next time, keep the error message just copy it into a code block in the question. – asynts Sep 07 '22 at 11:09

2 Answers2

2

Thank you for 'insert_image' correction. It currently works as follows:

import fitz

input_file = "example.pdf"
output_file = "example-with-sign.pdf"


# define the position (upper-right corner)
image_rectangle = fitz.Rect(450,20,550,120)

# retrieve the first page of the PDF
file_handle = fitz.open(input_file)
first_page = file_handle[0]

img = open("sign.png", "rb").read()  # an image file
img_xref = 0

first_page.insert_image(image_rectangle,stream=img,xref=img_xref)

file_handle.save(output_file)
1

I got stuck with a very similar error to your question. The insert_image solution you posted is correct, but I think the reason is that from a certain version of PyMuPDF, camelCase (which was good to use before) was totally deprecated, and was replaced by under_score_case. I think it's necessary to mark the PyMuPDF version here, just in case somebody was confused by these two coding styles when they met similar errors in the future.

Currently, I'm under PyMuPDF==1.21.0, in which I'm pretty sure camelCase was totally deprecated. So if you met a similar error, just try to convert your method someMethod() into some_method().

See: doc is here

Vigor
  • 1,706
  • 3
  • 26
  • 47