Ejemplo n.º 1
0
    def send_mail(subject, html_content, text_content, recipients, expert_request=None, attach_tor=False,
                  attach_letter=False):
        # control of execution
        if email_is_off():
            return

        # control of environment
        if env_is_local():
            # local env email only to secondments mail list
            recipients = SECONDMENTS_MAIL_LIST
        # test indicator to render PDF as test sample
        test = test_is_on()
        if test:
            # subject with TEST
            subject = "This is a TEST email! " + subject

        msg = EmailMultiAlternatives(subject, text_content, EMAIL_HOST_USER, recipients, bcc=SECONDMENTS_MAIL_LIST)
        msg.attach_alternative(html_content, "text/html")
        msg.mixed_subtype = 'related'

        # attachments stuff
        if attach_letter or attach_tor:
            context = {'expert_request': expert_request, 'pagesize': 'A4',
                       'BASE_DIR': os.path.join(BASE_DIR, 'crppdmt/static/'), 'test_env': test,}
            try:
                tor_pdf = render_to_pdf('crppdmt/pdf/tor.html', context)
                letter_pdf = render_to_pdf('crppdmt/pdf/letter_of_request.html', context)
                msg.attach('ToR.pdf',tor_pdf,'application/pdf')
                msg.attach('LetterOfRequest.pdf',letter_pdf,'application/pdf')
            except:
                print("Error attaching ToR and Letter to Email. Request: " + expert_request.name)
                print("Error: " + str(sys.exc_info()))

        msg.send()
Ejemplo n.º 2
0
    def get(self, request, *args, **kwargs):

        self.order = Order.objects.get(number=kwargs['number'])

        ctx = self.get_context_data()

        render_to_pdf(request=request,
                      template=self.template_name,
                      context=ctx,
                      download_filename=self.download_filename)

        return super(InvoiceDownloadView, self).get(request, *args, **kwargs)
Ejemplo n.º 3
0
    def send_mail(subject,
                  html_content,
                  text_content,
                  recipients,
                  expert_request=None,
                  attach_tor=False,
                  attach_letter=False):
        # control of execution
        if email_is_off():
            return

        # control of environment
        if env_is_local():
            # local env email only to secondments mail list
            recipients = SECONDMENTS_MAIL_LIST
        # test indicator to render PDF as test sample
        test = test_is_on()
        if test:
            # subject with TEST
            subject = "This is a TEST email! " + subject

        msg = EmailMultiAlternatives(subject,
                                     text_content,
                                     EMAIL_HOST_USER,
                                     recipients,
                                     bcc=SECONDMENTS_MAIL_LIST)
        msg.attach_alternative(html_content, "text/html")
        msg.mixed_subtype = 'related'

        # attachments stuff
        if attach_letter or attach_tor:
            context = {
                'expert_request': expert_request,
                'pagesize': 'A4',
                'BASE_DIR': os.path.join(BASE_DIR, 'crppdmt/static/'),
                'test_env': test,
            }
            try:
                tor_pdf = render_to_pdf('crppdmt/pdf/tor.html', context)
                letter_pdf = render_to_pdf(
                    'crppdmt/pdf/letter_of_request.html', context)
                msg.attach('ToR.pdf', tor_pdf, 'application/pdf')
                msg.attach('LetterOfRequest.pdf', letter_pdf,
                           'application/pdf')
            except:
                print("Error attaching ToR and Letter to Email. Request: " +
                      expert_request.name)
                print("Error: " + str(sys.exc_info()))

        msg.send()
Ejemplo n.º 4
0
 def render(self, data, accepted_media_type=None, renderer_context=None):
     try:
         entry = data["items"][0]
     except IndexError:
         context = {
             "header_rows": [],
             "content_rows": [],
             "total": 0,
             "title": data["title"],
         }
     else:
         group_by_month = entry.has_key("months")
         context = {
             "total":
             data["total_occurrences"],
             "title":
             data["title"],
             "header_rows":
             self.get_header_rows(entry,
                                  year=data.get("year"),
                                  group_by_month=group_by_month),
             "content_rows":
             self.get_content_rows(data["items"],
                                   group_by_month=group_by_month),
         }
     return render_to_pdf("nfdrenderers/pdf/aggregation_stats.html",
                          context)
Ejemplo n.º 5
0
def send_email(obj, user, userdata, doctordata, measurements) -> bool:
    """sends email from user's email to doctor, message contains all user's measurements and an attachment - PDF file

    Args:
        obj (SendDataToDoctor): [object representing view]
        user (UserData): [user's data]
        doctor (DoctorData): [doctor's data]
        measurements (Measurement): [all measurements belongs to logged user]
    """
    topic = "Pomiary ciśnienia krwi"
    message = "Pomiary ciśnienia krwi dla użytkownika {name} {surname}".format(
        name=userdata.name, surname=userdata.surname)

    context = {}
    context["user"] = userdata
    context["measurements"] = measurements

    try:
        attachment = render_to_pdf("generate_files/PDF_template.html", context)
    except Exception as e:
        print(e)
        print("Błąd przy tworzeniu załącznika")
        attachment = None
        return False

    email = EmailMessage(topic, message, user.email, [doctordata.email])
    email.attach("pomiary.pdf", attachment)
    email.send()
    return True
Ejemplo n.º 6
0
    def generate_pdf(self):
        today = datetime.datetime.today()
        data = {
            'surname': self.surname,
            'first_name': self.first_name,
            'year': today.year,
            'month': today.month,
            'hours': self.hours,
            'last_day_of_month': calendar.monthrange(today.year,
                                                     today.month)[1],
            'unit_of_organisation': self.unit_of_organisation,
        }

        timesheet_data, header_date, total_hours = generate_timesheet_data(
            year=data['year'],
            month=data['month'],
            fdom=1,
            ldom=data['last_day_of_month'],
            hours=data['hours'])

        data.update({
            'timesheet_data': timesheet_data,
            'header_date': header_date,
            'total_hours': total_hours
        })

        return render_to_pdf(template='creator/timesheet.html', context=data)
Ejemplo n.º 7
0
def generate_final_report(obj, code, labels, pdf, template, filename):
    labels_serializer = labels(obj)
    pdf_serializer = pdf(obj)
    context = {
        'engagement': pdf_serializer.data,
        'serializer': labels_serializer,
    }

    content_type = ContentType.objects.get_for_model(obj)
    file_type, __ = FileType.objects.get_or_create(
        code=code,
        defaults={
            "label": code.replace("_", " ").title(),
            "name": code.replace("_", " "),
        }
    )
    attachment, __ = Attachment.objects.get_or_create(
        code=code,
        content_type=content_type,
        object_id=obj.pk,
        defaults={
            "file_type": file_type,
        }
    )

    file_path = generate_file_path(attachment, filename)
    attachment.file.save(
        file_path,
        ContentFile(render_to_pdf(template, context)),
    )
Ejemplo n.º 8
0
 def render(self, data, accepted_media_type=None, renderer_context=None):
     occurrences = []
     for index, occ in enumerate(data):
         occurrence = _get_occurrence(occ)
         occurrence.update(index=index + 1)
         occurrences.append(occurrence)
     query_params = renderer_context["request"].query_params.dict()
     filters = self.get_filters(query_params)
     filters.update(
         natural_area_code_nac=query_params.get("natural_area_code_nac"),
         general_description=query_params.get("general_description"),
         notable_features=query_params.get("notable_features"),
     )
     default_columns = [
         "list_id",
         "genus",
         "natural_area_code",
         "general_description",
         "cm_status",
         "latitude",
         "longitude",
     ]
     chosen_table_columns = get_table_columns(query_params, default_columns)
     table_columns = chosen_table_columns if len(
         chosen_table_columns) > 0 else default_columns[0:1]
     return render_to_pdf(
         "nfdrenderers/pdf/natural_area_occurrence_report.html",
         context={
             "occurrences": occurrences,
             "filters": {k: v
                         for k, v in filters.items() if v},
             "table_columns": table_columns,
         })
Ejemplo n.º 9
0
def __email(request):
    arguments = request.session['job_app_args']
    message = request.session['email']
    to = [request.POST.get('address')]

    context = Context(arguments)
    template = 'cover_letter_pdf.html'
    cover_letter = render_to_pdf(template, context)

    print request.POST

    email = EmailMessage(subject=arguments.get('job_position'), body=message,
             bcc=['*****@*****.**'],
             from_email='*****@*****.**', to=to)
    email.content_subtype = "html"



    cv = CV.objects.first()
    email.attach('EkaterinaStepanova.CV.pdf', cv.file.read(), 'application/pdf')

    if 'vdom' in request.POST:
        vdom = Reference.objects.filter(name='vdom').first()
        email.attach('EkaterinaStepanova.Reference.VDOM.pdf', vdom.file.read(), 'application/pdf')
    if 'nec' in request.POST:
        nec = Reference.objects.filter(name='nec').first()
        email.attach('EkaterinaStepanova.Reference.NEC.pdf', nec.file.read(), 'application/pdf')

    email.attach('EkaterinaStepanova.MotivationLetter.pdf', cover_letter, 'application/pdf')
    email.send()

    return render(request, 'home.html')
Ejemplo n.º 10
0
def render_propietario_report_pdf(inmueble_pk, mes, site_name):
    '''

	this method generates the resumen for propietarios pdf
	'''
    from condominioaldia_app.models import Inmueble

    month = mes
    inmueble = Inmueble.objects.get(pk=inmueble_pk)
    #GET THE EGRESOS
    month_range = month_range_dt(month)
    egresos = inmueble.condominio.egreso_condominio_set.filter(
        mes__range=(month_range[0], month_range[1]))
    sum_egresos = egresos.aggregate(
        total_deuda=Sum('monto'))['total_deuda'] or 0
    ######################
    #cobranzas = inmueble.cobranza_condominio_set.filter(payment__aprobado =True)
    cobranzas = inmueble.cobranza_condominio_set.filter(
        mes__range=(month_range[0], month_range[1]))
    sum_cobranzas = get_total_cobranzas(cobranzas, inmueble, sum_egresos)

    pagos = inmueble.ingreso_condominio_set.filter(mes__range=(month_range[0],
                                                               month_range[1]),
                                                   aprobado=True)
    factura_propietario = inmueble.factura_propietario_set.filter(
        mes__range=(month_range[0], month_range[1]))[0]
    context = {}
    context['mes'] = month
    context['aviso'] = '''
	De acuerdo a los articulos 14 y 15 de la ley horizontal, 
	el presenteaviso de cobro tiene valor yfuerza ejecutiva
	'''
    #NEED TO GET TOTAL OWED
    debt_properties = inmueble.condominio.inmueble_set.filter(
        deuda_actual__lt=0)
    context['debt_properties'] = debt_properties
    context['pagos'] = pagos
    context['site_name'] = site_name
    context['inmueble'] = inmueble
    context['cobranzas'] = cobranzas
    context['cuentas'] = inmueble.condominio.bancos_set.all()
    context['egresos'] = egresos
    context['sum_cobranzas'] = decimal.Decimal(sum_cobranzas).quantize(
        settings.TWOPLACES)
    context['factura_propietario'] = factura_propietario
    context['paper_type'] = 'landscape'
    context['sum_egresos'] = sum_egresos
    context['pagesize'] = 'letter'
    context['page_margin_top'] = '1cm'
    context['page_margin_bottom'] = '1cm'
    context['page_margin_left'] = '1cm'
    context['page_margin_right'] = '1cm'
    context['footer_height'] = '1cm'
    context[
        'balance_title'] = 'Deuda' if factura_propietario.monto < 0 else 'Balance'
    template = 'pdf/reporte_mensual_propietario.html'
    pdf = render_to_pdf(template, context)
    return pdf
Ejemplo n.º 11
0
    def export_pdf(self):
        columns = []
        for i in range(len(self._datatable.columns)):
            field = list(self._datatable.columns.keys())[i]
            col = self._datatable.columns[field]
            if not col.export or isinstance(col, DisplayColumn):
                continue
            columns.append(col)

        cabecera = []
        for i in range(len(columns)):
            if not columns[i].export:
                continue
            cabecera.append(columns[i].label)

        datos = []

        r = 0
        for row in self._datatable.search(self.get_queryset()):
            d = []
            for i in range(len(columns)):
                if not columns[i].export:
                    continue
                if columns[i].processor:
                    val = getattr(self._datatable,
                                  columns[i].processor)(row, self._datatable)
                else:
                    val = row
                    for attr in columns[i].sources[0].split('__'):
                        try:
                            val = getattr(val, attr)
                        except:
                            val = ''
                if isinstance(val, models.Model):
                    val = str(val)
                if val is None:
                    val = ''
                d.append(val)
            r += 1
            datos.append(d)
        if hasattr(settings, 'LOGO_URL_DATATABLE'):
            logo_url = settings.LOGO_URL_DATATABLE
        else:
            logo_url = ''
        if hasattr(settings, 'MEDIA_ROOT'):
            static_url = settings.MEDIA_ROOT
        else:
            static_url = ''
        pdf = render_to_pdf(
            'datatableview/pdf.html', {
                'cabecera': cabecera,
                'datos': datos,
                'logo': logo_url,
                'url': static_url
            })
        return make_response(pdf, 'data.pdf')
Ejemplo n.º 12
0
def payment_complete(request):
    import os

    cart_proxy = CartProxy(request)
    cart_proxy.clear()
    cart_proxy.cart.delete()
    order_group = OrderGroup.objects.get(pk=request.session['order_group'])
    context = {
        'order_group':
        order_group,
        'order_group_detail_url':
        request.build_absolute_uri(
            reverse('order-details', args={order_group.hash})),
        'invoice_no':
        order_group.hash.hex[:6],
        'contact':
        order_group.contact,
        'settings':
        settings.INVOICE_SETTINGS
    }
    paypalLogger.debug('Processing payment complete...')
    paypalLogger.debug('Setting email context to: ')
    paypalLogger.debug(context)
    html_msg = render_to_string('order/email/order_placed/customer_main.html',
                                context=context)
    text_msg = strip_tags(html_msg)
    # send email to customer
    paypalLogger.debug('Sending email ..')
    msg = EmailMultiAlternatives('Your order',
                                 body=text_msg,
                                 from_email='*****@*****.**',
                                 to=[
                                     order_group.customer.email,
                                 ],
                                 bcc=__get_admins_email())
    #create invoice pdf
    invoice_pdf = render_to_pdf('order/email/order_placed/invoice.html',
                                context)
    temp = tempfile.NamedTemporaryFile(mode='wb', delete=False)
    temp.write(invoice_pdf)
    temp.close()
    file_name = 'invoice_{}.pdf'.format(order_group.hash.hex[:6])
    os.rename(temp.name, file_name)
    #attach and send
    msg.attach_alternative(html_msg, "text/html")
    msg.attach_file(file_name)
    msg.send()
    #clean up
    os.remove(file_name)
    paypalLogger.debug('Email sent to {} and admin email {}'.format(
        order_group.customer.email, __get_admins_email()))

    return render(request, 'payment/payment_complete.html', {
        'section': 'Payment',
        'order_id': order_group.pk
    })
Ejemplo n.º 13
0
 def get_as_response(self):
     try:
         pdf = render_to_pdf(self.template_name, self.get_context())
         response = make_response(pdf)
         response['Content-disposition'] = 'inline; filename="{}"'.format(self.file_name)
         return response
     except PDFRenderingError:
         error_message = 'Error trying to render PDF'
         logger.exception(error_message)
         return HttpResponse(error_message)
Ejemplo n.º 14
0
    def get(self, *args, **kwargs):
        salary = get_object_or_404(Salary, **kwargs)
        pdf = render_to_pdf('emails/payslip.html', {'salary': salary})

        filename = slugify(f"{salary.user.get_full_name()} {salary.period}")

        response = HttpResponse(pdf, content_type="application/pdf")
        response['Content-Disposition'] = f"attachment; filename=payslip_{filename}.pdf"

        return response
Ejemplo n.º 15
0
 def get(self, request, *args, **kwargs):
     context = self.get_context_data(**kwargs)
     context["query_results"] = self.query_results
     response = HttpResponse(content_type='application/pdf')
     response['Content-Disposition'] = 'attachment; filename="filename.pdf"'
     bts = render_to_pdf(self.template_name, context)    
     # logger.debug(bts)
     # logger.debug(str(bts))
     response.write(bts)
     return response
Ejemplo n.º 16
0
def generate_portfolio_pdf(request, pk, context):
    customer = get_object_or_404(Customer, pk=pk)
    template = get_template('portfolio/portfolio_pdf.html')

    html = template.render(context)
    pdf = render_to_pdf('portfolio/portfolio_pdf.html', context)
    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'filename= "portfolio_{}.pdf"'.format(customer.name)
        return pdf
    return HttpResponse("Not Found")
Ejemplo n.º 17
0
def signature_render(request, username, doc_type, signature_file):
    user = get_object_or_404(User, username=username)
    today = timezone.localtime(timezone.now()).date()
    pdf_args = {'name': user.get_full_name, 'date': today, 'doc_type': doc_type, 'signature_file': signature_file}
    if 'save_file' in request.GET:
        # Save the PDF as a file and redirect them back to the document list
        pdf_data = render_to_pdf('tablet/signature_render.html', pdf_args)
        pdf_file = FileUpload.objects.pdf_from_string(user, pdf_data, doc_type, user)
        os.remove(os.path.join(settings.MEDIA_ROOT, "signatures/%s" % signature_file))
        return HttpResponseRedirect(reverse('tablet:document_list', kwargs={'username': user.username}))
    return render_to_pdf_response(request, 'tablet/signature_render.html', pdf_args)
Ejemplo n.º 18
0
def signature_render(request, username, doc_type, signature_file):
    user = get_object_or_404(User, username=username)
    today = timezone.localtime(timezone.now()).date()
    pdf_args = {'name': user.get_full_name, 'date': today, 'doc_type': doc_type, 'signature_file': signature_file}
    if 'save_file' in request.GET:
        # Save the PDF as a file and redirect them back to the document list
        pdf_data = render_to_pdf('tablet/signature_render.html', pdf_args)
        pdf_file = FileUpload.objects.pdf_from_string(user, pdf_data, doc_type, user)
        os.remove(os.path.join(settings.MEDIA_ROOT, "signatures/%s" % signature_file))
        return HttpResponseRedirect(reverse('tablet_document_list', kwargs={'username': user.username}))
    return render_to_pdf_response(request, 'tablet/signature_render.html', pdf_args)
Ejemplo n.º 19
0
def crear_informe_en_archivo_pdf(ruta, perfil, desde, hasta, aplicacion):
    if aplicacion == 'suite':
        eventos = perfil.obtener_eventos_por_fecha(desde, hasta)
    else:
        eventos = perfil.obtener_eventos_de_robotica_por_fecha(desde, hasta)

    contexto = {
        "perfil": perfil,
        "eventos": eventos,
        "desde": formatear_fecha(desde),
        "hasta": formatear_fecha(hasta),
    }

    if aplicacion == 'suite':
        contenido = render_to_pdf("informe.html", contexto)
    else:
        contenido = render_to_pdf("informe_robotica.html", contexto)

    archivo2 = open(ruta, "w")
    archivo2.write(contenido)
    archivo2.close()
Ejemplo n.º 20
0
def test_render_to_pdf():
        expert_request = ExpertRequest.objects.get(id=11)
        context = {'expert_request': expert_request,
           'pagesize': 'A4',
           'BASE_DIR': BASE_DIR,
        }
        #tor_template = loader.get_template('crppdmt/tor.html')
        #letter_template = loader.get_template('crppdmt/letter_of_request.html')
        tor_pdf = render_to_pdf('crppdmt/pdf/tor.html', context)
        tor_file = open("tor_file.pdf",'w')
        tor_file.write(tor_pdf)
        tor_file.close()
Ejemplo n.º 21
0
def patient_summary_generate_pdf(request, pk, context):
    patient = get_object_or_404(Patient, pk=pk)
    template = get_template('chs/patient_summary_pdf.html')
    html = template.render(context)
    pdf = render_to_pdf('chs/patient_summary_pdf.html', context)
    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'filename= "summary{}.pdf"'.format(
            patient.PatientID)
        #return response
        #return HttpResponse(pdf, content_type='application/octet-stream')
        return pdf
    return HttpResponse("Not Found")
Ejemplo n.º 22
0
def send_booking_mail(context):

    post_pdf = render_to_pdf('hotel/testPDF.html', context)
    global customer

    email_subject = "innOcity Booking Confirmation"
    email_body = "Your booking has been successfully completed . Find your booking pass in the attachment. \n Regrads, \n innOcity Team"

    msg = EmailMultiAlternatives(email_subject, email_body,
                                 settings.EMAIL_HOST_USER, [customer.email])
    msg.attach('Booking Pass.pdf', post_pdf)
    msg.send()
    return
Ejemplo n.º 23
0
 def get(self, request, *args, **kwargs):
     context = self.get_context_data(**kwargs)
     if self.pdf_or_png == "pdf":
         return self.render_to_response(context)
     elif self.pdf_or_png == "png":
         pdf = render_to_pdf("schedule.html", context=context, request=request, **kwargs)
         img = convert_from_bytes(pdf)[0]
         response = HttpResponse(content_type='image/png')
         response['Content-Disposition'] = 'attachment; filename=ITUscheduler'
         img.save(response, "PNG")
         return response
     else:
         return HttpResponseRedirect("/")
Ejemplo n.º 24
0
def generate_pdf(request, pk):
    product = Products.objects.get(id=pk)
    jumia_data = Jumia.objects.filter(product_id=product)
    killmall_data = Killmall.objects.filter(product_id=product)
    avechi_data = Avechi.objects.filter(product_id=product)
    data = {
        'product': product,
        'jumia_data': jumia_data,
        'killmall_data': killmall_data,
        'avechi_data': avechi_data,
        'date': datetime.date.today()
    }
    pdf = render_to_pdf('pdf/contentpage.html', data)
    return HttpResponse(pdf, content_type='application/pdf')
Ejemplo n.º 25
0
    def get(self, request, *args, **kwargs):
        data = {#'today': datetime.date.today(),
         'amount': 39.99,
        'customer_name': 'Cooper Mann',
        'order_id': 1233434,
        'base_url' :'file://' + settings.STATIC_URL + '/',
        'price_s':price,
        'dict':dict_,
        'date':date_today,
        'query':global_query,

        }
        pdf = render_to_pdf('pdf/contentpage.html', data)
        return HttpResponse(pdf, content_type='application/pdf')
Ejemplo n.º 26
0
def imprimircita(request,id_paciente,y,m,d,hora,idmedico):
	fecha=y+"-"+m+"-"+d
	#if request.GET:
	# print id_paciente
	# print  hora
	# print idmedico
	# print fecha
	hoy=date.today()

	cita=Cita.objects.filter(paciente_idpaciente=id_paciente, fecha=fecha, hora_idhora=hora, medico_idmedico=idmedico)
	return render_to_pdf('citas/imprimircita.html',{
	   	'pagesize':'A4',
	   	'title':'Comprobante de cita',
	    'citaprint':cita,'hoy':hoy,
	    })
Ejemplo n.º 27
0
    def get(self, *args, **kwargs):
        #payroll = get_object_or_404(Salary, **kwargs)

        pdf = render_to_pdf(
            'emails/payslip.html',
            {}
        )
        html_content = "<p>payslip is attached</p>"

        msg = EmailMultiAlternatives("Swiftkind Payroll", "payslip is attached", settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'])
        msg.attach_alternative(html_content, "text/html")
        msg.attach('payslip.pdf', pdf, 'application/pdf')
        msg.send()

        return HttpResponse(status=200)
Ejemplo n.º 28
0
def pdf_portfolio(request, pk):
    template = get_template('portfolio/pdf_portfolio.html')
    customer = get_object_or_404(Customer, pk=pk)
    customers = Customer.objects.filter(created_date__lte=timezone.now())
    investments = Investment.objects.filter(customer=pk)
    stocks = Stock.objects.filter(customer=pk)
    mutualfunds = Mutualfund.objects.filter(customer=pk)
    sum_recent_value = Investment.objects.filter(customer=pk).aggregate(
        Sum('recent_value'))
    sum_acquired_value = Investment.objects.filter(customer=pk).aggregate(
        Sum('acquired_value'))
    sum_mutual_acquired_value = Mutualfund.objects.filter(
        customer=pk).aggregate(Sum('acquired_value'))
    sum_mutual_recent_value = Mutualfund.objects.filter(customer=pk).aggregate(
        Sum('recent_value'))
    # overall_investment_results = sum_recent_value-sum_acquired_value
    # Initialize the value of the stocks
    sum_current_stocks_value = 0
    sum_of_initial_stock_value = 0
    for stock in stocks:
        sum_current_stocks_value += stock.current_stock_value()
        sum_of_initial_stock_value += stock.initial_stock_value()
    context = {
        'customers': customers,
        'investments': investments,
        'stocks': stocks,
        'sum_acquired_value': sum_acquired_value,
        'sum_recent_value': sum_recent_value,
        'sum_current_stocks_value': sum_current_stocks_value,
        'sum_of_initial_stock_value': sum_of_initial_stock_value,
        'mutualfunds': mutualfunds,
        'sum_mutual_acquired_value': sum_mutual_acquired_value,
        'sum_mutual_recent_value': sum_mutual_recent_value,
    }
    html = template.render(context)

    # 'email_success': email_success})
    pdf = render_to_pdf('portfolio/pdf_portfolio.html', context)
    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        filename = 'pdf_portfolio_' + str(customer.name) + '.pdf'
        content = "inline; filename='%s'" % (filename)
        download = request.GET.get("download")
        if download:
            content = "attachment; filename='%s'" % (filename)
        response['Content-Disposition'] = content
        return response
    return HttpResponse("not found")
Ejemplo n.º 29
0
 def render(self, data, accepted_media_type=None, renderer_context=None):
     if data.get("geom") is not None:
         geom = json.loads(data["geom"])
         lat, lon = geom["coordinates"]
     else:
         lat = None
         lon = None
     no_data = "-"
     if data.get("details") is not None:
         details = {
             "gender":
             models.Gender.objects.get(code=data["details.gender"]),
             "marks":
             data["details.marks"] or no_data,
             "abnormalities":
             data["details.diseases_and_abnormalities"] or no_data,
         }
     else:
         details = {
             "gender": no_data,
             "marks": no_data,
             "abnormalities": no_data,
         }
     name = data["taxon.name"]
     rank = data["taxon.rank"]
     tsn = data["taxon.tsn"]
     return render_to_pdf(
         "nfdrenderers/pdf/layer_detail.html", {
             "taxon": {
                 "name": name,
                 "rank": rank,
                 "tsn": tsn,
                 "taxonomic_units": self.get_taxonomic_units(tsn),
             },
             "observation": {
                 "observation_date": data["observation.observation_date"],
                 "daytime": data["observation.daytime"] or no_data,
                 "season": data["observation.season"] or no_data,
                 "reporter_name": data["observation.reporter.name"],
                 "reporter_email": data["observation.reporter.email"],
             },
             "details": details,
             "location": {
                 "lat": lat,
                 "lon": lon,
             },
             "images": [im["image"] for im in data["images"]]
         })
Ejemplo n.º 30
0
	def get_context_data ( self, **kwargs ):
		template_name = settings.APP_ROOT + "/templates/base/print_contract.html"
		context = {
			"users"			: {},
			"calendar"		: None,
			"contracts"		: None,
			"contract"		: None,
			"today"			: None,
		}
		pdf = rendering.render_to_pdf( template_name, context, encoding = u'utf-8', **kwargs )

		return super ( self.__class__, self ).get_context_data( 
			pagesize = "A4",
			title = "Hi there",
			**kwargs
		)
Ejemplo n.º 31
0
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        context["query_results"] = self.query_results
        cod = request.GET.get('cod', '')
        logger.debug("cod: " + cod)
        bts = render_to_pdf(self.template_name, context)    
        # rs = { "bts": str(bts.decode('utf-8'))}
        #rs = { "bts": str(bts)}

        # return HttpResponse(str(bts), 
        #                 content_type='application/pdf; charset=utf-8')

        # return HttpResponse(bts, 
        #                 content_type='application/text')

        return HttpResponse(bts, 
                        content_type='application/pdf')
Ejemplo n.º 32
0
def mandarEmail(request, ausencias, fecha, asunto, destinatario, observaciones):
    try:
        mail_destino = []
        mail_destino.append(destinatario)

        try:
            config = configuracion.objects.all().first()
        except configuracion.DoesNotExist:
            raise ValueError

        datos = config.get_datos_mail()
        mensaje_inicial = datos["mensaje_inicial"]
        mail_cuerpo = datos["mail_cuerpo"]
        mail_servidor = datos["mail_servidor"]
        mail_puerto = int(datos["mail_puerto"])
        mail_usuario = datos["mail_usuario"]
        mail_password = str(datos["mail_password"])
        mail_origen = datos["mail_origen"]
        observaciones_finales = observaciones
        context = Context()

        template = "ausentismos/informe_ausentismos.html"
        post_pdf = render_to_pdf(template, locals())

        fecha = fecha
        nombre = "Informe_%s" % fecha

        html_content = get_template("general/email.html").render(
            {"mensaje_inicial": mensaje_inicial, "mail_cuerpo": mail_cuerpo}
        )

        backend = EmailBackend(
            host=mail_servidor, port=mail_puerto, username=mail_usuario, password=mail_password, fail_silently=False
        )
        email = EmailMessage(
            subject="%s" % (asunto), body=html_content, from_email=mail_origen, to=mail_destino, connection=backend
        )
        email.attach("%s.pdf" % nombre, post_pdf, "application/pdf")
        email.content_subtype = "html"
        email.send()
        return True
    except Exception as e:
        print e
        return False
Ejemplo n.º 33
0
def send_slip(request, emp_id, mail, month=1):
    try:
        emp = Employee.objects.get(pk=emp_id)
        main_salary = emp.main_salary
        total_salary = emp.get_tottal_salary(month)
        net_salary = emp.get_net_salary(month)
        total_earnings, total_deductions = emp.get_tottals(month)

        try:
            s1 = EmployeeEarning.objects.filter(date__month=month,
                                                employee=emp)
            s = EmployeeEarningSerializer(s1, many=True)
            earnings = s.data
        except Exception as ex:
            earnings = []

        try:
            d1 = EmployeeDeduction.objects.filter(date__month=month,
                                                  employee=emp)
            d = EmployeeDeductionSerializer(d1, many=True)
            deductions = d.data
        except Exception as ex:
            deductions = []

        data = {
            'main_salary': main_salary,
            'total_salary': total_salary,
            'net_salary': net_salary,
            'total_earnings': total_earnings,
            'total_deductions': total_deductions,
            'earnings': earnings,
            'deductions': deductions
        }
        post_pdf = render_to_pdf('app_wall/slip.html', data)
        msg = EmailMessage("Employee Slip",
                           "this slip for {}".format(emp.get_full_name()),
                           to=[mail])
        msg.attach('file.pdf', post_pdf, 'application/pdf')
        msg.content_subtype = "html"
        msg.send()
        return Response(status.HTTP_200_OK)
    except:
        return Response(status.HTTP_404_NOT_FOUND)
Ejemplo n.º 34
0
    def get(self, request, pk, *args, **kwargs):
        # Render to pdf
        report = ProgressReport.objects.get(id=pk)

        data = dict()

        data['pd'] = report.programme_document

        data['unicef_office'] = report.programme_document.unicef_office
        data['title'] = report.programme_document.title
        data['reference_number'] = report.programme_document.reference_number
        data['start_date'] = report.programme_document.start_date.strftime(
            settings.PRINT_DATA_FORMAT)
        data['end_date'] = report.programme_document.end_date.strftime(
            settings.PRINT_DATA_FORMAT)
        data['cso_contribution'] = report.programme_document.cso_contribution
        data['budget'] = report.programme_document.budget
        data[
            'funds_received_to_date'] = report.programme_document.funds_received_to_date
        data[
            'challenges_in_the_reporting_period'] = report.challenges_in_the_reporting_period
        data['proposed_way_forward'] = report.proposed_way_forward
        data[
            'partner_contribution_to_date'] = report.partner_contribution_to_date
        data['submission_date'] = report.get_submission_date()
        data['reporting_period'] = report.get_reporting_period()

        data['partner'] = report.programme_document.partner

        data[
            'authorized_officer'] = report.programme_document.unicef_officers.first(
            )
        data[
            'focal_point'] = report.programme_document.unicef_focal_point.first(
            )

        data['outputs'] = self.prepare_reportable(
            report.indicator_reports.all().order_by('reportable'))

        pdf = render_to_pdf("report_annex_c_pdf.html", data)
        return HttpResponse(pdf, content_type='application/pdf')
Ejemplo n.º 35
0
def reportgenerator(request):
    # products = list((TrackedProducts.objects.values_list('product_id'),flat=True))
    # # set(ProductOrder.objects.values_list('category', flat=True))
    products_count = []
    products_to_view = []
    products = TrackedProducts.objects.order_by('product_id').values_list(
        'product_id').distinct()[:10]
    # print("products",products)

    for i in products:
        product_coun = TrackedProducts.objects.filter(product_id=i[0]).count()
        product_name_to = Products.objects.get(id=i[0]).product_name
        products_count.append(product_coun)
        products_to_view.append(product_name_to)

    data = {
        'products_count': products_count,
        'products_name': products_to_view
    }
    pdf = render_to_pdf('main/report.html', data)
    return HttpResponse(pdf, content_type='application/pdf')
Ejemplo n.º 36
0
def note2pdf(note: Note):
    template = 'note2pdf.html'
    note.rendered_content = render_markdown(note.content)
    context = {'note': note}
    return render_to_pdf(template, context)