def render(self, data, accepted_media_type=None, renderer_context=None): """ returns the default html output as pdf """ content = super(TemplatePDFRenderer, self).render(data, accepted_media_type, renderer_context) content = make_absolute_paths(content) tempfile = NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='.html', prefix='tmp', dir=None, delete=True) tempfile.write(content.encode('utf-8')) tempfile.flush() options = {} """ example usage of wkhtmltopdf method: wkhtmltopdf(pages=['/tmp/example.html'], dpi=300, rotation='Landscape', disable_javascript=True) """ return wkhtmltopdf(pages=[tempfile.name], **options)
def to_pdf(self, html, document=None, documents=None): args = [] options = self.pdf_options() # this makes all paths, such as stylesheets and javascript, use # absolute file paths so that wkhtmltopdf finds them html = make_absolute_paths(html) # keep this around so that the file doesn't get cleaned up # before its used colophon_f = None if self.colophon: colophon = self.render_colophon(document=document, documents=documents) if colophon: colophon_f = tempfile.NamedTemporaryFile(suffix='.html') colophon_f.write(colophon.encode('utf-8')) colophon_f.flush() args.extend(['cover', 'file://' + colophon_f.name]) toc_xsl = options.pop('xsl-style-sheet') if self.toc: args.extend(['toc', '--xsl-style-sheet', toc_xsl]) with tempfile.NamedTemporaryFile(suffix='.html') as f: f.write(html.encode('utf-8')) f.flush() args.append('file://' + f.name) return self._wkhtmltopdf(args, **options)
def render_to_temporary_file(self, template_name, mode='w+b', bufsize=-1, suffix='.html', prefix='tmp', dir=None, delete=True): template = self.resolve_template(template_name) context = self.resolve_context(self.context_data) content = smart_str(template.render(context)) content = make_absolute_paths(content) tempfile = NamedTemporaryFile(mode=mode, bufsize=bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete) try: tempfile.write(content) tempfile.flush() return tempfile except: # Clean-up tempfile if an Exception is raised. tempfile.close() raise
def test_pdf_template_response(self, show_content=False): """Test PDFTemplateResponse.""" context = {'title': 'Heading'} request = RequestFactory().get('/') response = PDFTemplateResponse(request=request, template=self.template, context=context, show_content_in_browser=show_content) self.assertEqual(response._request, request) self.assertEqual(response.template_name, self.template) self.assertEqual(response.context_data, context) self.assertEqual(response.filename, None) self.assertEqual(response.header_template, None) self.assertEqual(response.footer_template, None) self.assertEqual(response.cmd_options, {}) self.assertFalse(response.has_header('Content-Disposition')) # Render to temporary file tempfile = response.render_to_temporary_file(self.template) tempfile.seek(0) html_content = smart_str(tempfile.read()) self.assertTrue(html_content.startswith('<html>')) self.assertTrue('<h1>{title}</h1>'.format(**context) in html_content) pdf_content = response.rendered_content self.assertTrue(pdf_content.startswith(b'%PDF-')) self.assertTrue(pdf_content.endswith(b'%%EOF\n')) # Footer cmd_options = {'title': 'Test PDF'} response = PDFTemplateResponse(request=request, template=self.template, context=context, filename=self.pdf_filename, show_content_in_browser=show_content, footer_template=self.footer_template, cmd_options=cmd_options) self.assertEqual(response.filename, self.pdf_filename) self.assertEqual(response.header_template, None) self.assertEqual(response.footer_template, self.footer_template) self.assertEqual(response.cmd_options, cmd_options) self.assertTrue(response.has_header('Content-Disposition')) tempfile = response.render_to_temporary_file(self.footer_template) tempfile.seek(0) footer_content = smart_str(tempfile.read()) footer_content = make_absolute_paths(footer_content) media_url = 'file://{0}/'.format(settings.MEDIA_ROOT) self.assertTrue(media_url in footer_content, True) static_url = 'file://{0}/'.format(settings.STATIC_ROOT) self.assertTrue(static_url in footer_content, True) pdf_content = response.rendered_content title = '\0'.join(cmd_options['title']) self.assertIn(six.b(title), pdf_content)
def content_to_pdf(content, encoding="utf-8", **options): """ Write into *dest* file object the given html *content*. Returns the PDF Content """ content = make_absolute_paths(content) tempfile = NamedTemporaryFile(mode="w+b", bufsize=-1, suffix=".html", prefix="tmp", dir=None, delete=True) tempfile.write(content.encode(encoding)) tempfile.flush() return wkhtmltopdf(pages=[tempfile.name], **options)
def render_colophon(self, document=None, documents=None): """ Find the colophon template this document and render it, returning the rendered HTML. This renders the colophon using a wrapper template to ensure it's a full HTML document. """ colophon = self.find_colophon(document or documents[0]) if colophon: # find the wrapper template html = render_to_string('indigo_api/akn/export/pdf_colophon.html', { 'colophon': colophon, }) return make_absolute_paths(html)
def test_make_absolute_paths(self): """ Regression test for https://github.com/incuna/django-wkhtmltopdf/issues/22 """ content = """ <img src="/static/foo.png"/> <img src="/static/bar/static/foo.png"/> """ expected = """ <img src="file:///path/to/some/dir/foo.png"/> <img src="file:///path/to/some/dir/bar/static/foo.png"/> """ self.assertEqual(make_absolute_paths(content), expected)
def _html_to_pdf(self, content): content = make_absolute_paths(content) tempfile = NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='.html', prefix='tmp', dir=None, delete=True) tempfile.write(content.encode('utf-8')) tempfile.flush() options = {} """ example usage of wkhtmltopdf method: wkhtmltopdf(pages=['/tmp/example.html'], dpi=300, rotation='Landscape', disable_javascript=True) """ return wkhtmltopdf(pages=[tempfile.name], **options)
def render(self, data, accepted_media_type=None, renderer_context=None): """ returns the default html output as pdf """ content = super(TemplatePDFRenderer, self).render( data, accepted_media_type, renderer_context) content = make_absolute_paths(content) tempfile = NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='.html', prefix='tmp', dir=None, delete=True) tempfile.write(content.encode('utf-8')) tempfile.flush() options = {} """ example usage of wkhtmltopdf method: wkhtmltopdf(pages=['/tmp/example.html'], dpi=300, rotation='Landscape', disable_javascript=True) """ return wkhtmltopdf(pages=[tempfile.name], **options)