##// END OF EJS Templates
base64 encode PDF before writing back to the nb structure
Jonathan Frederic -
Show More
@@ -1,70 +1,71 b''
1 1 """Module containing a transformer that converts outputs in the notebook from
2 2 one format to another.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2013, the IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 import os
17 17 from IPython.utils.tempdir import TemporaryDirectory
18 18
19 19 from .convertfigures import ConvertFiguresTransformer
20 20
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Constants
24 24 #-----------------------------------------------------------------------------
25 25
26 26 INKSCAPE_COMMAND = "inkscape --without-gui --export-pdf=\"{to_filename}\" \"{from_filename}\""
27 27
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Classes
31 31 #-----------------------------------------------------------------------------
32 32
33 33 class ConvertSvgTransformer(ConvertFiguresTransformer):
34 34 """
35 35 Converts all of the outputs in a notebook from one format to another.
36 36 """
37 37
38 38
39 39 def __init__(self, **kw):
40 40 """
41 41 Constructor
42 42 """
43 43 super(ConvertSvgTransformer, self).__init__(['svg'], 'pdf', **kw)
44 44
45 45
46 46 def convert_figure(self, data_format, data):
47 47 """
48 48 Convert a single Svg figure. Returns converted data.
49 49 """
50 50
51 51 #Work in a temporary directory
52 52 with TemporaryDirectory() as tmpdir:
53 53
54 54 #Write fig to temp file
55 55 input_filename = os.path.join(tmpdir, 'figure.' + data_format)
56 56 with open(input_filename, 'w') as f:
57 57 f.write(data)
58 58
59 59 #Call conversion application
60 60 output_filename = os.path.join(tmpdir, 'figure.pdf')
61 61 shell = INKSCAPE_COMMAND.format(from_filename=input_filename,
62 62 to_filename=output_filename)
63 63 subprocess.call(shell, shell=True) #Shell=True okay since input is trusted.
64 64
65 65 #Read output from drive
66 66 if os.path.isfile(output_filename):
67 with open(output_filename) as f:
68 return f.read()
67 with open(output_filename, 'rb') as f:
68 return f.read().encode("base64") #PDF is a nb supported binary
69 #data type, so base64 encode.
69 70 else:
70 71 return TypeError("Inkscape svg to png conversion failed")
General Comments 0
You need to be logged in to leave comments. Login now