1
# -*- coding: utf-8 -*-
2
from __future__ import with_statement
5
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
6
__docformat__ = 'restructuredtext en'
9
Reverse content of PDF.
13
from optparse import OptionGroup, Option
15
from calibre.ebooks.metadata.meta import metadata_from_formats
16
from calibre.ebooks.metadata import authors_to_string
17
from calibre.utils.config import OptionParser
18
from calibre.utils.logging import Log
19
from calibre.constants import preferred_encoding
20
from calibre.customize.conversion import OptionRecommendation
21
from calibre.ebooks.pdf.verify import is_valid_pdf, is_encrypted
23
from pyPdf import PdfFileWriter, PdfFileReader
25
USAGE = '\n%prog %%name ' + _('''\
32
OptionRecommendation(name='output', recommended_value='reversed.pdf',
33
level=OptionRecommendation.HIGH, long_switch='output', short_switch='o',
34
help=_('Path to output file. By default a file is created in the current directory.')),
37
def print_help(parser, log):
38
help = parser.format_help().encode(preferred_encoding, 'replace')
41
def option_parser(name):
42
usage = USAGE.replace('%%name', name)
43
return OptionParser(usage=usage)
45
def option_recommendation_to_cli_option(add_option, rec):
47
switches = ['-'+opt.short_switch] if opt.short_switch else []
48
switches.append('--'+opt.long_switch)
49
attrs = dict(dest=opt.name, help=opt.help,
50
choices=opt.choices, default=rec.recommended_value)
51
add_option(Option(*switches, **attrs))
53
def add_options(parser):
54
group = OptionGroup(parser, _('Reverse Options:'), _('Options to control the transformation of pdf'))
55
parser.add_option_group(group)
56
add_option = group.add_option
59
option_recommendation_to_cli_option(add_option, rec)
61
def reverse(pdf_path, out_path, metadata=None):
66
title = metadata.title
67
author = authors_to_string(metadata.authors)
69
out_pdf = PdfFileWriter(title=title, author=author)
71
pdf = PdfFileReader(open(os.path.abspath(pdf_path), 'rb'))
72
for page in reversed(pdf.pages):
75
with open(out_path, 'wb') as out_file:
76
out_pdf.write(out_file)
78
def main(args=sys.argv, name=''):
80
parser = option_parser(name)
83
opts, args = parser.parse_args(args)
87
print 'Error: A PDF file is required.\n'
88
print_help(parser, log)
91
if not is_valid_pdf(args[0]):
92
print 'Error: Could not read file `%s`.' % args[0]
95
if is_encrypted(args[0]):
96
print 'Error: file `%s` is encrypted.' % args[0]
99
mi = metadata_from_formats([args[0]])
101
reverse(args[0], opts.output, mi)
105
if __name__ == '__main__':