Minor fixups.
[librarian.git] / librarian / embeds / latex.py
1 import os
2 import shutil
3 from subprocess import call, PIPE
4 from tempfile import mkdtemp
5 from librarian import get_resource
6 from . import DataEmbed, create_embed, downgrades_to, converts_to
7
8 class LaTeX(DataEmbed):
9     @downgrades_to('image/png')
10     def to_png(self):
11         tmpl = open(get_resource('res/embeds/latex/template.tex')).read().decode('utf-8')
12         tempdir = mkdtemp('-librarian-embed-latex')
13         fpath = os.path.join(tempdir, 'doc.tex')
14         with open(fpath, 'w') as f:
15             f.write((tmpl % {'code': self.data}).encode('utf-8'))
16         call(['xelatex', '-interaction=batchmode', '-output-directory', tempdir, fpath], stdout=PIPE, stderr=PIPE)
17         call(['convert', '-density', '150', os.path.join(tempdir, 'doc.pdf'), '-trim',
18                 os.path.join(tempdir, 'doc.png')])
19         pngdata = open(os.path.join(tempdir, 'doc.png')).read()
20         shutil.rmtree(tempdir)
21         return create_embed('image/png', data=pngdata)