Skip to content

Instantly share code, notes, and snippets.

@aleperno
Created Sep 6, 2021
Embed
What would you like to do?
XObject PDf helper
import re
from io import BytesIO
from PIL import Image
from pdfrw.objects import PdfName
from pdfrw.findobjs import find_objects
from pdfrw import PdfReader, PdfWriter
original = "/tmp/expanded.pdf"
nuevo_file = "/tmp/nuevo.pdf"
regex = "\(data/res/(?P<image_filename>.*)\)"
regex_number = "img_(?P<number>.*).jpg"
reader = PdfReader(original, password="C9CD86F5401F4C808AE9CF2260A483C8")
xobjects = list(find_objects(reader, valid_types=(PdfName.XObject,), valid_subtypes=(PdfName.Image,)))
def new_pdf(xobjects):
for xobject in xobjects:
if '/F' in xobject:
#print(xobject)
m = re.match(regex, xobject['/F'])
if m:
filename = m.groupdict()['image_filename']
print(filename)
image = Image.open(f"/tmp/images/{filename}")
rgb_image = image
if image.format != "JPEG" or image.mode == "L":
rgb_image = image.convert("RGB")
xobject.stream = rgb_image.tobytes().decode('latin1')
nuevo = PdfWriter(nuevo_file, trailer=reader)
nuevo.write()
new_pdf(xobjects)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment