3
0
Fork 0
mirror of https://github.com/nanoy42/coope synced 2024-12-01 17:12:24 +00:00
coope/django_tex/core.py

50 lines
1.8 KiB
Python
Raw Normal View History

2019-01-06 14:57:02 +00:00
import os
from subprocess import PIPE, run
import tempfile
from django.template.loader import get_template
from django_tex.exceptions import TexError
from django.conf import settings
2019-04-28 11:08:51 +00:00
DEFAULT_INTERPRETER = 'pdflatex'
2019-01-06 14:57:02 +00:00
def run_tex(source):
2019-02-28 12:18:41 +00:00
"""
Copy the source to temp dict and run latex.
"""
2019-01-06 14:57:02 +00:00
with tempfile.TemporaryDirectory() as tempdir:
filename = os.path.join(tempdir, 'texput.tex')
with open(filename, 'x', encoding='utf-8') as f:
f.write(source)
latex_interpreter = getattr(settings, 'LATEX_INTERPRETER', DEFAULT_INTERPRETER)
2019-02-21 19:08:29 +00:00
latex_command = 'cd "{tempdir}" && {latex_interpreter} -interaction=batchmode {path}'.format(tempdir=tempdir, latex_interpreter=latex_interpreter, path=os.path.basename(filename))
2019-01-06 14:57:02 +00:00
process = run(latex_command, shell=True, stdout=PIPE, stderr=PIPE)
try:
if process.returncode == 1:
with open(os.path.join(tempdir, 'texput.log'), encoding='utf8') as f:
log = f.read()
raise TexError(log=log, source=source)
with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as pdf_file:
pdf = pdf_file.read()
except FileNotFoundError:
if process.stderr:
raise Exception(process.stderr.decode('utf-8'))
raise
return pdf
def compile_template_to_pdf(template_name, context):
2019-02-28 12:18:41 +00:00
"""
Compile the source with :func:`~django_tex.core.render_template_with_context` and :func:`~django_tex.core.run_tex`.
"""
2019-01-06 14:57:02 +00:00
source = render_template_with_context(template_name, context)
return run_tex(source)
def render_template_with_context(template_name, context):
2019-02-28 12:18:41 +00:00
"""
Render the template
"""
2019-01-06 14:57:02 +00:00
template = get_template(template_name, using='tex')
return template.render(context)