1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
9 from tempfile import mkdtemp
10 from StringIO import StringIO
11 from django.conf import settings
13 from django.http import HttpResponse
14 from django.template.loader import render_to_string
16 logger = logging.getLogger(__name__)
19 def render_to_pdf(output_path, template, context=None, add_files=None):
20 """Renders a TeXML document into a PDF file.
22 :param str output_path: is where the PDF file should go
23 :param str template: is a TeXML template path
24 :param context: is context for rendering the template
25 :param dict add_files: a dictionary of additional files XeTeX will need
28 import Texml.processor
29 rendered = render_to_string(template, context)
30 texml = StringIO(rendered.encode('utf-8'))
31 tempdir = mkdtemp(prefix = "render_to_pdf-")
32 tex_path = os.path.join(tempdir, "doc.tex")
33 with open(tex_path, 'w') as tex_file:
34 Texml.processor.process(texml, tex_file, encoding="utf-8")
37 for add_name, src_file in add_files.items():
38 add_path = os.path.join(tempdir, add_name)
39 if hasattr(src_file, "read"):
40 with open(add_path, 'w') as add_file:
41 add_file.write(add_file.read())
43 shutil.copy(src_file, add_path)
48 subprocess.check_call(['xelatex', '-interaction=batchmode', tex_path],
49 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
51 os.makedirs(os.path.dirname(output_path))
54 shutil.move(os.path.join(tempdir, "doc.pdf"), output_path)
57 shutil.rmtree(tempdir)
60 def read_chunks(f, size=8192):
67 def generated_file_view(file_name, mime_type, send_name=None, signals=None):
68 file_path = os.path.join(settings.MEDIA_ROOT, file_name)
69 file_url = os.path.join(settings.MEDIA_URL, file_name)
71 send_name = os.path.basename(file_name)
73 def signal_handler(*args, **kwargs):
77 for signal in signals:
78 signal.connect(signal_handler, weak=False)
81 def view(request, *args, **kwargs):
82 if not os.path.exists(file_path):
83 func(file_path, *args, **kwargs)
85 if hasattr(send_name, "__call__"):
90 response = HttpResponse(mimetype=mime_type)
91 response['Content-Disposition'] = 'attachment; filename=%s' % name
92 with open(file_path) as f:
93 for chunk in read_chunks(f):