Code

7cbe8ebfd65d122c1b74f4045f5dd80f22a4ffe5
[inkscape.git] / share / extensions / eqtexsvg.py
1 #!/usr/bin/env python
2 # -*- coding: cp1252 -*-
3 """
4 eqtexsvg.py
5 functions for converting LaTeX equation string into SVG path
6 This extension need, to work properly:
7     - a TeX/LaTeX distribution (MiKTeX ...)
8     - pstoedit software: <http://www.pstoedit.net/pstoedit>
10 Copyright (C) 2006 Julien Vitard <julienvitard@gmail.com>
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
26 """
28 import inkex, os, tempfile, sys, xml.dom.minidom
30 def create_equation_tex(filename, equation):
31     tex = open(filename, 'w')
32     tex.write("""%% processed with eqtexsvg.py
33 \\documentclass{article}
34 \\usepackage{amsmath}
35 \\usepackage{amssymb}
36 \\usepackage{amsfonts}
38 \\thispagestyle{empty}
39 \\begin{document}
40 """)
41     tex.write(equation)
42     tex.write("\n\\end{document}\n")
43     tex.close()
45 def svg_open(self,filename):
46     doc_width = inkex.unittouu(self.document.getroot().get('width'))
47     doc_height = inkex.unittouu(self.document.getroot().get('height'))
48     doc_sizeH = min(doc_width,doc_height)
49     doc_sizeW = max(doc_width,doc_height)
51     def clone_and_rewrite(self, node_in):
52         in_tag = node_in.tag.rsplit('}',1)[-1]
53         if in_tag != 'svg':
54             node_out = inkex.etree.Element(inkex.addNS(in_tag,'svg'))
55             for name in node_in.attrib:
56                 node_out.set(name, node_in.attrib[name])
57         else:
58             node_out = inkex.etree.Element(inkex.addNS('g','svg'))
59         for c in node_in.iterchildren():
60             c_tag = c.tag.rsplit('}',1)[-1]
61             if c_tag in ('g', 'path', 'polyline', 'polygon'):
62                 child = clone_and_rewrite(self, c)
63                 if c_tag == 'g':
64                     child.set('transform','matrix('+str(doc_sizeH/700.)+',0,0,'+str(-doc_sizeH/700.)+','+str(-doc_sizeH*0.25)+','+str(doc_sizeW*0.75)+')')
65                 node_out.append(child)
67         return node_out
69     doc = inkex.etree.parse(filename)
70     svg = doc.getroot()
71     group = clone_and_rewrite(self, svg)
72     self.current_layer.append(group)
74 class EQTEXSVG(inkex.Effect):
75     def __init__(self):
76         inkex.Effect.__init__(self)
77         self.OptionParser.add_option("-f", "--formule",
78                         action="store", type="string",
79                         dest="formula", default=10.0,
80                         help="LaTeX formula")
81     def effect(self):
83         base_dir = tempfile.mkdtemp("", "inkscape-");
84         latex_file = os.path.join(base_dir, "eq.tex")
85         aux_file = os.path.join(base_dir, "eq.aux")
86         log_file = os.path.join(base_dir, "eq.log")
87         ps_file = os.path.join(base_dir, "eq.ps")
88         dvi_file = os.path.join(base_dir, "eq.dvi")
89         svg_file = os.path.join(base_dir, "eq.svg")
90         out_file = os.path.join(base_dir, "eq.out")
91         err_file = os.path.join(base_dir, "eq.err")
93         def clean():
94             os.remove(latex_file)
95             os.remove(aux_file)
96             os.remove(log_file)
97             os.remove(ps_file)
98             os.remove(dvi_file)
99             os.remove(svg_file)
100             os.remove(out_file)
101             if os.path.exists(err_file):
102                 os.remove(err_file)
103             os.rmdir(base_dir)
105         create_equation_tex(latex_file, self.options.formula)
106         os.system('latex "-output-directory=%s" -halt-on-error "%s" > "%s"' \
107                   % (base_dir, latex_file, out_file))
108         try:
109             os.stat(dvi_file)
110         except OSError:
111             print >>sys.stderr, "invalid LaTeX input:"
112             print >>sys.stderr, self.options.formula
113             print >>sys.stderr, "temporary files were left in:", base_dir
114             sys.exit(1)
116         os.system('dvips -q -f -E -D 600 -y 5000 -o "%s" "%s"' % (ps_file, dvi_file))
117         # cd to base_dir is necessary, because pstoedit writes
118         # temporary files to cwd and needs write permissions
119         separator = ';'
120         if os.name == 'nt':
121             separator = '&&'
122         os.system('cd "%s" %s pstoedit -f plot-svg -dt -ssp "%s" "%s" > "%s" 2> "%s"' \
123                   % (base_dir, separator, ps_file, svg_file, out_file, err_file))
125         # forward errors to stderr but skip pstoedit header
126         if os.path.exists(err_file):
127             err_stream = open(err_file, 'r')
128             for line in err_stream:
129                 if not line.startswith('pstoedit: version'):
130                     sys.stderr.write(line + '\n')
131             err_stream.close()
132  
133         svg_open(self, svg_file)
135         clean()
137 e = EQTEXSVG()
138 e.affect()