Minor EPUB/MOBI fixes.
[librarian.git] / src / 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         with open(get_resource('res/embeds/latex/template.tex'), 'rb') as f:
16             tmpl = f.read().decode('utf-8')
17         tempdir = mkdtemp('-librarian-embed-latex')
18         fpath = os.path.join(tempdir, 'doc.tex')
19         with open(fpath, 'wb') as f:
20             f.write((tmpl % {'code': self.data}).encode('utf-8'))
21         call(['xelatex', '-interaction=batchmode', '-output-directory',
22               tempdir, fpath], stdout=PIPE, stderr=PIPE)
23         call(['convert', '-density', '150', os.path.join(tempdir, 'doc.pdf'),
24               '-trim', os.path.join(tempdir, 'doc.png')])
25         pngdata = open(os.path.join(tempdir, 'doc.png'), 'rb').read()
26         shutil.rmtree(tempdir)
27         return create_embed('image/png', data=pngdata)