0% found this document useful (0 votes)
32 views1 page

Env (Copy)

The document provides a Python function using the PyMuPDF library to insert an image into a specified page of a PDF file. It includes parameters for the PDF path, image path, output path, page number, and dimensions for the image placement. An example usage of the function is also provided, demonstrating how to insert an image into the first page of a PDF.

Uploaded by

temp8varr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views1 page

Env (Copy)

The document provides a Python function using the PyMuPDF library to insert an image into a specified page of a PDF file. It includes parameters for the PDF path, image path, output path, page number, and dimensions for the image placement. An example usage of the function is also provided, demonstrating how to insert an image into the first page of a PDF.

Uploaded by

temp8varr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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
)

You might also like