Example #1
0
    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)
Example #2
0
    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)
Example #3
0
 def create_pdf(self):
     return_file = (
         "invoices/" + "Invoice_" +
         str(self.client.profile.last_name) + '_' +
         str(self.client.profile.first_name) + '_' +
         str(self.start_date.month) + '.pdf'
     )
     abs_return_file = settings.MEDIA_ROOT + return_file
     context = {
         'invoice' : self,
         'user' : User.objects.get(username='******'),
         'pdf' : True,
     }
     factory = RequestFactory()
     response = PDFTemplateResponse(
         request=factory.get('/admin/'), 
         context=context, 
         template=get_template('invoice.html'),
         cmd_options={
             'page-size': 'Letter',
             'quiet': False
         },
     )
     temp_file = response.render_to_temporary_file(
                         "invoice.html")
     try:
         wkhtmltopdf(pages=[temp_file.name], output=abs_return_file)
         self.pdf.name = return_file
     finally:
         temp_file.close()
     self.save()
Example #4
0
    def test_wkhtmltopdf(self):
        """Should run wkhtmltopdf to generate a PDF"""
        title = 'A test template.'
        response = PDFTemplateResponse(self.factory.get('/'),
                                       None,
                                       context={'title': title})
        temp_file = response.render_to_temporary_file('sample.html')
        try:
            # Standard call
            pdf_output = wkhtmltopdf(pages=[temp_file.name])
            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)

            # Single page
            pdf_output = wkhtmltopdf(pages=temp_file.name)
            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)

            # Unicode
            pdf_output = wkhtmltopdf(pages=[temp_file.name], title=u'♥')
            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)

            # Invalid arguments
            self.assertRaises(CalledProcessError,
                              wkhtmltopdf, pages=[])
        finally:
            temp_file.close()
Example #5
0
 def test_PDFTemplateResponse_render_to_temporary_file(self):
     """Should render a template to a temporary file."""
     title = 'A test template.'
     response = PDFTemplateResponse(self.factory.get('/'), None, context={'title': title})
     temp_file = response.render_to_temporary_file('sample.html')
     temp_file.seek(0)
     saved_content = temp_file.read()
     self.assertTrue(title in saved_content)
     temp_file.close()
Example #6
0
 def test_PDFTemplateResponse_render_to_temporary_file(self):
     """Should render a template to a temporary file."""
     title = 'A test template.'
     response = PDFTemplateResponse(self.factory.get('/'), None, context={'title': title})
     temp_file = response.render_to_temporary_file('sample.html')
     temp_file.seek(0)
     saved_content = smart_str(temp_file.read())
     self.assertTrue(title in saved_content)
     temp_file.close()
Example #7
0
 def test_wkhtmltopdf_with_unicode_content(self):
     """A wkhtmltopdf call should render unicode content properly"""
     title = u'♥'
     response = PDFTemplateResponse(self.factory.get('/'),
                                    None,
                                    context={'title': title})
     temp_file = response.render_to_temporary_file('unicode.html')
     try:
         pdf_output = wkhtmltopdf(pages=[temp_file.name])
         self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
     finally:
         temp_file.close()
Example #8
0
 def test_wkhtmltopdf_with_unicode_content(self):
     """A wkhtmltopdf call should render unicode content properly"""
     title = u'♥'
     response = PDFTemplateResponse(self.factory.get('/'),
                                    None,
                                    context={'title': title})
     temp_file = response.render_to_temporary_file('unicode.html')
     try:
         pdf_output = wkhtmltopdf(pages=[temp_file.name])
         self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
     finally:
         temp_file.close()
Example #9
0
    def test_wkhtmltopdf(self):
        """Should run wkhtmltopdf to generate a PDF"""
        title = 'A test template.'
        response = PDFTemplateResponse(self.factory.get('/'), None, context={'title': title})
        temp_file = response.render_to_temporary_file('sample.html')
        try:
            # Standard call
            pdf_output = wkhtmltopdf(pages=[temp_file.name])
            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)

            # Single page
            pdf_output = wkhtmltopdf(pages=temp_file.name)
            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)

            # Unicode
            pdf_output = wkhtmltopdf(pages=[temp_file.name], title=u'♥')
            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)

            # Invalid arguments
            self.assertRaises(CalledProcessError,
                              wkhtmltopdf, pages=[])
        finally:
            temp_file.close()
Example #10
0
def getPDF(request, context, template, path, filename, displayInBrowserFlag,
           landscapeFlag):
    os.environ["DISPLAY"] = ":0"
    cmd_options = {}
    if landscapeFlag == True:
        cmd_options['orientation'] = 'landscape'
    else:
        cmd_options['orientation'] = 'portrait'
    response = PDFTemplateResponse(
        request=request,
        template=template,
        filename=filename,
        context=context,
        show_content_in_browser=displayInBrowserFlag,
        cmd_options=cmd_options,
    )
    temp_file = response.render_to_temporary_file(template)
    wkhtmltopdf(pages=[temp_file.name],
                output=path + filename,
                orientation=cmd_options['orientation'])
    ## remove tmp files
    for fileName in glob.glob("/tmp/wkhtmltopdf*"):
        os.remove(fileName)
    return response
Example #11
0
    def test_pdf_template_response(self):
        """Test PDFTemplateResponse."""
        from django.conf import settings

        with override_settings(
                MEDIA_URL='/media/',
                MEDIA_ROOT='/tmp/media',
                STATIC_URL='/static/',
                STATIC_ROOT='/tmp/static',
                TEMPLATE_CONTEXT_PROCESSORS=[
                    'django.core.context_processors.media',
                    'django.core.context_processors.static',
                ],
                TEMPLATE_LOADERS=['django.template.loaders.filesystem.Loader'],
                TEMPLATE_DIRS=[
                    os.path.join(os.path.dirname(__file__), '_testproject',
                                 'templates')
                ],
                WKHTMLTOPDF_DEBUG=False,
        ):
            # Setup sample.html
            template = 'sample.html'
            context = {'title': 'Heading'}
            request = RequestFactory().get('/')
            response = PDFTemplateResponse(request=request,
                                           template=template,
                                           context=context)
            self.assertEqual(response._request, request)
            self.assertEqual(response.template_name, 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(template)
            tempfile.seek(0)
            html_content = 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('%PDF-'))
            self.assertTrue(pdf_content.endswith('%%EOF\n'))

            # Footer
            filename = 'output.pdf'
            footer_template = 'footer.html'
            cmd_options = {'title': 'Test PDF'}
            response = PDFTemplateResponse(request=request,
                                           template=template,
                                           context=context,
                                           filename=filename,
                                           footer_template=footer_template,
                                           cmd_options=cmd_options)
            self.assertEqual(response.filename, filename)
            self.assertEqual(response.header_template, None)
            self.assertEqual(response.footer_template, footer_template)
            self.assertEqual(response.cmd_options, cmd_options)
            self.assertTrue(response.has_header('Content-Disposition'))

            tempfile = response.render_to_temporary_file(footer_template)
            tempfile.seek(0)
            footer_content = tempfile.read()

            media_url = 'MEDIA_URL = file://{0}/'.format(settings.MEDIA_ROOT)
            self.assertTrue(
                media_url in footer_content,
                "{0!r} not in {1!r}".format(media_url, footer_content))

            static_url = 'STATIC_URL = file://{0}/'.format(
                settings.STATIC_ROOT)
            self.assertTrue(
                static_url in footer_content,
                "{0!r} not in {1!r}".format(static_url, footer_content))

            pdf_content = response.rendered_content
            self.assertTrue('\0'.join('{title}'.format(
                **cmd_options)) in pdf_content)

            # Override settings
            response = PDFTemplateResponse(
                request=request,
                template=template,
                context=context,
                filename=filename,
                footer_template=footer_template,
                cmd_options=cmd_options,
                override_settings={'STATIC_URL': 'file:///tmp/s/'})
            tempfile = response.render_to_temporary_file(footer_template)
            tempfile.seek(0)
            footer_content = tempfile.read()

            static_url = 'STATIC_URL = {0}'.format('file:///tmp/s/')
            self.assertTrue(
                static_url in footer_content,
                "{0!r} not in {1!r}".format(static_url, footer_content))
            self.assertEqual(settings.STATIC_URL, '/static/')
Example #12
0
    def test_pdf_template_response(self):
        """Test PDFTemplateResponse."""
        from django.conf import settings

        with override_settings(
            MEDIA_URL='/media/',
            MEDIA_ROOT='/tmp/media',
            STATIC_URL='/static/',
            STATIC_ROOT='/tmp/static',
            TEMPLATE_CONTEXT_PROCESSORS=[
                'django.core.context_processors.media',
                'django.core.context_processors.static',
            ],
            TEMPLATE_LOADERS=['django.template.loaders.filesystem.Loader'],
            TEMPLATE_DIRS=[os.path.join(os.path.dirname(__file__),
                                        '_testproject', 'templates')],
            WKHTMLTOPDF_DEBUG=False,
        ):
            # Setup sample.html
            template = 'sample.html'
            context = {'title': 'Heading'}
            request = RequestFactory().get('/')
            response = PDFTemplateResponse(request=request,
                                           template=template,
                                           context=context)
            self.assertEqual(response._request, request)
            self.assertEqual(response.template_name, 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(template)
            tempfile.seek(0)
            html_content = 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('%PDF-'))
            self.assertTrue(pdf_content.endswith('%%EOF\n'))

            # Footer
            filename = 'output.pdf'
            footer_template = 'footer.html'
            cmd_options = {'title': 'Test PDF'}
            response = PDFTemplateResponse(request=request,
                                           template=template,
                                           context=context,
                                           filename=filename,
                                           footer_template=footer_template,
                                           cmd_options=cmd_options)
            self.assertEqual(response.filename, filename)
            self.assertEqual(response.header_template, None)
            self.assertEqual(response.footer_template, footer_template)
            self.assertEqual(response.cmd_options, cmd_options)
            self.assertTrue(response.has_header('Content-Disposition'))

            tempfile = response.render_to_temporary_file(footer_template)
            tempfile.seek(0)
            footer_content = tempfile.read()

            media_url = 'MEDIA_URL = file://{0}/'.format(settings.MEDIA_ROOT)
            self.assertTrue(
                media_url in footer_content,
                "{0!r} not in {1!r}".format(media_url, footer_content)
            )

            static_url = 'STATIC_URL = file://{0}/'.format(settings.STATIC_ROOT)
            self.assertTrue(
                static_url in footer_content,
                "{0!r} not in {1!r}".format(static_url, footer_content)
            )

            pdf_content = response.rendered_content
            self.assertTrue('\0'.join('{title}'.format(**cmd_options))
                            in pdf_content)

            # Override settings
            response = PDFTemplateResponse(request=request,
                                           template=template,
                                           context=context,
                                           filename=filename,
                                           footer_template=footer_template,
                                           cmd_options=cmd_options,
                                           override_settings={
                                               'STATIC_URL': 'file:///tmp/s/'
                                           })
            tempfile = response.render_to_temporary_file(footer_template)
            tempfile.seek(0)
            footer_content = tempfile.read()

            static_url = 'STATIC_URL = {0}'.format('file:///tmp/s/')
            self.assertTrue(
                static_url in footer_content,
                "{0!r} not in {1!r}".format(static_url, footer_content)
            )
            self.assertEqual(settings.STATIC_URL, '/static/')