Exemplo n.º 1
0
 def test_no_arguments(self):
     try:
         generate_pdf()
     except ValueError:
         pass
     else:
         raise AssertionError('Should have raised a ValueError')
Exemplo n.º 2
0
 def test_too_many_arguments(self):
     try:
         generate_pdf(
             html='foo',
             url='bar',
         )
     except ValueError:
         pass
     else:
         raise AssertionError('Should have raised a ValueError')
Exemplo n.º 3
0
Arquivo: run.py Projeto: Visar-is/pdf
def html_to_pdf():
    """Takes an HTTP POST of html data and returns a pdf.

    Example use with jQuery:

        $.post('/html-to-pdf, {'html': HTML_DATA})

    """
    raw_html = flask.request.form.get('html', '')
    
    if raw_html:
        pdf_file = generate_pdf(html=raw_html.encode(encoding='UTF-8'))
        
        '''
        template = get_template('my_awesome_template.html')
        html = template.render(RequestContext(request))
        pdf_file = generate_pdf(html=html)
        response = HttpResponse(FileWrapper(pdf_file), content_type='application/pdf')
        response['Content-Disposition'] = 
        response['Content-Length'] = pdf_file.tell()
        pdf_file.seek(0)
        return response
        '''
        
        
        resp = flask.Response(response=pdf_file,
                                  status=200,
                                  mimetype='application/pdf')
        #resp.headers['Content-Disposition'] = 'attachment; filename=%s.pdf' % basename(pdf_file.name)
        #resp.headers['Content-Length'] = pdf_file.tell()
        #pdf_file.seek(0)
        return resp
    else:
        flask.abort(400)
Exemplo n.º 4
0
def html_to_pdf():
    """Takes an HTTP POST of html data and returns a pdf.

    Example use with jQuery:

        $.post('/html-to-pdf, {'html': HTML_DATA})

    """
    raw_html = flask.request.form.get('html', '')

    if raw_html:
        pdf_file = generate_pdf(html=raw_html.encode(encoding='UTF-8'))
        '''
        template = get_template('my_awesome_template.html')
        html = template.render(RequestContext(request))
        pdf_file = generate_pdf(html=html)
        response = HttpResponse(FileWrapper(pdf_file), content_type='application/pdf')
        response['Content-Disposition'] = 
        response['Content-Length'] = pdf_file.tell()
        pdf_file.seek(0)
        return response
        '''

        resp = flask.Response(response=pdf_file,
                              status=200,
                              mimetype='application/pdf')
        #resp.headers['Content-Disposition'] = 'attachment; filename=%s.pdf' % basename(pdf_file.name)
        #resp.headers['Content-Length'] = pdf_file.tell()
        #pdf_file.seek(0)
        return resp
    else:
        flask.abort(400)
Exemplo n.º 5
0
def index(request):
    context_dict = {}
    
    if request.method == 'POST':
        form = MarkdownForm(request.POST)
        if form.is_valid():
            html = make_html(form.cleaned_data['markdown_input'])
            context_dict['html'] = html
            styling = form.cleaned_data['stationary'].styling
            render_dict =  {'html':html, 'styling':styling}

            if 'generate' in request.POST:
                return render_to_response('documanager/browser_render.html',
                    render_dict,
                    context_instance = RequestContext(request))

            elif 'print' in request.POST:
                rendered_html = render_to_string('documanager/print_render.html',
                                render_dict)
            
                pdf_file = generate_pdf(html=rendered_html)
                return HttpResponse(FileWrapper(pdf_file),
                        content_type = 'application/pdf')
    else:
        form = MarkdownForm()
    
    if not Stationary.objects.all():
        context_dict['no_stationary'] = "There are no stationaries"

    context_dict['form'] = form
    return render_to_response("documanager/home.html",
                               context_dict, 
                               context_instance=RequestContext(request)
                              )    
Exemplo n.º 6
0
    def _pdf_of_html_report(self, request, pk, report_name):
        # Use wkhtmltopdf to write PDF of HTML report to file on disk
        jwt = request.auth or self._jwt_from_request(request)
        proposal_filename = 'data/%s_%s.pdf' % (report_name, pk)
        url = request.build_absolute_uri('../%s/?jwt=%s' % (report_name, jwt))
        pdf_file = generate_pdf(url=url)
        # Read from the PDF just dumped
        contentfile = open(pdf_file.name, 'rb')
        return contentfile

        merger.append(contentfile)
Exemplo n.º 7
0
    def _pdf_of_html_report(self, request, pk, report_name):
        # Use wkhtmltopdf to write PDF of HTML report to file on disk
        jwt = request.auth or self._jwt_from_request(request)
        proposal_filename = 'data/%s_%s.pdf' % (report_name, pk)
        url = request.build_absolute_uri('../%s/?jwt=%s'
            % (report_name, jwt))
        pdf_file = generate_pdf(url=url)
        # Read from the PDF just dumped
        contentfile = open(pdf_file.name, 'rb')
        return contentfile

        merger.append(contentfile)
Exemplo n.º 8
0
def hello():
    pdf_file = generate_pdf(html="""
<html>
    <head>
        <title>Hello, world</title>
    </head>
    <body>
        <h1>Hello, cruel world!</h1>
    </body>
</html>
    """)
    return send_file(pdf_file)
Exemplo n.º 9
0
def regenerate(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            to_search = request.POST.get('INV')
            try:
                data = database.objects.filter(invoice_no=str(to_search))
                try:
                    data = data[0]
                except:
                    return HttpResponse("Invoice not found!")
            except:
                return HttpResponse("Unable to access database!")
            c_dic={}
            c_dic['firm'] = data.firm
            is_Firm1 = c['firm'] =="Firm 1"
            c_dic['bill_type'] = data.bill_type
            c_dic['PD']=data.party_details
            c_dic['PT']=data.party_tin
            c_dic['IN']=data.invoice_no
            c_dic['DATE']=data.dated
            c_dic['TP']=data.transport
            c_dic['VN']=data.vehicle_no
            c_dic['ST']=data.station
            name = data.desc.split('~')
            qty = data.qty.split('~')
            unit = data.unit.split('~')
            price = data.price.split('~')
            amount =[int(i.strip(' '))*int(j.strip(' ')) for i,j in zip(qty,price)]
            gst = data.gst
            gst_val = round(float(gst)/2.0,2)
            sno = range(1,len(name)+1)
            br_extra = range(15-len(sno))
            val = zip(sno,name,qty,unit,price,amount)
            total = sum(amount)
            gtotal = total+total*(float(gst)/100)

            #convert number to words
            words =  ntw().convertNumberToWords(gtotal)[3:]+' Only'
            source = render_to_string("bill.html",{'info':c_dic,'val':val,'brs':br_extra,'last':br_extra[len(br_extra)-1],'total':total
            ,'gst':gst_val,'csgst':float(total*float(gst_val))/100,'gtotal':gtotal,'inwords':words,'is_Firm1':is_Firm1})
            pdf =generate_pdf(html=source)
            response = HttpResponse(pdf.read(),content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=%s' % smart_str('out.pdf')
            return response
        else:
            return render(request,"formx.html")
    else:
        return redirect('/login')
Exemplo n.º 10
0
def email_pdf(request):
    if request.method == 'POST':    
        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest("No JSON provided")
        try: 
            msubject = data['Subject']
            mfrom = data['From']
            mbody = data['TextBody']
        except KeyError:
                return HttpResponseBadRequest("Invalid JSON")
    
        # Now let's create the pdf
        try:
            styling = Stationary.objects.get(name__icontains='msubject').styling
        except ObjectDoesNotExist: 
            styling = '' 

        rendered_html = render_to_string('documanager/print_render.html',
                                        {'html':mbody, 'styling':styling})

        pdf_file = generate_pdf(html=rendered_html)
        PM_API_KEY = getattr(settings, "PM_API_KEY", None)
        PM_SENDER =  getattr(settings, "PM_SENDER", None)

        message = pystmark.Message(sender=PM_SENDER, to=mfrom, 
                                   subject = 'Hi', text = 'Your email should (not yet) be attached',
                                   tag = 'greeting')
        pystmark.send(message, api_key=PM_API_KEY)


        return HttpResponse("Success!")


    else:
        return HttpResponseNotAllowed(['POST'])
Exemplo n.º 11
0
def main(request):
    global source
    if request.user.is_authenticated:
        if request.method == "POST":
            c_dic={}
            c_dic['firm'] = request.POST.get('firm')
            c_dic['bill_type'] = request.POST.get('bill_type')
            is_Firm1 = c_dic['firm']=="Firm 1"
            c_dic['PD']=request.POST.get('PD')
            c_dic['PT']=request.POST.get('PT')
            c_dic['IN']=request.POST.get('IN')
            c_dic['DATE']=request.POST.get('DATE')
            c_dic['TP']=request.POST.get('TP')
            c_dic['VN']=request.POST.get('VN')
            c_dic['ST']=request.POST.get('ST')
            name = request.POST.getlist('DG')
            qty = request.POST.getlist('QTY')
            unit = request.POST.getlist('UNIT')
            price = request.POST.getlist('PRICE')
            amount =[int(i.strip(' '))*int(j.strip(' ')) for i,j in zip(qty,price)]
            gst = request.POST.get('GST')
            gst_val = round(float(gst)/2.0,2)
            sno = range(1,len(name)+1)
            br_extra = range(15-len(sno))
            val = zip(sno,name,qty,unit,price,amount)
            total = sum(amount)
            gtotal = total+total*(float(gst)/100)

            #convert number to words
            words =  ntw().convertNumberToWords(gtotal)[4:]+' Only';

            # Saving all to database
            try:
                database(
                    firm = c_dic['firm'],
                    bill_type = c_dic['bill_type'],
                    invoice_no=c_dic['IN'],
                    dated = c_dic['DATE'],
                    party_details=c_dic['PD'],
                    party_tin = c_dic['PT'],
                    transport=c_dic['TP'],
                    station=c_dic['ST'],
                    vehicle_no=c_dic['VN'],
                    desc='~'.join(name),
                    qty = '~'.join([str(i) for i in qty]),
                    unit = '~'.join(unit),
                    price = '~'.join([str(i) for i in price]),
                    gst = str(gst)
                ).save()
            except:
                return HttpResponse("Data could not be saved to database")
            source = render_to_string("bill.html",{'info':c_dic,'val':val,'brs':br_extra,'last':br_extra[len(br_extra)-1],'total':total
            ,'gst':gst_val,'csgst':float(total*float(gst_val))/100,'gtotal':gtotal,'inwords':words,'is_Firm1':is_Firm1})
            pdf = generate_pdf(html=source)
            response = HttpResponse(pdf.read(),content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=%s' % smart_str('out.pdf')
            return response

            #return render(request,"bill.html",{'info':c_dic,'val':val,'brs':br_extra,'last':br_extra[len(br_extra)-1],'total':total
            #,'gst':gst_val,'csgst':float(total*float(gst_val))/100,'gtotal':gtotal,'inwords':words})
        else:
            return render(request,"form.html")
    else:
        return redirect('/login')
Exemplo n.º 12
0
 def test_generate_pdf(self, mock_post):
     pdf_file = generate_pdf('<html><body>Is this thing on?</body></html>')
     self.assertTrue(os_path.exists(pdf_file.name))
Exemplo n.º 13
0
 def test_generate_pdf_with_html(self):
     pdf_content = generate_pdf(
         html='<html><body>Is this thing on?</body></html>',
     )
     assert pdf_content[:4] == '%PDF'
Exemplo n.º 14
0
 def test_unicode(self):
     pdf_content = generate_pdf(
         html=u'<html><body>Schrödinger</body></html>',
     )
     assert pdf_content[:4] == '%PDF'
Exemplo n.º 15
0
 def test_generate_pdf_with_url(self):
     pdf_content = generate_pdf(
         url='http://google.com',
     )
     assert pdf_content[:4] == '%PDF'