1#!/usr/local/bin/python3.8
2# coding=utf-8
3#
4# Copyright (C) 2019 Marc Jeanmougin
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
19#
20"""
21Generate Latex via a PDF using pdflatex
22"""
23
24import os
25
26import inkex
27from inkex.base import TempDirMixin
28from inkex.command import call, inkscape
29from inkex import load_svg, ShapeElement, Defs
30
31class PdfLatex(TempDirMixin, inkex.GenerateExtension):
32    """
33    Use pdflatex to generate LaTeX, this whole hack is required because
34    we don't want to open a LaTeX document as a document, but as a
35    generated fragment (like import, but done manually).
36    """
37    def add_arguments(self, pars):
38        pars.add_argument('--formule', type=str, default='')
39        pars.add_argument('--packages', type=str, default='')
40
41    def generate(self):
42        tex_file = os.path.join(self.tempdir, 'input.tex')
43        pdf_file = os.path.join(self.tempdir, 'input.pdf') # Auto-generate by pdflatex
44        svg_file = os.path.join(self.tempdir, 'output.svg')
45
46        with open(tex_file, 'w') as fhl:
47            self.write_latex(fhl)
48
49        call('pdflatex', tex_file,\
50            output_directory=self.tempdir,\
51            halt_on_error=True, oldie=True)
52
53        inkscape(pdf_file, export_filename=svg_file, pdf_page=1,
54                 pdf_poppler=True, export_type="svg")
55
56        if not os.path.isfile(svg_file):
57            fn = os.path.basename(svg_file)
58            if os.path.isfile(fn):
59                # Inkscape bug detected, file got saved wrong
60                svg_file = fn
61
62        with open(svg_file, 'r') as fhl:
63            svg = load_svg(fhl).getroot()
64            svg.set_random_ids(backlinks=True)
65            for child in svg:
66                if isinstance(child, ShapeElement):
67                    yield child
68                elif isinstance(child, Defs):
69                    for def_child in child:
70                        #def_child.set_random_id()
71                        self.svg.defs.append(def_child)
72
73    def write_latex(self, stream):
74        """Takes a forumle and wraps it in latex"""
75        stream.write(r"""%% processed with pdflatex.py
76\documentclass{minimal}
77\usepackage{amsmath}
78\usepackage{amssymb}
79\usepackage{amsfonts}
80""")
81        for package in self.options.packages.split(','):
82            if package:
83                stream.write('\\usepackage{{{}}}\n'.format(package))
84        stream.write("\n\\begin{document}\n")
85        stream.write(self.options.formule)
86        stream.write("\n\\end{document}\n")
87
88if __name__ == '__main__':
89    PdfLatex().run()
90