home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1047 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  6.2 KB  |  131 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL v3'
  5. __copyright__ = '2009, James Beal <james_@catbus.co.uk>, 2009, John Schember <john@nachtimwald.com>'
  6. __docformat__ = 'restructuredtext en'
  7. import sys
  8. import re
  9. from decimal import Decimal
  10. from optparse import OptionGroup, Option
  11. from calibre.ebooks.metadata.meta import metadata_from_formats
  12. from calibre.ebooks.metadata import authors_to_string
  13. from calibre.utils.config import OptionParser
  14. from calibre.utils.logging import Log
  15. from calibre.constants import preferred_encoding
  16. from calibre.customize.conversion import OptionRecommendation
  17. from calibre.ebooks.pdf.verify import is_valid_pdf, is_encrypted
  18. from pyPdf import PdfFileWriter, PdfFileReader
  19. DEFAULT_CROP = 10
  20. USAGE = '\n%prog %%name ' + _('[options] file.pdf\n\nCrop a PDF file.\n')
  21. OPTIONS = set([
  22.     OptionRecommendation(name = 'output', recommended_value = 'cropped.pdf', level = OptionRecommendation.HIGH, long_switch = 'output', short_switch = 'o', help = _('Path to output file. By default a file is created in the current directory.')),
  23.     OptionRecommendation(name = 'bottom_left_x', recommended_value = DEFAULT_CROP, level = OptionRecommendation.LOW, long_switch = 'left-x', short_switch = 'x', help = _('Number of pixels to crop from the left most x (default is %s)') % DEFAULT_CROP),
  24.     OptionRecommendation(name = 'bottom_left_y', recommended_value = DEFAULT_CROP, level = OptionRecommendation.LOW, long_switch = 'left-y', short_switch = 'y', help = _('Number of pixels to crop from the left most y (default is %s)') % DEFAULT_CROP),
  25.     OptionRecommendation(name = 'top_right_x', recommended_value = DEFAULT_CROP, level = OptionRecommendation.LOW, long_switch = 'right-x', short_switch = 'v', help = _('Number of pixels to crop from the right most x (default is %s)') % DEFAULT_CROP),
  26.     OptionRecommendation(name = 'top_right_y', recommended_value = DEFAULT_CROP, level = OptionRecommendation.LOW, long_switch = 'right-y', short_switch = 'w', help = _('Number of pixels to crop from the right most y (default is %s)') % DEFAULT_CROP),
  27.     OptionRecommendation(name = 'bounding', recommended_value = None, level = OptionRecommendation.LOW, long_switch = 'bounding', short_switch = 'b', help = _('A file generated by ghostscript which allows each page to be individually cropped `gs -dSAFER -dNOPAUSE -dBATCH -sDEVICE=bbox file.pdf 2> bounding`'))])
  28.  
  29. def print_help(parser, log):
  30.     help = parser.format_help().encode(preferred_encoding, 'replace')
  31.     log(help)
  32.  
  33.  
  34. def option_parser(name):
  35.     usage = USAGE.replace('%%name', name)
  36.     return OptionParser(usage = usage)
  37.  
  38.  
  39. def option_recommendation_to_cli_option(add_option, rec):
  40.     opt = rec.option
  41.     switches = None if opt.short_switch else []
  42.     switches.append('--' + opt.long_switch)
  43.     attrs = dict(dest = opt.name, help = opt.help, choices = opt.choices, default = rec.recommended_value)
  44.     add_option(Option(*switches, **attrs))
  45.  
  46.  
  47. def add_options(parser):
  48.     group = OptionGroup(parser, _('Crop Options:'), _('Options to control the transformation of pdf'))
  49.     parser.add_option_group(group)
  50.     add_option = group.add_option
  51.     for rec in OPTIONS:
  52.         option_recommendation_to_cli_option(add_option, rec)
  53.     
  54.  
  55.  
  56. def crop_pdf(pdf_path, opts, metadata = None):
  57.     if metadata == None:
  58.         title = _('Unknown')
  59.         author = _('Unknown')
  60.     else:
  61.         title = metadata.title
  62.         author = authors_to_string(metadata.authors)
  63.     input_pdf = PdfFileReader(open(pdf_path, 'rb'))
  64.     bounding_lines = []
  65.     if opts.bounding != None:
  66.         
  67.         try:
  68.             bounding = open(opts.bounding, 'r')
  69.             bounding_regex = re.compile('%%BoundingBox: (?P<bottom_x>\\d+) (?P<bottom_y>\\d+) (?P<top_x>\\d+) (?P<top_y>\\d+)')
  70.         except:
  71.             raise Exception('Error reading %s' % opts.bounding)
  72.  
  73.         lines = bounding.readlines()
  74.         for line in lines:
  75.             if line.startswith('%%BoundingBox:'):
  76.                 bounding_lines.append(line)
  77.                 continue
  78.         
  79.         if len(bounding_lines) != input_pdf.numPages:
  80.             raise Exception('Error bounding file %s page count does not correspond to specified pdf' % opts.bounding)
  81.         len(bounding_lines) != input_pdf.numPages
  82.     
  83.     output_pdf = PdfFileWriter(title = title, author = author)
  84.     blines = iter(bounding_lines)
  85.     for page in input_pdf.pages:
  86.         if bounding_lines != []:
  87.             mo = bounding_regex.search(blines.next())
  88.             if mo == None:
  89.                 raise Exception('Error in bounding file %s' % opts.bounding)
  90.             mo == None
  91.             page.mediaBox.upperRight = (float(mo.group('top_x')), Decimal(mo.group('top_y')))
  92.             page.mediaBox.lowerLeft = (float(mo.group('bottom_x')), Decimal(mo.group('bottom_y')))
  93.         else:
  94.             page.mediaBox.upperRight = (page.bleedBox.getUpperRight_x() - Decimal(opts.top_right_x), page.bleedBox.getUpperRight_y() - Decimal(opts.top_right_y))
  95.             page.mediaBox.lowerLeft = (page.bleedBox.getLowerLeft_x() + Decimal(opts.bottom_left_x), page.bleedBox.getLowerLeft_y() + Decimal(opts.bottom_left_y))
  96.         output_pdf.addPage(page)
  97.     
  98.     
  99.     try:
  100.         output_file = _[1]
  101.         output_pdf.write(output_file)
  102.     finally:
  103.         pass
  104.  
  105.  
  106.  
  107. def main(args = sys.argv, name = ''):
  108.     log = Log()
  109.     parser = option_parser(name)
  110.     add_options(parser)
  111.     (opts, args) = parser.parse_args(args)
  112.     args = args[1:]
  113.     if len(args) < 1:
  114.         print 'Error: A PDF file is required.\n'
  115.         print_help(parser, log)
  116.         return 1
  117.     if not is_valid_pdf(args[0]):
  118.         print 'Error: Could not read file `%s`.' % args[0]
  119.         return 1
  120.     if is_encrypted(args[0]):
  121.         print 'Error: file `%s` is encrypted.' % args[0]
  122.         return 1
  123.     mi = metadata_from_formats([
  124.         args[0]])
  125.     crop_pdf(args[0], opts, mi)
  126.     return 0
  127.  
  128. if __name__ == '__main__':
  129.     sys.exit(main())
  130.  
  131.