1 # -*- coding: utf-8 -*-
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
7 # \author Thibaut Cuvelier
9 # Full author contact details are available in file CREDITS
12 # python docbook2epub.py java_binary in.docbook out.epub
14 from __future__ import print_function
16 # import glob # Not powerful enough before Python 3.5.
24 def parse_arguments():
25 if len(sys.argv) != 4:
27 own_path, java_path, input, output = sys.argv
28 script_folder = os.path.dirname(own_path) + '/../'
30 print('Generating ePub with the following parameters:')
35 return java_path, input, output, script_folder
38 def create_temporary_folder():
39 output_dir = tempfile.mkdtemp().replace('\\', '/')
40 print('Temporary output directory:')
45 def start_xslt_transformation(input, output_dir, script_folder, java_path):
46 xslt = script_folder + 'docbook/epub3/chunk.xsl'
47 saxon_jar = script_folder + 'scripts/saxon6.5.5.jar'
48 saxon_params = 'base.dir=%s' % output_dir
49 command = '"' + java_path + '" -jar "' + saxon_jar + '" "' + input + '" "' + xslt + '" "' + saxon_params + '"'
51 print('XSLT style sheet to use:')
53 print('Command to execute:')
56 quoted_command = command
58 # On Windows, it is typical to have spaces in folder names, and that requires to wrap the whole command
59 # in quotes. On Linux, this might create errors when starting the command.
60 quoted_command = '"' + command + '"'
61 # This could be simplified by using subprocess.run, but this requires Python 3.5.
63 if os.system(quoted_command) != 0:
64 print('docbook2epub fails')
65 shutil.rmtree(output_dir, ignore_errors=True)
68 print('Generated ePub contents.')
71 def create_zip_archive(output, output_dir):
72 with zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as zip:
73 # Python 3.5 brings the `recursive` argument. For older versions, this trick is required...
74 # for file in glob.glob(output_dir + '/**/*', recursive=True):
75 for file in [os.path.join(dp, f) for dp, dn, filenames in os.walk(output_dir) for f in filenames]:
76 zip.write(file, os.path.relpath(file, output_dir), compress_type=zipfile.ZIP_STORED)
78 shutil.rmtree(output_dir)
79 print('Generated ePub.')
82 if __name__ == '__main__':
83 java_path, input, output, script_folder = parse_arguments()
84 output_dir = create_temporary_folder()
85 start_xslt_transformation(input, output_dir, script_folder, java_path)
86 create_zip_archive(output, output_dir)