Skip to content

Instantly share code, notes, and snippets.

Created Sep 6, 2021
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:
m = re.match(regex, xobject['/F'])
if m:
filename = m.groupdict()['image_filename']
image ="/tmp/images/{filename}")
rgb_image = image
if image.format != "JPEG" or image.mode == "L":
rgb_image = image.convert("RGB") = rgb_image.tobytes().decode('latin1')
nuevo = PdfWriter(nuevo_file, trailer=reader)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment