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