Last active
December 19, 2015 21:49
-
-
Save pshchelo/6023073 to your computer and use it in GitHub Desktop.
Convert a PDF or PS files to CBZ files via Ghostscript
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 python | |
'''Convert PDF or PS files to CBZ files | |
CBZ files are ZIP-compressed sets of image files, this script in particular creates PNG images | |
it takes filename and target resolution (DPI) as arguments | |
''' | |
import os, sys | |
import getopt, shutil | |
from tempfile import mkdtemp | |
from glob import glob | |
import zipfile | |
from optparse import OptionParser | |
if sys.platform == 'win32': | |
ghostscript = 'gswin32c' | |
else: | |
ghostscript == 'gs' | |
def usage(): | |
help = '''Convert PDF or PS to CBZ | |
Usage: | |
gs2png -r DPI file1 file2 ... | |
where | |
DPI - target resolution in dots per inch | |
''' | |
return help | |
def png_to_cbz(imgdir, name): | |
imgfiles = glob(os.path.join(imgdir,'*.png')) | |
cbzfile = zipfile.ZipFile(name+'.cbz', 'w', zipfile.ZIP_DEFLATED) | |
for file in imgfiles: | |
cbzfile.write(file, os.path.basename(file)) | |
cbzfile.close() | |
def gs_to_cbz(dpi, filename): | |
name = os.path.basename(filename) | |
base, ext = os.path.splitext(name) | |
try: | |
# create temp dir | |
imgdir = mkdtemp('_gs2cbz', 'name_') | |
#convert file to images creating the dir 'filename' | |
outfname = os.path.join(imgdir, base+'-%03d.png') | |
gsparams = { | |
'ghostscript':ghostscript, | |
'dpi':dpi, | |
'outfile':outfname, | |
'infile':filename, | |
'other':'-dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -dTextAlphaBits=4', | |
} | |
os.system('%(ghostscript)s %(other)s -r%(dpi)i -sOutputFile="%(outfile)s" "%(infile)s"' %gsparams) | |
#pack images to the zip archive next to the original file | |
png_to_cbz(imgdir, base) | |
except: | |
print 'There were some errors.' | |
finally: | |
#remove temp dir with all files | |
shutil.rmtree(imgdir) | |
def main(): | |
parser = OptionParser('Convert files to CBZ book with GhostScript') | |
#default dpi is approximately equal to dpi of Nokia 5800 screen | |
parser.add_option('--dpi', type='int', dest='dpi', default=228) | |
options, args = parser.parse_args() | |
for filename in args: | |
gs_to_cbz(options.dpi, filename) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment