Created
November 21, 2014 05:12
-
-
Save holloway/5e3c424194550dae7450 to your computer and use it in GitHub Desktop.
Extracting images from PDFs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import sys | |
pdf = open(sys.argv[1], "rb").read() | |
minimum_seek = 20 | |
startfix = 0 | |
endfix = 2 | |
i = 0 | |
formats = { | |
"jpeg": { | |
"start": b'\xff\xd8', | |
"end": b'\xff\xd9' | |
} | |
} | |
filenumber = 0 | |
while True: | |
istream = pdf.find(b'stream', i) | |
if istream < 0: | |
break | |
print(istream) | |
iend = pdf.find(b'endstream', istream) | |
if iend < 0: | |
raise Exception("Didn't find end of stream!") | |
istart = pdf.find(formats["jpeg"]["start"], istream, istream + minimum_seek) | |
if istart < 0: | |
iend = pdf.find(b'endstream', istart) | |
data = pdf[istream:iend] | |
datafile = open("data%d" % filenumber, "wb") | |
datafile.write(data) | |
datafile.close() | |
i = istream + minimum_seek | |
filenumber += 1 | |
continue | |
iend = pdf.find(formats["jpeg"]["end"], iend - minimum_seek) | |
if iend < 0: | |
raise Exception("Didn't find end of JPG!") | |
istart += startfix | |
iend += endfix | |
print("JPG %d from %d to %d" % (filenumber, istart, iend)) | |
jpg = pdf[istart:iend] | |
jpgfile = open("jpg%d.jpg" % filenumber, "wb") | |
jpgfile.write(jpg) | |
jpgfile.close() | |
filenumber += 1 | |
i = iend |
I used this a couple years ago in python 2 and it worked. Recently I tried this again in both python 2 and python 3, but after a few loop, it raise Exception("Didn't find end of stream!"). It seems to me there is some change with pdf. Do you think so?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit to http://nedbatchelder.com/blog/200712/extracting_jpgs_from_pdfs.html
I ported it to Python3 and am working on extracting other image types.