1
# -*- coding: utf-8 -*-
2
from __future__ import with_statement
5
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
6
__docformat__ = 'restructuredtext en'
13
from optparse import OptionGroup, Option
15
from calibre.utils.config import OptionParser
16
from calibre.utils.logging import Log
17
from calibre.constants import preferred_encoding
18
from calibre.customize.conversion import OptionRecommendation
19
from calibre.ebooks.pdf.verify import is_valid_pdf, is_encrypted
21
from pyPdf import PdfFileWriter, PdfFileReader
23
USAGE = '\n%prog %%name ' + _('''\
24
[options] file.pdf password
30
OptionRecommendation(name='output', recommended_value='encrypted.pdf',
31
level=OptionRecommendation.HIGH, long_switch='output', short_switch='o',
32
help=_('Path to output file. By default a file is created in the current directory.')),
35
def print_help(parser, log):
36
help = parser.format_help().encode(preferred_encoding, 'replace')
39
def option_parser(name):
40
usage = USAGE.replace('%%name', name)
41
return OptionParser(usage=usage)
43
def option_recommendation_to_cli_option(add_option, rec):
45
switches = ['-'+opt.short_switch] if opt.short_switch else []
46
switches.append('--'+opt.long_switch)
47
attrs = dict(dest=opt.name, help=opt.help,
48
choices=opt.choices, default=rec.recommended_value)
49
add_option(Option(*switches, **attrs))
51
def add_options(parser):
52
group = OptionGroup(parser, _('Encrypt Options:'), _('Options to control the transformation of pdf'))
53
parser.add_option_group(group)
54
add_option = group.add_option
57
option_recommendation_to_cli_option(add_option, rec)
59
def encrypt(pdf_path, out_path, password, metadata=None):
64
title = metadata.title
65
author = authors_to_string(metadata.authors)
67
out_pdf = PdfFileWriter(title=title, author=author)
69
pdf = PdfFileReader(open(os.path.abspath(pdf_path), 'rb'))
70
for page in pdf.pages:
73
with open(out_path, 'wb') as out_file:
74
out_pdf.encrypt(str(password))
75
out_pdf.write(out_file)
77
def main(args=sys.argv, name=''):
79
parser = option_parser(name)
82
opts, args = parser.parse_args(args)
86
print 'Error: A PDF file and decryption password is required.\n'
87
print_help(parser, log)
90
if not is_valid_pdf(args[0]):
91
print 'Error: Could not read file `%s`.' % args[0]
94
if is_encrypted(args[0]):
95
print 'Error: file `%s` is already encrypted.' % args[0]
98
mi = metadata_from_formats([args[0]])
100
encrypt(args[0], opts.output, args[1], mi)
104
if __name__ == '__main__':