def render(self, request, **kwargs): """ Render the template to a PDF file. Supported template formats: .tex - Uses django-tex plugin to render LaTeX template against an installed LaTeX engine .html - Uses django-weasyprint plugin to render HTML template against Weasyprint """ filename = kwargs.get('filename', 'report.pdf') context = self.get_context_data(request) context['request'] = request context['user'] = request.user context['datetime'] = datetime.datetime.now() if self.extension == '.tex': # Render LaTeX template to PDF if settings.LATEX_ENABLED: # Attempt to render to LaTeX template # If there is a rendering error, return the (partially rendered) template, # so at least we can debug what is going on try: rendered = render_template_with_context(self.template_name, context) return render_to_pdf(request, self.template_name, context, filename=filename) except TexError: return TexResponse(rendered, filename="error.tex") else: return ValidationError("Enable LaTeX support in config.yaml") elif self.extension in ['.htm', '.html']: # Render HTML template to PDF wp = WeasyprintReportMixin(request, self.template_name, **kwargs) return wp.render_to_response(context, **kwargs)
def test_render_template(self): template_name = 'tests/test.tex' context = { 'test': 'a simple test', 'number': Decimal('1000.10'), 'date': datetime.date(2017, 10, 25), 'names': ['Arjen', 'Robert', 'Mats'], } output = render_template_with_context(template_name, context) self.assertIn('\\section{a simple test}', output) self.assertIn('This is a number: 1000,10.', output) self.assertIn('And this is a date: 25.10.2017.', output) self.assertIn('\\item Arjen', output)
def test_render_template(self): template_name = "tests/test.tex" context = { "test": "a simple test", "number": Decimal("1000.10"), "date": datetime.date(2017, 10, 25), "names": ["Arjen", "Robert", "Mats"], } output = render_template_with_context(template_name, context) self.assertIn("\\section{a simple test}", output) self.assertIn("This is a number: 1000,10.", output) self.assertIn("And this is a date: 25.10.2017.", output) self.assertIn("\\item Arjen", output)
def test_render_template_from_custom_directory(self): template_name = 'custom_directory_test.tex' context = {'foo': 'bar'} output = render_template_with_context(template_name, context) self.assertIn('bar', output)
def test_render_template_from_custom_directory(self): template_name = "custom_directory_test.tex" context = {"foo": "bar"} output = render_template_with_context(template_name, context) self.assertIn("bar", output)