pythonimagepdf

Insert image in pdf file using python


I want to insert an image in a pdf using a python script. I have given a jpg as well as a png file. I want to be able to specify a page number, x and y coordinates and heigth and width of the image. Then I want the image inserted at the given point.

I have found this question: How to add image to PDF file in Python?, but the answer is only providing a way to overlay another pdf page on an existing one.


Solution

  • Try with PyMuPDF.

    Here is a sample code but I didn't tested.

    # !/usr/bin/python
    
    import fitz
    
    input_file = "example.pdf"
    output_file = "example-with-barcode.pdf"
    barcode_file = "barcode.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)