Code

Updated the text of the JessyInk effect extension to make translation easier (bug...
[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 2010-04-04: Added support for custom packages
13             Christoph Schmidt-Hieber <christsc@gmx.de>
15 This program is free software; you can redistribute it and/or modify
16 it under the terms of the GNU General Public License as published by
17 the Free Software Foundation; either version 2 of the License, or
18 (at your option) any later version.
20 This program is distributed in the hope that it will be useful,
21 but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 GNU General Public License for more details.
25 You should have received a copy of the GNU General Public License
26 along with this program; if not, write to the Free Software
27 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
29 """
31 import inkex, os, tempfile, sys, xml.dom.minidom
33 def parse_pkgs(pkgstring):
34     pkglist = pkgstring.replace(" ","").split(",")
35     header = ""
36     for pkg in pkglist:
37         header += "\\usepackage{%s}\n" % pkg
39     return header
41 def create_equation_tex(filename, equation, add_header=""):
42     tex = open(filename, 'w')
43     tex.write("""%% processed with eqtexsvg.py
44 \\documentclass{article}
45 \\usepackage{amsmath}
46 \\usepackage{amssymb}
47 \\usepackage{amsfonts}
48 """)
49     tex.write(add_header)
50     tex.write("""\\thispagestyle{empty}
51 \\begin{document}
52 """)
53     tex.write(equation)
54     tex.write("\n\\end{document}\n")
55     tex.close()
57 def svg_open(self,filename):
58     doc_width = inkex.unittouu(self.document.getroot().get('width'))
59     doc_height = inkex.unittouu(self.document.getroot().get('height'))
60     doc_sizeH = min(doc_width,doc_height)
61     doc_sizeW = max(doc_width,doc_height)
63     def clone_and_rewrite(self, node_in):
64         in_tag = node_in.tag.rsplit('}',1)[-1]
65         if in_tag != 'svg':
66             node_out = inkex.etree.Element(inkex.addNS(in_tag,'svg'))
67             for name in node_in.attrib:
68                 node_out.set(name, node_in.attrib[name])
69         else:
70             node_out = inkex.etree.Element(inkex.addNS('g','svg'))
71         for c in node_in.iterchildren():
72             c_tag = c.tag.rsplit('}',1)[-1]
73             if c_tag in ('g', 'path', 'polyline', 'polygon'):
74                 child = clone_and_rewrite(self, c)
75                 if c_tag == 'g':
76                     child.set('transform','matrix('+str(doc_sizeH/700.)+',0,0,'+str(-doc_sizeH/700.)+','+str(-doc_sizeH*0.25)+','+str(doc_sizeW*0.75)+')')
77                 node_out.append(child)
79         return node_out
81     doc = inkex.etree.parse(filename)
82     svg = doc.getroot()
83     group = clone_and_rewrite(self, svg)
84     self.current_layer.append(group)
86 class EQTEXSVG(inkex.Effect):
87     def __init__(self):
88         inkex.Effect.__init__(self)
89         self.OptionParser.add_option("-f", "--formule",
90                         action="store", type="string",
91                         dest="formula", default="",
92                         help="LaTeX formula")
93         self.OptionParser.add_option("-p", "--packages",
94                         action="store", type="string",
95                         dest="packages", default="",
96                         help="Additional packages")
97     def effect(self):
99         base_dir = tempfile.mkdtemp("", "inkscape-");
100         latex_file = os.path.join(base_dir, "eq.tex")
101         aux_file = os.path.join(base_dir, "eq.aux")
102         log_file = os.path.join(base_dir, "eq.log")
103         ps_file = os.path.join(base_dir, "eq.ps")
104         dvi_file = os.path.join(base_dir, "eq.dvi")
105         svg_file = os.path.join(base_dir, "eq.svg")
106         out_file = os.path.join(base_dir, "eq.out")
107         err_file = os.path.join(base_dir, "eq.err")
109         def clean():
110             os.remove(latex_file)
111             os.remove(aux_file)
112             os.remove(log_file)
113             os.remove(ps_file)
114             os.remove(dvi_file)
115             os.remove(svg_file)
116             os.remove(out_file)
117             if os.path.exists(err_file):
118                 os.remove(err_file)
119             os.rmdir(base_dir)
121         add_header = parse_pkgs(self.options.packages)
122         create_equation_tex(latex_file, self.options.formula, add_header)
123         os.system('latex "-output-directory=%s" -halt-on-error "%s" > "%s"' \
124                   % (base_dir, latex_file, out_file))
125         try:
126             os.stat(dvi_file)
127         except OSError:
128             print >>sys.stderr, "invalid LaTeX input:"
129             print >>sys.stderr, self.options.formula
130             print >>sys.stderr, "temporary files were left in:", base_dir
131             sys.exit(1)
133         os.system('dvips -q -f -E -D 600 -y 5000 -o "%s" "%s"' % (ps_file, dvi_file))
134         # cd to base_dir is necessary, because pstoedit writes
135         # temporary files to cwd and needs write permissions
136         separator = ';'
137         if os.name == 'nt':
138             separator = '&&'
139         os.system('cd "%s" %s pstoedit -f plot-svg -dt -ssp "%s" "%s" > "%s" 2> "%s"' \
140                   % (base_dir, separator, ps_file, svg_file, out_file, err_file))
142         # forward errors to stderr but skip pstoedit header
143         if os.path.exists(err_file):
144             err_stream = open(err_file, 'r')
145             for line in err_stream:
146                 if not line.startswith('pstoedit: version'):
147                     sys.stderr.write(line + '\n')
148             err_stream.close()
149  
150         svg_open(self, svg_file)
152         clean()
154 if __name__ == '__main__':
155     e = EQTEXSVG()
156     e.affect()
159 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 fileencoding=utf-8 textwidth=99