import fitz # PyMuPDF
def insert_image_into_pdf(
pdf_path: str,
image_path: str,
output_path: str,
page_number: int,
x: float,
y: float,
width: float,
height: float
):
# Open the PDF
pdf_doc = fitz.open(pdf_path)
# Ensure the page number is valid
if page_number < 0 or page_number >= len(pdf_doc):
raise ValueError("Page number out of range.")
page = pdf_doc[page_number]
# Define the rectangle where the image will be placed
rect = fitz.Rect(x, y, x + width, y + height)
# Insert the image
page.insert_image(rect, filename=image_path)
# Save to output
pdf_doc.save(output_path)
pdf_doc.close()
print(f"Image inserted on page {page_number + 1} at ({x}, {y}) and saved to
{output_path}")
# Example usage
insert_image_into_pdf(
pdf_path="example.pdf",
image_path="logo.png",
output_path="output.pdf",
page_number=0, # first page
x=100, # horizontal position
y=150, # vertical position
width=200, # image width
height=100 # image height
)