Skip to content

Instantly share code, notes, and snippets.

@MuhammadSawalhy
Last active July 25, 2022 19:03
Show Gist options
  • Save MuhammadSawalhy/fb21fcb8275c2042e6cf22307e06bc8d to your computer and use it in GitHub Desktop.
Save MuhammadSawalhy/fb21fcb8275c2042e6cf22307e06bc8d to your computer and use it in GitHub Desktop.
Replace images in a pdf using python
import math
import glob
from PIL import Image
for img in glob.glob("images/*.png"):
# for img in ["imageroot-014.png"]:
with Image.open(img) as im:
x = math.floor(im.size[0]/2)
px = im.getpixel((x,-1))
if px == (12,12,12):
print(img)
import fitz
from rich import inspect
# This creates the Document object doc
doc: fitz.Document = fitz.open("file.pdf")
for page in doc:
for img in page.get_images():
xref = img[0]
pix = fitz.Pixmap(doc, xref)
bg_color = pix.pixel(pix.width - 1, int(pix.height / 2))
if bg_color == (12,12,12):
pix.invert_irect()
rect = page.get_image_bbox(img[-2])
page.insert_image(rect, pixmap=pix, keep_proportion=False)
# doc.save(filename=r"file.new.pdf", clean=True)
# doc.save(filename=r"file.new.pdf", clean=True, garbage=4)
doc.save(filename=r"file.new.pdf", clean=True, deflate=4, deflate_images=1, deflate_fonts=1)
doc.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment