process_latex.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. from subprocess import call, PIPE
  3. from os import remove, rename
  4. from os.path import dirname
  5. from tempfile import NamedTemporaryFile
  6. from django.template import loader, Context
  7. from django.conf import settings
  8. def process_latex(template, context={}, type='pdf', outfile=None):
  9. """
  10. Processes a template as a LaTeX source file.
  11. Output is either being returned or stored in outfile.
  12. At the moment only pdf output is supported.
  13. """
  14. t = loader.get_template(template)
  15. c = Context(context)
  16. r = t.render(c)
  17. tex = NamedTemporaryFile()
  18. tex.write(r.encode('utf-8'))
  19. tex.flush()
  20. base = tex.name
  21. items = "log aux pdf dvi png".split()
  22. names = dict((x, '%s.%s' % (base, x)) for x in items)
  23. output = names[type]
  24. if type == 'pdf' or type == 'dvi':
  25. pdflatex(base, type)
  26. elif type == 'png':
  27. pdflatex(base, 'dvi')
  28. call(['dvipng', '-bg', '-transparent',
  29. names['dvi'], '-o', names['png']],
  30. cwd=dirname(base), stdout=PIPE, stderr=PIPE)
  31. remove(names['log'])
  32. remove(names['aux'])
  33. if not outfile:
  34. o = file(output).read()
  35. remove(output)
  36. return o
  37. else:
  38. rename(output, outfile)
  39. def pdflatex(file, type='pdf'):
  40. call([settings.PDFLATEX_PATH, '-interaction=nonstopmode',
  41. '-output-format', type, file],
  42. cwd=dirname(file), stdout=PIPE, stderr=PIPE)