1
from __future__ import with_statement
3
__copyright__ = '2009, James Beal, james_@catbus.co.uk'
4
__docformat__ = 'restructuredtext en'
9
from calibre.utils.config import Config, StringConfig
10
from pyPdf import PdfFileWriter, PdfFileReader
12
def config(defaults=None):
13
desc = _('Options to control the transformation of pdf')
16
c = Config('trimpdf', desc)
18
c = StringConfig(defaults, desc)
19
c.add_opt('verbose', ['-v', '--verbose'], default=0, action='count',
20
help=_('Be verbose, useful for debugging. Can be specified multiple times for greater verbosity.'))
21
c.add_opt('output', ['-o', '--output'],default='cropped.pdf',
22
help=_('Path to output file. By default a file is created in the current directory.'))
23
c.add_opt('bottom_left_x', [ '-x', '--leftx'], default=default_crop,
24
help=_('Number of pixels to crop from the left most x (default is %d) ')%default_crop )
25
c.add_opt('bottom_left_y', [ '-y', '--lefty'], default=default_crop,
26
help=_('Number of pixels to crop from the left most y (default is %d) ')%default_crop )
27
c.add_opt('top_right_x', [ '-v', '--rightx'], default=default_crop,
28
help=_('Number of pixels to crop from the right most x (default is %d) ')%default_crop )
29
c.add_opt('top_right_y', [ '-w', '--righty'], default=default_crop,
30
help=_('Number of pixels to crop from the right most y (default is %d)')%default_crop )
31
c.add_opt('bounding', ['-b', '--bounding'],
32
help=_('A file generated by ghostscript which allows each page to be individually cropped [gs -dSAFER -dNOPAUSE -dBATCH -sDEVICE=bbox > bounding] '))
38
return c.option_parser(usage=_('''\
39
%prog [options] file.pdf
44
def main(args=sys.argv):
45
parser = option_parser()
46
opts, args = parser.parse_args(args)
48
source = os.path.abspath(args[1])
49
input_pdf = PdfFileReader(file(source, "rb"))
51
print "Unable to read input"
56
info = input_pdf.getDocumentInfo()
63
if opts.bounding != None:
65
bounding = open( opts.bounding , 'r' )
66
bounding_regex= re.compile('%%BoundingBox: (?P<bottom_x>[0-9]+) (?P<bottom_y>[0-9]+) (?P<top_x>[0-9]+) (?P<top_y>[0-9]+)')
68
print 'Error opening %s' % opts.bounding
70
output_pdf = PdfFileWriter(title=title,author=author)
71
for page_number in range (0, input_pdf.getNumPages() ):
72
page = input_pdf.getPage(page_number)
73
if opts.bounding != None:
75
line=bounding.readline()
76
match=bounding_regex.search(line)
79
page.mediaBox.upperRight = (match.group('top_x'),match.group('top_y'))
80
page.mediaBox.lowerLeft = (match.group('bottom_x'),match.group('bottom_y'))
82
page.mediaBox.upperRight = (page.bleedBox.getUpperRight_x()-opts.top_right_x,page.bleedBox.getUpperRight_y()-opts.top_right_y)
83
page.mediaBox.lowerLeft = (page.bleedBox.getLowerLeft_x()+opts.bottom_left_x,page.bleedBox.getLowerLeft_y()+opts.bottom_left_y)
84
output_pdf.addPage(page)
85
if opts.bounding != None:
87
output_file = file(opts.output, "wb")
88
output_pdf.write(output_file)
94
if __name__ == '__main__':