Skip to content

Instantly share code, notes, and snippets.

@arleite
Last active May 2, 2023 21:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arleite/59d8b861159e53bafbefc83434c9b511 to your computer and use it in GitHub Desktop.
Save arleite/59d8b861159e53bafbefc83434c9b511 to your computer and use it in GitHub Desktop.
Replace image PDF
import sys
import os
from PIL import Image
# Include the \n to ensure extact match and avoid partials from 111, 211...
OBJECT_ID = "\n11 0 obj"
def replace_image(filepath, new_image):
f = open(filepath, "rb")
contents = f.read()
f.close()
image = Image.open(new_image)
width, height = image.size
length = os.path.getsize(new_image)
start = contents.find(str.encode(OBJECT_ID))
stream = contents.find(str.encode("stream"), start)
image_beginning = stream + 7
# Process the metadata and update with new image's details
meta = contents[start: image_beginning]
meta = meta.split(str.encode("\n"))
new_meta = []
for item in meta:
if str.encode("/Width") in item:
new_meta.append("/Width {0}".format(width))
elif str.encode("/Height") in item:
new_meta.append("/Height {0}".format(height))
elif str.encode("/Length") in item:
new_meta.append("/Length {0}".format(length))
else:
new_meta.append(item.decode(encoding='utf-8'))
new_meta = "\n".join(new_meta)
# Find the end location
image_end = contents.find(str.encode("endstream"), stream) - 1
# read the image
f = open(new_image, "rb")
new_image_data = f.read()
f.close()
# recreate the PDF file with the new_sign
with open(filepath, "wb") as f:
f.write(contents[:start])
f.write(str.encode("\n"))
f.write(str.encode(new_meta))
f.write(new_image_data)
f.write(contents[image_end:])
#replace_image('pdfuncompressedfile.pdf' 'new_image')
if __name__ == "__main__":
if len(sys.argv) == 3:
replace_image(sys.argv[1], sys.argv[2])
else:
print("Usage: python process.py <pdfuncompressedfile> <new_image>")
@JasonKitty
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment