Esempio n. 1
0
    def render_url_to_pdf_response(self, url, filename):
        pdf_output = NamedTemporaryFile(delete=True)
        wkhtmltopdf([url], output=pdf_output.name)

        response = PDFResponse(pdf_output, filename=filename)

        return response
Esempio n. 2
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()
Esempio n. 3
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()
Esempio n. 4
0
def create_smartfile_docs(request, clip_id):
    clip = Clipping.objects.get(id=clip_id)
    base_path = settings.MEDIA_URL + clip.filename

    api = generate_api(request)
    create_smartfile_dirs(api)
    api.client.post('/path/data/smartclip/html',
                    file=(clip.filename + '.html',
                          StringIO(clip.html.encode('utf-8'))))

    html_file = open(base_path + '.html', 'w')
    html_file.write(clip.html.encode('ascii', 'xmlcharrefreplace'))
    html_file.close()

    wkhtmltopdf(pages=[base_path + '.html'], output=base_path + '.pdf')

    with open(base_path + '.pdf') as f:
        api.client.post('/path/data/smartclip/pdf',
                        file=(clip.filename + '.pdf', f))

    if os.path.isfile(base_path + '.pdf'):
        os.remove(base_path + '.pdf')

    if os.path.isfile(base_path + '.html'):
        os.remove(base_path + '.html')
Esempio n. 5
0
def create_smartfile_docs(request, clip_id):
    clip = Clipping.objects.get(id=clip_id)
    base_path = settings.MEDIA_URL + clip.filename
    
    api = generate_api(request)
    create_smartfile_dirs(api)
    api.client.post('/path/data/smartclip/html',
                    file=(clip.filename+'.html',
                          StringIO(clip.html.encode('utf-8'))))
    
    html_file = open(base_path+'.html', 'w')
    html_file.write(clip.html.encode('ascii','xmlcharrefreplace'))
    html_file.close()

    wkhtmltopdf(pages=[base_path+'.html'], output=base_path+'.pdf')

    with open(base_path+'.pdf') as f:
        api.client.post('/path/data/smartclip/pdf',
                        file=(clip.filename+'.pdf',f))

    if os.path.isfile(base_path+'.pdf'):
        os.remove(base_path+'.pdf')

    if os.path.isfile(base_path+'.html'):
        os.remove(base_path+'.html')
Esempio n. 6
0
    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)
Esempio n. 7
0
    def get(self, request, *args, **kwargs):
        # render as pdf
        url = '/profiles/%s-%s-%s?print=1' % (self.geo_level, self.geo_code, self.geo.slug)
        url = request.build_absolute_uri(url)
        pdf = wkhtmltopdf(url, zoom=0.7)
        filename = '%s-%s-%s.pdf' % (self.geo_level, self.geo_code, self.geo.slug)

        return PDFResponse(pdf, filename=filename)
Esempio n. 8
0
 def test_wkhtmltopdf_with_unicode_content(self):
     """A wkhtmltopdf call should render unicode content properly"""
     title = u'♥'
     template = loader.get_template('unicode.html')
     temp_file = render_to_temporary_file(template, context={'title': title})
     try:
         pdf_output = wkhtmltopdf(pages=[temp_file.name])
         self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
     finally:
         temp_file.close()
Esempio n. 9
0
 def test_table_of_contents(self):
     title = 'Chapter 1'
     template = loader.get_template('sample.html')
     temp_file = render_to_temporary_file(template,
                                          context={'title': title})
     try:
         pdf_output = wkhtmltopdf(pages=[temp_file.name])
         self.assertTrue(pdf_output.find("Pages 2") > -1)
     finally:
         temp_file.close()
Esempio n. 10
0
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)
Esempio n. 11
0
    def get(self, request, *args, **kwargs):
        profiles = request.GET.get("profiles")
        if profiles:
            url = f"/profiles/{self.geo_level}-{self.geo_code}-{self.geo.slug}/?profiles={profiles}"
        else:
            url = f"/profiles/{self.geo_level}-{self.geo_code}-{self.geo.slug}"

        url = request.build_absolute_uri(url)
        pdf = wkhtmltopdf(url)
        filename = "%s-%s-%s.pdf" % (self.geo_level, self.geo_code, self.geo.slug)

        return PDFResponse(pdf, filename=filename)
Esempio n. 12
0
    def test_wkhtmltopdf(self):
        """Should run wkhtmltopdf to generate a PDF"""
        title = 'A test template.'
        template = loader.get_template('sample.html')
        temp_file = render_to_temporary_file(template, context={'title': title})
        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()
Esempio n. 13
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
Esempio n. 14
0
    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)
Esempio n. 15
0
    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)
Esempio n. 16
0
    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)
Esempio n. 17
0
 def _wkhtmltopdf(self, *args, **kwargs):
     return wkhtmltopdf(*args, **kwargs)