##// END OF EJS Templates
Rename SVG2PDFTransformer class
Jonathan Frederic -
Show More
@@ -0,0 +1,203 b''
1 #!/usr/bin/env python
2 """NBConvert is a utility for conversion of IPYNB files.
3
4 Commandline interface for the NBConvert conversion utility. Read the
5 readme.rst for usage information
6 """
7 #-----------------------------------------------------------------------------
8 #Copyright (c) 2013, the IPython Development Team.
9 #
10 #Distributed under the terms of the Modified BSD License.
11 #
12 #The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
14
15 #-----------------------------------------------------------------------------
16 #Imports
17 #-----------------------------------------------------------------------------
18
19 #Stdlib imports
20 from __future__ import print_function
21 import sys
22 import os
23 import glob
24
25 #From IPython
26 from IPython.core.application import BaseIPythonApplication
27 from IPython.config.application import catch_config_error
28 from IPython.utils.traitlets import Unicode, List, Instance, DottedObjectName, Type
29 from IPython.utils.importstring import import_item
30
31 from .exporters.export import export_by_name, get_export_names, ExporterNameError
32 from .exporters.exporter import Exporter
33 from .writers.base import WriterBase
34 from .utils.base import NbConvertBase
35
36 #-----------------------------------------------------------------------------
37 #Classes and functions
38 #-----------------------------------------------------------------------------
39
40 class NbConvertApp(BaseIPythonApplication):
41 """Application used to convert to and from notebook file type (*.ipynb)"""
42
43 <<<<<<< HEAD
44 name = 'ipython-nbconvert'
45 =======
46 name = Unicode(u'ipython-nbconvert')
47
48 config_file_name = Unicode(u'ipython_nbconvert_config.py')
49 >>>>>>> Moved config_file_name up
50
51 description = Unicode(
52 u"""This application is used to convert notebook files (*.ipynb).
53 An ipython config file can be used to batch convert notebooks in the
54 current directory.""")
55
56 examples = Unicode(u"""
57 Running `ipython nbconvert` will read the directory config file and then
58 apply it to one or more notebooks.
59
60 Multiple notebooks can be given at the command line in a couple of
61 different ways:
62
63 > ipython nbconvert notebook*.ipynb
64 > ipython nbconvert notebook1.ipynb notebook2.ipynb
65 > ipython nbconvert # this will use the config file to fill in the notebooks
66 """)
67
68 #Writer specific variables
69 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
70 help="""Instance of the writer class used to write the
71 results of the conversion.""")
72 writer_class = DottedObjectName('FilesWriter', config=True,
73 help="""Writer class used to write the
74 results of the conversion""")
75 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
76 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
77 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
78 writer_factory = Type()
79
80 def _writer_class_changed(self, name, old, new):
81 if new in self.writer_aliases:
82 new = self.writer_aliases[new]
83 self.writer_factory = import_item(new)
84
85
86 #Other configurable variables
87 export_format = Unicode(
88 "", config=True,
89 help="""If specified, nbconvert will convert the document(s) specified
90 using this format.""")
91
92 notebooks = List([], config=True, help="""List of notebooks to convert.
93 Search patterns are supported.""")
94
95 nbconvert_aliases = {'format':'NbConvertApp.export_format',
96 'notebooks':'NbConvertApp.notebooks',
97 'writer':'NbConvertApp.writer_class'}
98
99
100 @catch_config_error
101 def initialize(self, argv=None):
102 self.aliases.update(self.nbconvert_aliases)
103
104 super(NbConvertApp, self).initialize(argv)
105
106 #Register class here to have help with help all
107 self.classes.insert(0, Exporter)
108 self.classes.insert(0, WriterBase)
109 self.classes.insert(0, NbConvertBase)
110
111 #Init
112 self.init_config(self.extra_args)
113 self.init_writer()
114
115
116 def init_config(self, extra_args):
117 """
118 Add notebooks to the config if needed. Glob each notebook to replace
119 notebook patterns with filenames.
120 """
121
122 #Get any additional notebook patterns from the commandline
123 if len(extra_args) > 0:
124 for pattern in extra_args:
125 self.notebooks.append(pattern)
126
127 #Use glob to replace all the notebook patterns with filenames.
128 filenames = []
129 for pattern in self.notebooks:
130 for filename in glob.glob(pattern):
131 if not filename in filenames:
132 filenames.append(filename)
133 self.notebooks = filenames
134
135
136 def init_writer(self):
137 """
138 Initialize the writer (which is stateless)
139 """
140 self._writer_class_changed(None, self.writer_class, self.writer_class)
141 self.writer = self.writer_factory(parent=self)
142
143
144 def start(self, argv=None):
145 """
146 Ran after initiialization completed
147 """
148 super(NbConvertApp, self).start()
149 self.convert_notebooks()
150
151
152 def convert_notebooks(self):
153 """
154 Convert the notebooks in the self.notebook traitlet
155 """
156 #Export each notebook
157 conversion_success = 0
158 for notebook_filename in self.notebooks:
159
160 #Get a unique key for the notebook and set it in the resources object.
161 basename = os.path.basename(notebook_filename)
162 notebook_name = basename[:basename.rfind('.')]
163 resources = {}
164 resources['unique_key'] = notebook_name
165
166 #Try to export
167 try:
168 output, resources = export_by_name(self.export_format,
169 notebook_filename,
170 resources=resources,
171 config=self.config)
172 except ExporterNameError as e:
173 print("Error: '%s' exporter not found." % self.export_format,
174 file=sys.stderr)
175 print("Known exporters are:",
176 "\n\t" + "\n\t".join(get_export_names()),
177 file=sys.stderr)
178 sys.exit(-1)
179 #except Exception as e:
180 #print("Error: could not export '%s'" % notebook_filename, file=sys.stderr)
181 #print(e, file=sys.stderr)
182 else:
183 self.writer.write(output, resources, notebook_name=notebook_name)
184 conversion_success += 1
185
186 #If nothing was converted successfully, help the user.
187 if conversion_success == 0:
188
189 #No notebooks were specified, show help.
190 if len(self.notebooks) == 0:
191 self.print_help()
192
193 #Notebooks were specified, but not converted successfully. Show how
194 #to access help.
195 else:
196 print('For help, use "ipython nbconvert --help"')
197
198
199 #-----------------------------------------------------------------------------
200 # Main entry point
201 #-----------------------------------------------------------------------------
202
203 launch_new_instance = NbConvertApp.launch_instance
@@ -1,110 +1,110 b''
1 """
1 """
2 Exporter that allows Latex Jinja templates to work. Contains logic to
2 Exporter that allows Latex Jinja templates to work. Contains logic to
3 appropriately prepare IPYNB files for export to LaTeX. Including but
3 appropriately prepare IPYNB files for export to LaTeX. Including but
4 not limited to escaping LaTeX, fixing math region tags, using special
4 not limited to escaping LaTeX, fixing math region tags, using special
5 tags to circumvent Jinja/Latex syntax conflicts.
5 tags to circumvent Jinja/Latex syntax conflicts.
6 """
6 """
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (c) 2013, the IPython Development Team.
8 # Copyright (c) 2013, the IPython Development Team.
9 #
9 #
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11 #
11 #
12 # The full license is in the file COPYING.txt, distributed with this software.
12 # The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 # Stdlib imports
19 # Stdlib imports
20 import os
20 import os
21
21
22 # IPython imports
22 # IPython imports
23 from IPython.utils.traitlets import Unicode, List
23 from IPython.utils.traitlets import Unicode, List
24 from IPython.config import Config
24 from IPython.config import Config
25
25
26 from IPython.nbconvert import filters, transformers
26 from IPython.nbconvert import filters, transformers
27 from .exporter import Exporter
27 from .exporter import Exporter
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Classes and functions
30 # Classes and functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 class LatexExporter(Exporter):
33 class LatexExporter(Exporter):
34 """
34 """
35 Exports to a Latex template. Inherit from this class if your template is
35 Exports to a Latex template. Inherit from this class if your template is
36 LaTeX based and you need custom tranformers/filters. Inherit from it if
36 LaTeX based and you need custom tranformers/filters. Inherit from it if
37 you are writing your own HTML template and need custom tranformers/filters.
37 you are writing your own HTML template and need custom tranformers/filters.
38 If you don't need custom tranformers/filters, just change the
38 If you don't need custom tranformers/filters, just change the
39 'template_file' config option. Place your template in the special "/latex"
39 'template_file' config option. Place your template in the special "/latex"
40 subfolder of the "../templates" folder.
40 subfolder of the "../templates" folder.
41 """
41 """
42
42
43 file_extension = Unicode(
43 file_extension = Unicode(
44 'tex', config=True,
44 'tex', config=True,
45 help="Extension of the file that should be written to disk")
45 help="Extension of the file that should be written to disk")
46
46
47 template_file = Unicode(
47 template_file = Unicode(
48 'base', config=True,
48 'base', config=True,
49 help="Name of the template file to use")
49 help="Name of the template file to use")
50
50
51 #Latex constants
51 #Latex constants
52 template_path = Unicode(
52 template_path = Unicode(
53 os.path.join("..", "templates", "latex"), config=True,
53 os.path.join("..", "templates", "latex"), config=True,
54 help="Path where the template files are located.")
54 help="Path where the template files are located.")
55
55
56 template_skeleton_path = Unicode(
56 template_skeleton_path = Unicode(
57 os.path.join("..", "templates", "latex", "skeleton"), config=True,
57 os.path.join("..", "templates", "latex", "skeleton"), config=True,
58 help="Path where the template skeleton files are located.")
58 help="Path where the template skeleton files are located.")
59
59
60 #Special Jinja2 syntax that will not conflict when exporting latex.
60 #Special Jinja2 syntax that will not conflict when exporting latex.
61 jinja_comment_block_start = Unicode("((=", config=True)
61 jinja_comment_block_start = Unicode("((=", config=True)
62 jinja_comment_block_end = Unicode("=))", config=True)
62 jinja_comment_block_end = Unicode("=))", config=True)
63 jinja_variable_block_start = Unicode("(((", config=True)
63 jinja_variable_block_start = Unicode("(((", config=True)
64 jinja_variable_block_end = Unicode(")))", config=True)
64 jinja_variable_block_end = Unicode(")))", config=True)
65 jinja_logic_block_start = Unicode("((*", config=True)
65 jinja_logic_block_start = Unicode("((*", config=True)
66 jinja_logic_block_end = Unicode("*))", config=True)
66 jinja_logic_block_end = Unicode("*))", config=True)
67
67
68 #Extension that the template files use.
68 #Extension that the template files use.
69 template_extension = Unicode(".tplx", config=True)
69 template_extension = Unicode(".tplx", config=True)
70
70
71 default_transformers = List([transformers.ExtractFigureTransformer,
71 default_transformers = List([transformers.ExtractFigureTransformer,
72 transformers.CSSHTMLHeaderTransformer,
72 transformers.CSSHTMLHeaderTransformer,
73 transformers.LatexTransformer,
73 transformers.LatexTransformer,
74 transformers.Svg2PdfTransformer],
74 transformers.SVG2PDFTransformer],
75 config=True,
75 config=True,
76 help="""List of transformers available by default, by name, namespace,
76 help="""List of transformers available by default, by name, namespace,
77 instance, or type.""")
77 instance, or type.""")
78
78
79
79
80 def _init_filters(self):
80 def _init_filters(self):
81 """
81 """
82 Register all of the filters required for the exporter.
82 Register all of the filters required for the exporter.
83 """
83 """
84
84
85 #Register the filters of the base class.
85 #Register the filters of the base class.
86 super(LatexExporter, self)._init_filters()
86 super(LatexExporter, self)._init_filters()
87
87
88 #Add latex filters to the Jinja2 environment
88 #Add latex filters to the Jinja2 environment
89 self.register_filter('escape_tex', filters.escape_latex)
89 self.register_filter('escape_tex', filters.escape_latex)
90 self.register_filter('highlight', filters.highlight2latex)
90 self.register_filter('highlight', filters.highlight2latex)
91
91
92
92
93 @property
93 @property
94 def default_config(self):
94 def default_config(self):
95 c = Config({
95 c = Config({
96 'NbConvertBase': {
96 'NbConvertBase': {
97 'display_data_priority' : ['latex', 'png', 'jpg', 'svg', 'jpeg', 'text']
97 'display_data_priority' : ['latex', 'png', 'jpg', 'svg', 'jpeg', 'text']
98 },
98 },
99 'ExtractFigureTransformer': {
99 'ExtractFigureTransformer': {
100 'enabled':True
100 'enabled':True
101 },
101 },
102 'Svg2PdfTransformer': {
102 'SVG2PDFTransformer': {
103 'enabled':True
103 'enabled':True
104 },
104 },
105 'LatexTransformer': {
105 'LatexTransformer': {
106 'enabled':True
106 'enabled':True
107 }
107 }
108 })
108 })
109 c.merge(super(LatexExporter,self).default_config)
109 c.merge(super(LatexExporter,self).default_config)
110 return c
110 return c
@@ -1,77 +1,77 b''
1 """Module containing a transformer that converts outputs in the notebook from
1 """Module containing a transformer that converts outputs in the notebook from
2 one format to another.
2 one format to another.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
5 # Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import os
16 import os
17 import sys
17 import sys
18 import subprocess
18 import subprocess
19
19
20 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.tempdir import TemporaryDirectory
21 from IPython.utils.traitlets import Unicode
21 from IPython.utils.traitlets import Unicode
22
22
23 from .convertfigures import ConvertFiguresTransformer
23 from .convertfigures import ConvertFiguresTransformer
24
24
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Constants
27 # Constants
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 INKSCAPE_COMMAND = 'inkscape --without-gui --export-pdf="{to_filename}" "{from_filename}"'
30 INKSCAPE_COMMAND = 'inkscape --without-gui --export-pdf="{to_filename}" "{from_filename}"'
31 INKSCAPE_OSX_COMMAND = '/Applications/Inkscape.app/Contents/Resources/bin/inkscape --without-gui --export-pdf="{to_filename}" "{from_filename}"'
31 INKSCAPE_OSX_COMMAND = '/Applications/Inkscape.app/Contents/Resources/bin/inkscape --without-gui --export-pdf="{to_filename}" "{from_filename}"'
32
32
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Classes
35 # Classes
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 class Svg2PdfTransformer(ConvertFiguresTransformer):
38 class SVG2PDFTransformer(ConvertFiguresTransformer):
39 """
39 """
40 Converts all of the outputs in a notebook from one format to another.
40 Converts all of the outputs in a notebook from one format to another.
41 """
41 """
42
42
43 from_format = Unicode('svg', config=True, help='Format the converter accepts')
43 from_format = Unicode('svg', config=True, help='Format the converter accepts')
44 to_format = Unicode('pdf', config=False, help='Format the converter writes')
44 to_format = Unicode('pdf', config=False, help='Format the converter writes')
45
45
46
46
47 def convert_figure(self, data_format, data):
47 def convert_figure(self, data_format, data):
48 """
48 """
49 Convert a single Svg figure. Returns converted data.
49 Convert a single Svg figure. Returns converted data.
50 """
50 """
51
51
52 #Work in a temporary directory
52 #Work in a temporary directory
53 with TemporaryDirectory() as tmpdir:
53 with TemporaryDirectory() as tmpdir:
54
54
55 #Write fig to temp file
55 #Write fig to temp file
56 input_filename = os.path.join(tmpdir, 'figure.' + data_format)
56 input_filename = os.path.join(tmpdir, 'figure.' + data_format)
57 with open(input_filename, 'w') as f:
57 with open(input_filename, 'w') as f:
58 f.write(data)
58 f.write(data)
59
59
60 #Determine command (different on Mac OSX)
60 #Determine command (different on Mac OSX)
61 command = INKSCAPE_COMMAND
61 command = INKSCAPE_COMMAND
62 if sys.platform == 'darwin':
62 if sys.platform == 'darwin':
63 command = INKSCAPE_OSX_COMMAND
63 command = INKSCAPE_OSX_COMMAND
64
64
65 #Call conversion application
65 #Call conversion application
66 output_filename = os.path.join(tmpdir, 'figure.pdf')
66 output_filename = os.path.join(tmpdir, 'figure.pdf')
67 shell = command.format(from_filename=input_filename,
67 shell = command.format(from_filename=input_filename,
68 to_filename=output_filename)
68 to_filename=output_filename)
69 subprocess.call(shell, shell=True) #Shell=True okay since input is trusted.
69 subprocess.call(shell, shell=True) #Shell=True okay since input is trusted.
70
70
71 #Read output from drive
71 #Read output from drive
72 if os.path.isfile(output_filename):
72 if os.path.isfile(output_filename):
73 with open(output_filename, 'rb') as f:
73 with open(output_filename, 'rb') as f:
74 return f.read().encode("base64") #PDF is a nb supported binary
74 return f.read().encode("base64") #PDF is a nb supported binary
75 #data type, so base64 encode.
75 #data type, so base64 encode.
76 else:
76 else:
77 return TypeError("Inkscape svg to png conversion failed")
77 return TypeError("Inkscape svg to png conversion failed")
@@ -1,12 +1,12 b''
1 # Class base Transformers
1 # Class base Transformers
2 from .base import ConfigurableTransformer
2 from .base import ConfigurableTransformer
3 from .convertfigures import ConvertFiguresTransformer
3 from .convertfigures import ConvertFiguresTransformer
4 from .SVG2PDF import Svg2PdfTransformer
4 from .SVG2PDF import SVG2PDFTransformer
5 from .extractfigure import ExtractFigureTransformer
5 from .extractfigure import ExtractFigureTransformer
6 from .revealhelp import RevealHelpTransformer
6 from .revealhelp import RevealHelpTransformer
7 from .latex import LatexTransformer
7 from .latex import LatexTransformer
8 from .sphinx import SphinxTransformer
8 from .sphinx import SphinxTransformer
9 from .csshtmlheader import CSSHTMLHeaderTransformer
9 from .csshtmlheader import CSSHTMLHeaderTransformer
10
10
11 # decorated function Transformers
11 # decorated function Transformers
12 from .coalescestreams import coalesce_streams
12 from .coalescestreams import coalesce_streams
General Comments 0
You need to be logged in to leave comments. Login now