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.
5 from errno import ENOENT
8 from django.conf import settings
10 from django.http import HttpResponse
12 logger = logging.getLogger(__name__)
15 def render_to_pdf(output_path, template, context=None, add_files=None):
16 """Renders a TeXML document into a PDF file.
18 :param str output_path: is where the PDF file should go
19 :param str template: is a TeXML template path
20 :param context: is context for rendering the template
21 :param dict add_files: a dictionary of additional files XeTeX will need
24 from StringIO import StringIO
26 from tempfile import mkdtemp
28 import Texml.processor
29 from django.template.loader import render_to_string
31 rendered = render_to_string(template, context)
32 texml = StringIO(rendered.encode('utf-8'))
33 tempdir = mkdtemp(prefix="render_to_pdf-")
34 tex_path = os.path.join(tempdir, "doc.tex")
35 with open(tex_path, 'w') as tex_file:
36 Texml.processor.process(texml, tex_file, encoding="utf-8")
39 for add_name, src_file in add_files.items():
40 add_path = os.path.join(tempdir, add_name)
41 if hasattr(src_file, "read"):
42 with open(add_path, 'w') as add_file:
43 add_file.write(add_file.read())
45 shutil.copy(src_file, add_path)
50 subprocess.check_call(['xelatex', '-interaction=batchmode', tex_path],
51 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
53 os.makedirs(os.path.dirname(output_path))
56 shutil.move(os.path.join(tempdir, "doc.pdf"), output_path)
59 shutil.rmtree(tempdir)
62 def render_to_csv(output_path, template, context=None, add_files=None):
63 """Renders a TeXML document into a PDF file.
65 :param str output_path: is where the PDF file should go
66 :param str template: is a TeXML template path
67 :param context: is context for rendering the template
68 :param dict add_files: a dictionary of additional files XeTeX will need
71 from django.template.loader import render_to_string
74 os.makedirs(os.path.dirname(output_path))
78 rendered = render_to_string(template, context)
79 with open(output_path, 'w') as csv_file:
80 csv_file.write(rendered.encode('utf-8'))
83 def read_chunks(f, size=8192):
90 def generated_file_view(file_name, mime_type, send_name=None, signals=None):
91 file_path = os.path.join(settings.MEDIA_ROOT, file_name)
93 send_name = os.path.basename(file_name)
95 def signal_handler(*args, **kwargs):
99 if oe.errno != ENOENT:
103 for signal in signals:
104 signal.connect(signal_handler, weak=False)
107 def view(request, *args, **kwargs):
108 if not os.path.exists(file_path):
109 func(file_path, *args, **kwargs)
111 if hasattr(send_name, "__call__"):
116 response = HttpResponse(content_type=mime_type)
117 response['Content-Disposition'] = 'attachment; filename=%s' % name
118 with open(file_path) as f:
119 for chunk in read_chunks(f):
120 response.write(chunk)