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