Replace PDF JPG Images with PNG – Image Scale & Placement Issue

I’m very new to coding so any help is appreciated greatly!

I’ve written a python script that’s suppose to look through the JPG images in a PDF file and swap them for png equivalents that I have in a directory on my computer. Basically the pngs are just the same as the JPG image but with the white backgrounds removed.

The script does successfully remove the original jpg’s and swap in the png equivalent, but unfortunately the png images end up not being the same scale/size as the original jpg and they don’t get placed in the same spot that the original JPG was. Any idea what I’m doing wrong?

I’m running it from terminal on a Macbook pro.

Thank you for your help!

import fitz  # PyMuPDF
from PIL import Image
import os
from io import BytesIO

# Path to the PDF file
pdf_path = '/example/example/example.pdf'
# Path to the directory containing PNG files
png_dir = '/Users/example/example'
# Output PDF path
output_pdf_path = '/Users/example/example'

# Open the PDF
pdf_document = fitz.open(pdf_path)

# Iterate through the pages
for page_num in range(len(pdf_document)):
    page = pdf_document.load_page(page_num)
    images = page.get_images(full=True)
    
    for img_index, img in enumerate(images):
        xref = img[0]
        
        # Get the image information
        base_image = pdf_document.extract_image(xref)
        image_name = f"img_{xref}"
        image_ext = base_image["ext"]
        
        # Generate file names for extracted and replacement images
        old_img_path = f"{image_name}.{image_ext}"
        new_img_path = os.path.join(png_dir, f"{image_name}.png")

        # If a corresponding PNG file exists, replace the image
        if os.path.exists(new_img_path):
            print(f"Replacing {old_img_path} with {new_img_path}")
            # Load the new image
            image_obj = Image.open(new_img_path)
            
            # Get the dimensions of the new image
            new_width, new_height = image_obj.size
            
            # Calculate the position to insert the new image
            x, y = img[2], img[3]  # Top-left corner coordinates of the original image
            rect = fitz.Rect(x, y, x + new_width, y + new_height)
            
            # Convert the image to bytes for insertion
            image_bytes = BytesIO()
            image_obj.save(image_bytes, format='PNG')
            image_bytes = image_bytes.getvalue()
            
            # Insert the new image in the same position
            page.insert_image(rect, stream=image_bytes)
            
            # Remove the old image
            page.delete_image(xref)
        else:
            print(f"No corresponding PNG found for {old_img_path}, skipping...")

# Save the updated PDF
pdf_document.save(output_pdf_path)
pdf_document.close()

New contributor

aurora912 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật