Exemple #1
0
    def create_pdf(request):
        if request._request.GET.get('classe'):
            request._request.GET.pop('classe')
        view_set = CasEleveViewSet.as_view({'get': 'list'})
        results = view_set(request._request).data['results']
        if not results:
            return None

        # Use datetime object instead of plain text.
        for r in results:
            r['datetime_encodage'] = timezone.datetime.strptime(r['datetime_encodage'][:19], "%Y-%m-%dT%H:%M:%S")
            if r['info']:
                continue
            r['datetime_sanction'] = timezone.datetime.strptime(r['datetime_sanction'][:19], "%Y-%m-%dT%H:%M:%S") if r['datetime_sanction'] else None
        student = StudentModel.objects.get(matricule=request.GET['matricule_id'])
        check_student_photo(student)
        #TODO: Should we show current year statistics or all years statistics?
        context = {'statistics': StatisticAPI().gen_stats(request.user, student,
                                                          all_years=False)}
        tenure = ResponsibleModel.objects.filter(tenure=student.classe).first()
        context['tenure'] = tenure.fullname if tenure else "—"

        context['student'] = student
        context['list'] = results
        context['absolute_path'] = settings.BASE_DIR

        t = get_template('dossier_eleve/discip_pdf.rml')
        rml_str = t.render(context)

        pdf = rml2pdf.parseString(rml_str)
        return pdf
Exemple #2
0
    def get(self, request, *args, **kwargs):
        classe_id = kwargs['classe_id']
        try:
            classe = ClasseModel.objects.get(id=classe_id)
        except ObjectDoesNotExist:
            # Class not found
            return render(request, 'dossier_eleve/no_student.html')

        students = StudentModel.objects.filter(classe=classe).order_by(
            'last_name', 'first_name')
        tenures = ResponsibleModel.objects.filter(tenure=classe)
        t = get_template('annuaire/classe_list.rml')
        rml_str = t.render({
            'students': students,
            'students_numb': len(students),
            'classe': classe,
            'tenures': tenures
        })

        pdf = rml2pdf.parseString(rml_str)
        if not pdf:
            return render(request, 'dossier_eleve/no_student.html')
        pdf_name = 'classes_%s_%s%s.pdf' % (classe.teaching.name, classe.year,
                                            classe.letter)

        response = HttpResponse(content_type='application/pdf')
        response[
            'Content-Disposition'] = 'filename; filename="' + pdf_name + '"'
        response.write(pdf.read())
        return response
Exemple #3
0
    def __call__(self):
        request = self.request

        ret = cc.makeRequest(
            '/variable-instance',
            'post', {'processInstanceIdIn': [request.matchdict['processId']]},
            urlParams={'deserializeValues': 'false'})
        if not ret:
            raise HTTPNotFound()

        self.variables = cc.parseVariables(ret)
        ois = self.variables.get('orderItems')
        if ois:
            addItemInfo(ois)

        stream = self.template.generate(variables=self.variables, view=self)
        body = rml2pdf.parseString(stream.render()).read()

        response = Response(
            content_type='application/pdf',
            content_disposition='filename="%s_%s.pdf"' %
            (self.variables['externalOrderId'], request.matchdict['form']),
            content_length=len(body),
            body=body)
        return response
Exemple #4
0
def get_pdf_retenues(request, date=None, date2=None):
    if not date2:
        date2 = date

    rows = filter_and_order(request, column="datetime_sanction", retenues=True,
                            data1=date.replace("-", "/"), data2=date2.replace("-", "/"),
                            order_by="classe")

    retenues = []
    for r in rows:
        dic = model_to_dict(r)
        # student = student_man.get_person(dic['matricule'])
        student = People().get_student_by_id(dic['matricule'])
        dic['classe'] = student.classe.compact_str
        dic['full_name'] = student.fullname
        dic['sanction_decision'] = SanctionDecisionDisciplinaire.objects.get(pk=dic['sanction_decision'])

        retenues.append(dic)

    context = {'date': date, 'list': retenues}
    t = get_template('dossier_eleve/discip_retenues.rml')
    rml_str = t.render(context)

    pdf = rml2pdf.parseString(rml_str)
    if not pdf:
        return render(request, 'dossier_eleve/no_student.html')
    pdf_name = 'retenues_' + date + '.pdf'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename; filename="' + pdf_name + '"'
    response.write(pdf.read())
    return response
Exemple #5
0
    def __call__(self):
        assert 'orders' in self.request.params
        oids = self.request.params['orders'].split(',')
        assert oids

        labels = []
        for oid in oids:
            ret = cc.makeRequest('/process-instance',
                                 'post', {'businessKey': oid},
                                 withProcessVariables=(
                                     'orderId',
                                     'externalOrderId',
                                     'factoryNumber',
                                     'customerName',
                                     'customerRegionCode',
                                 ),
                                 processInstanceIdField='id',
                                 hoistProcessVariables=True)
            pkgId = ret[0]['pkgId'] = shortuuid.uuid()
            ret[0]['labelUrl'] = f'{self.request.host_url}/ikea/shipOrder?' \
                f'orderId={oid}&pkgId={pkgId}'
            labels.append(ret[0])

        loader = TemplateLoader([os.path.dirname(__file__)])
        template = loader.load('shippingLabel.rml')
        stream = template.generate(labels=labels, view=self)
        body = rml2pdf.parseString(stream.render()).read()

        response = Response(content_type='application/pdf',
                            content_disposition='filename="labels.pdf"',
                            content_length=len(body),
                            body=body)
        return response
Exemple #6
0
 def _render(self, aggregated, configuration, locale, language, **kwargs):
     template_name = configuration["template"]
     template = self.environment.get_template(template_name)
     rendered = template.render(aggregated=aggregated,
                                locale=locale, language=language, font_dir=self.template_dir,
                                **kwargs)
     return parseString(rendered).getvalue()
Exemple #7
0
 def handle_button_form_send_clicked(self):
   
   rmlText = self.rep_template.get(str(self.combo_zone.currentText())+' - '+
                                   str(self.combo_sensor.currentText()),
                                   datetime.datetime.now().strftime("%Y-%m-%d"),
                                   str(self.edit_requester_name.text()),
                                   str(self.edit_requester_addr.toPlainText()),
                                   str(self.edit_requester_mail.text()),
                                   str(self.edit_expert_name.text()),
                                   str(self.edit_expert_addr.toPlainText()),
                                   str(self.edit_expert_mail.text()),
                                   str(self.edit_observations.toPlainText()),
                                   self.cosmos_cli.local_filepath+'/plot.png')
   pdf = rml2pdf.parseString(rmlText)
   
   with open(self.cosmos_cli.local_filepath+'/rmlReport.pdf', 'w+') as pdfFile:
     pdfFile.write(pdf.read())
   
   time.sleep(1)
   
   (password, ok) = QInputDialog().getText(self, 'password', 'password', mode=QLineEdit.Password)
   
   print str(self.edit_requester_mail.text())
   print str(password)
   
   email_cli = EmailClient(username = str(self.edit_requester_mail.text()),
                           password = str(password))
   
   email_cli.sendEmail(from_addr=str(self.edit_requester_mail.text()),
                       to_addr=str(self.edit_expert_mail.text()),
                       mail_subject='[FRESH Expert Service] Request for Advice',
                       mail_body=str(self.edit_observations.toPlainText()),
                       attachment=self.cosmos_cli.local_filepath+'/rmlReport.pdf')
Exemple #8
0
def create_pdf(student, all_year, infos, sanctions):
    cas = None
    if int(all_year):
        cas = CasEleve.objects.filter(Q(matricule=student) &
                                      (Q(sanction_faite__isnull=True) | Q(sanction_faite=True)))
    else:
        current_scholar_year = get_scolar_year()
        limit_date = timezone.make_aware(timezone.datetime(current_scholar_year, 8, 15))
        cas = CasEleve.objects.filter(matricule=student, datetime_encodage__gte=limit_date)
        cas = cas.filter(Q(sanction_faite__isnull=True) | Q(sanction_faite=True))
    if infos == "0":
        cas = cas.filter(sanction_decision__isnull=False)
    if sanctions == "0":
        cas = cas.filter(info__isnull=False)

    if not cas:
        return None

    context = gen_stats(student)
    tenure = ResponsibleModel.objects.filter(tenure=student.classe).first()
    # tenure = teacher_man.get_people(filters=['tenure=' + student.classe])[0]
    context['tenure'] = tenure.fullname

    context['student'] = student
    context['list'] = cas
    context['absolute_path'] = settings.BASE_DIR

    t = get_template('dossier_eleve/discip_pdf.rml')
    rml_str = t.render(context)

    pdf = rml2pdf.parseString(rml_str)
    return pdf
Exemple #9
0
    def get(self, request, pk):
        invoice = get_object_or_404(models.Invoice, pk=pk)
        object = invoice.event
        template = get_template('RIGS/event_print.xml')
        copies = ('TEC', 'Client')
        context = RequestContext(request, {
            'object': object,
            'fonts': {
                'opensans': {
                    'regular': 'RIGS/static/fonts/OPENSANS-REGULAR.TTF',
                    'bold': 'RIGS/static/fonts/OPENSANS-BOLD.TTF',
                }
            },
            'invoice': invoice,
            'current_user': request.user,
        })

        rml = template.render(context)
        buffer = StringIO.StringIO()

        buffer = rml2pdf.parseString(rml)

        pdfData = buffer.read()

        escapedEventName = re.sub('[^a-zA-Z0-9 \n\.]', '', object.name)

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = "filename=Invoice %05d | %s.pdf" % (invoice.pk, escapedEventName)
        response.write(pdfData)
        return response
Exemple #10
0
    def get(self, request, pk):
        invoice = get_object_or_404(models.Invoice, pk=pk)
        object = invoice.event
        template = get_template('RIGS/event_print.xml')

        context = {
            'object': object,
            'fonts': {
                'opensans': {
                    'regular': 'RIGS/static/fonts/OPENSANS-REGULAR.TTF',
                    'bold': 'RIGS/static/fonts/OPENSANS-BOLD.TTF',
                }
            },
            'invoice': invoice,
            'current_user': request.user,
        }

        rml = template.render(context)

        buffer = rml2pdf.parseString(rml)

        pdfData = buffer.read()

        escapedEventName = re.sub('[^a-zA-Z0-9 \n\.]', '', object.name)

        response = HttpResponse(content_type='application/pdf')
        response[
            'Content-Disposition'] = "filename=Invoice %05d - N%05d | %s.pdf" % (
                invoice.pk, invoice.event.pk, escapedEventName)
        response.write(pdfData)
        return response
Exemple #11
0
def get_pdf_council(request, date_from=None, date_to=None):
    rows = filter_and_order(request, only_actives=True, retenues=False,
                            column='datetime_council', data1=date_from.replace("-", "/"), data2=date_to.replace("-", "/"),
                            order_by='classe')

    discip_council = []
    for r in rows:
        dic = model_to_dict(r)
        # student = student_man.get_person(dic['matricule'])
        student = People().get_student_by_id(dic['matricule'])
        dic['classe'] = student.classe.compact_str
        dic['full_name'] = student.fullname
        dic['sanction_decision'] = SanctionDecisionDisciplinaire.objects.get(pk=dic['sanction_decision'])

        discip_council.append(dic)

    context = {'date_from': date_from, 'date_to': date_to,
               'list': discip_council}
    t = get_template('dossier_eleve/discip_council.rml')
    rml_str = t.render(context)

    pdf = rml2pdf.parseString(rml_str)
    if not pdf:
        return render(request, 'dossier_eleve/no_student.html')
    pdf_name = 'council_' + date_from + '_' + date_to + '.pdf'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename; filename="' + pdf_name + '"'
    response.write(pdf.read())
    return response
    def get(self, request, pk):
        invoice = get_object_or_404(models.Invoice, pk=pk)
        user = self.request.user

        if invoice.user != user:
            raise PermissionDenied()

        if user.username == 'harry':
            logo_path = 'hb-invoice-logo.png'
        else:
            logo_path = 'default-logo.png'

        template = get_template('invoice_print.xml')

        def generate_invoice_info():
            info = list()

            info.append('DATE   {}'.format(invoice.created.date()))
            info.append('INVOICE NO.   {}'.format(invoice.invoice_number()))

            if invoice.utr:
                info.append('UTR NO.   {}'.format(invoice.user.utr))

            if invoice.po_number:
                info.append('PO NO.   {}'.format(invoice.po_number))

            return info

        context = {
            'invoice': invoice,
            'user': user,
            'fonts': {
                'roboto': {
                    'regular': 'invoice/static/fonts/roboto/Roboto-Light.ttf',
                    'bold': 'invoice/static/fonts/roboto/Roboto-Regular.ttf',
                }
            },
            'logo': 'invoice/static/imgs/paperwork/{}'.format(logo_path),
            'invoice_info': generate_invoice_info()
        }

        rml = template.render(context)

        buf = rml2pdf.parseString(rml)

        response = HttpResponse(content_type='application/pdf')

        if invoice.user_invoice_number:
            invoice_number = invoice.user_invoice_number
        else:
            invoice_number = 'N%04d' % invoice.pk

        response['Content-Disposition'] = "filename={}_{}.pdf".format(
            invoice_number,
            str(invoice.company).replace(',', ' '))
        # response['Content-Disposition'] = 'filename=test.pdf'
        response.write(buf.read())
        return response
Exemple #13
0
 def renderToFile(self):
     filename = _quoteUrl(self.filename)
     if not pdf.isEnabled():
         return filename, None
     filename = _quoteUrl(self.filename)
     xml = self.template()
     stream = rml2pdf.parseString(xml, filename=filename)
     data = stream.getvalue()
     return filename, data
Exemple #14
0
 def renderToFile(self):
     filename = _quoteUrl(self.filename)
     if not pdf.isEnabled():
         return filename, None
     filename = _quoteUrl(self.filename)
     xml = self.template()
     stream = rml2pdf.parseString(xml, filename=filename)
     data = stream.getvalue()
     return filename, data
Exemple #15
0
def rml_to_pdf(rml_string, embed_logo=True):
    pdf_fp = rml2pdf.parseString(rml_string)

    if embed_logo:
        cur_dirname = os.path.dirname(__file__)
        logo_pdf = os.path.abspath(os.path.join(cur_dirname,
                                                "Logo auf A4.pdf"))
        logo_template_fp = file(logo_pdf, "rb")
        pdf_fp = perform_logo_embedding(pdf_fp, logo_template_fp)
    return pdf_fp
Exemple #16
0
def objectives_pdf_view(context, request):

    project = context.__parent__     

    result =  render_template('templates/objectives_pdf.pt',
               api=TemplateAPI(request),
               project = project)
     
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type =  "application/pdf"
    return response
Exemple #17
0
def objectives_pdf_view(context, request):

    project = context.__parent__

    result = render_template('templates/objectives_pdf.pt',
                             api=TemplateAPI(request),
                             project=project)

    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type = "application/pdf"
    return response
Exemple #18
0
def render_rml(data,card_no,request=None):

    # t = get_template('bingocard.xml')
    # c = RequestContext(request,{'data':data})
    # rml = t.render(c)
    rml = render_to_string('bingocard.xml',{'data':data,'static':settings.STATIC_ROOT})
    try:
        pdf = rml2pdf.parseString(rml)
    except Exception,e:
        print "Error %s" % e
        return False
Exemple #19
0
    def parse(self, xml, filename):
        print(pineboolib.project._DGI.isDeployed())
        if not pineboolib.project._DGI.isDeployed():
            from z3c.rml import document, rml2pdf
        else:
            return

        res_ = rml2pdf.parseString(xml).read()
        with open(filename, 'wb') as w:
            w.write(res_)

        w.close()
Exemple #20
0
    def parse(self, xml, filename):
        print(pineboolib.project._DGI.isDeployed())
        if not pineboolib.project._DGI.isDeployed():
            from z3c.rml import document, rml2pdf
        else:
            return

        res_ = rml2pdf.parseString(xml).read()
        with open(filename, 'wb') as w:
            w.write(res_)

        w.close()
	def crear_reporte(cls, invoice):

		#import pudb;pu.db
		
		if invoice.invoice_type.invoice_type == '1': #Factura A
			datos = report_creator.crear_data_factura_a(invoice)
			rml_text = template_fac_a.get(*datos)
			out = rml2pdf.parseString(rml_text)
			return out.read()
		elif invoice.invoice_type.invoice_type == '6':  #Factura B
		#elif invoice.invoice_type.id == 18:  #Factura B
			datos = report_creator.crear_data_factura_b(invoice)
			rml_text = template_fac_b.get(*datos)
			out = rml2pdf.parseString(rml_text)
			return out.read()
		elif invoice.invoice_type.invoice_type == '3': #Nota de Credito A
			datos = report_creator.crear_data_nota_credito_a(invoice)
			rml_text = template_nota_credito_a.get(*datos)
			out = rml2pdf.parseString(rml_text)
			return out.read()
		elif invoice.invoice_type.invoice_type == '8':  #Nota de Credito B
			datos = report_creator.crear_data_nota_credito_b(invoice)
			rml_text = template_nota_credito_b.get(*datos)
			out = rml2pdf.parseString(rml_text)
			return out.read()
		elif invoice.invoice_type.invoice_type == '2':  #Nota de Debito A
			datos = report_creator.crear_data_nota_debito_a(invoice)
			rml_text = template_nota_debito_a.get(*datos)
			out = rml2pdf.parseString(rml_text)
			return out.read()
		elif invoice.invoice_type.invoice_type == '7':  #Nota de Debito B
			datos = report_creator.crear_data_nota_debito_b(invoice)
			rml_text = template_nota_debito_b.get(*datos)
			out = rml2pdf.parseString(rml_text)
			return out.read()
Exemple #22
0
def render_to_pdf(template_name, dictionary=None, context_instance=None):

    # Sobreescribir la ruta de los archivos estáticos para que la ruta sea local
    STATIC_URL = getattr(settings, 'PDF_STATIC_URL', None)
    if STATIC_URL:
        if dictionary is None:
            dictionary = {}
        dictionary['STATIC_URL'] = STATIC_URL
    
    # Renderizar la plantilla RML y convertir el contenido a PDF
    rml = loader.render_to_string(template_name, dictionary=dictionary,
        context_instance=context_instance)
    return rml2pdf.parseString(rml)
Exemple #23
0
def main(argv):
    # Load the rml template into the preprocessor, ...
    template = preppy.getModule('reportTemplate.prep')
        
    # ... and do the preprocessing.
    #{{def(sensor, date, requester_name, requester_address, requester_contact, expert_name, expert_address, expert_contact, observations, plot)}}
    rmlText = template.get("Sensor 1", datetime.datetime.now().strftime("%Y-%m-%d"), "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA")
    
    # Finally generate the *.pdf output ...
    pdf = rml2pdf.parseString(rmlText)
    
    # ... and save it.
    with open('rmlReport.pdf', 'w') as pdfFile:
        pdfFile.write(pdf.read())
Exemple #24
0
    def render(self):
        # Do preprocessing.
        logger.info('Rendering template.')
        rml_text = self._template.render(self._data)
        rml_text = rml_text.strip()
        logger.info('Rendered template.')

        # Generate PDF output.
        logger.info('Generating PDF document.')
        pdf = rml2pdf.parseString(rml_text)
        logger.info('Generated PDF document.')

        self._pdf = pdf
        return self._pdf
Exemple #25
0
    def render(self):
        # Do preprocessing.
        logger.info('Rendering template.')
        rml_text = self._template.render(self._data)
        rml_text = rml_text.strip()
        logger.info('Rendered template.')

        # Generate PDF output.
        logger.info('Generating PDF document.')
        pdf = rml2pdf.parseString(rml_text)
        logger.info('Generated PDF document.')

        self._pdf = pdf
        return self._pdf
Exemple #26
0
def open_rml_pdf(tpl_filename, **kwargs):
    pdf_filename = tpl_filename+'.pdf'
    
    f = open(rpt_path+tpl_filename)
    rml = f.read()
    f.close()
    params = {}
    
    for key, value in kwargs.iteritems():
        params[key] = value

    rml = rml.format(waktu=waktu(), **kwargs)
    pdf = rml2pdf.parseString(rml)
    return pdf, pdf_filename
def open_rml_pdf(tpl_filename, **kwargs):
    pdf_filename = tpl_filename+'.pdf'
    
    f = open(rpt_path+tpl_filename)
    rml = f.read()
    f.close()
    params = {}
    
    for key, value in kwargs.iteritems():
        #if key == "logo":
        #    value = rpt_path+"/pajak/static/img/logo.png"
        params[key] = value

    rml = rml.format(waktu=waktu(), **kwargs)
    pdf = rml2pdf.parseString(rml)
    return pdf, pdf_filename
Exemple #28
0
 def renderPDF(self, xml):
     filename = self.filename
     stream = rml2pdf.parseString(xml, filename=filename or None)
     data = stream.getvalue()
     response = self.request.response
     response.setHeader("Content-Type", "application/pdf")
     response.setHeader("Content-Length", len(data))
     # We don't really accept ranges, but Acrobat Reader will not show the
     # report in the browser page if this header is not provided.
     response.setHeader("Accept-Ranges", "bytes")
     disposition = self.inline and "inline" or "attachment"
     quoted_filename = quoteFilename(filename)
     if quoted_filename:
         disposition += '; filename="%s"' % quoted_filename
     response.setHeader("Content-Disposition", disposition)
     return data
Exemple #29
0
 def renderPDF(self, xml):
     filename = self.filename
     stream = rml2pdf.parseString(xml, filename=filename or None)
     data = stream.getvalue()
     response = self.request.response
     response.setHeader('Content-Type', 'application/pdf')
     response.setHeader('Content-Length', len(data))
     # We don't really accept ranges, but Acrobat Reader will not show the
     # report in the browser page if this header is not provided.
     response.setHeader('Accept-Ranges', 'bytes')
     disposition = self.inline and 'inline' or 'attachment'
     quoted_filename = quoteFilename(filename)
     if quoted_filename:
         disposition += '; filename="%s"' % quoted_filename
     response.setHeader('Content-Disposition', disposition)
     return data
Exemple #30
0
    def get(self, request, *args, **kwargs):
        classe_id = kwargs['classe_id']
        try:
            classe = ClasseModel.objects.get(id=classe_id)
        except ObjectDoesNotExist:
            return render(request, 'dossier_eleve/no_student.html')
        students = StudentModel.objects.filter(classe=classe)

        students = sorted(students,
                          key=lambda s: unidecode(s.last_name.lower()))
        rows = []
        student_by_row = 6
        row = []
        for i, student in enumerate(students):
            check_student_photo(student)
            if i % student_by_row == 0:
                row = []
            row.append(student)
            if i % student_by_row == student_by_row - 1 or len(
                    students) == i + 1:
                rows.append(row)

        context = {
            'classe': classe.compact_str,
            'list': rows,
            'students_numb': len(students)
        }

        tenures = ResponsibleModel.objects.filter(tenure=classe)

        context['tenures'] = tenures

        context['absolute_path'] = settings.BASE_DIR
        t = get_template('annuaire/classe.rml')
        rml_str = t.render(context)

        pdf = rml2pdf.parseString(rml_str)
        if not pdf:
            return render(request, 'dossier_eleve/no_student.html')
        pdf_name = 'classes_%s%s.pdf' % (classe.year, classe.letter)

        response = HttpResponse(content_type='application/pdf')
        response[
            'Content-Disposition'] = 'filename; filename="' + pdf_name + '"'
        response.write(pdf.read())
        return response
Exemple #31
0
    def __call__(self):
        key = self.request.matchdict['key']
        if key == 'current':
            today = date.today()
            self.startDate = today - timedelta(today.isocalendar()[2] + 6)
        else:
            assert len(key) == 6 and key.isnumeric()
            year, week = int(key[:4]), int(key[4:])
            assert week <= 52 and year >= 2018 and year <= 2050
            self.startDate = Week(year, week).monday()

        self.endDate = self.startDate + timedelta(6)
        cal = self.startDate.isocalendar()
        self.docKey = f'{cal[0]}/{cal[1]}'

        self.orders = self.sess.query(SalesOrder).\
            filter_by(orderSource=ORDER_SOURCE.IKEA).\
            filter_by(orderStatus=ORDER_STATUS.COMPLETED).\
            filter(SalesOrder.completionDate >= self.startDate).\
            filter(SalesOrder.completionDate < self.endDate + timedelta(1)).\
            all()
        self.total = sum([o.amount for o in self.orders])

        for o in self.orders:
            ret = cc.makeRequest(
                '/history/process-instance', 'post',
                {'processInstanceBusinessKey': o.orderId},
                withProcessVariables=('storeId', ),
                processInstanceIdField='id', hoistProcessVariables=True
            )[0]
            o.storeId = ret['storeId']

        self.orders.sort(key=lambda o: (o.storeId, o.orderId))

        loader = TemplateLoader([os.path.dirname(__file__)])
        template = loader.load('receivable.pt')
        stream = template.generate(view=self)
        body = rml2pdf.parseString(stream.render()).read()

        response = Response(
            content_type='application/pdf',
            content_disposition=f'filename="AR{self.docKey}.pdf"',
            content_length=len(body),
            body=body)
        return response
Exemple #32
0
    def get(self, request, pk):
        object = get_object_or_404(models.Event, pk=pk)
        template = get_template('RIGS/event_print.xml')
        copies = ('TEC', 'Client')

        merger = PdfFileMerger()

        for copy in copies:

            context = RequestContext(request, { # this should be outside the loop, but bug in 1.8.2 prevents this
                'object': object,
                'fonts': {
                    'opensans': {
                        'regular': 'RIGS/static/fonts/OPENSANS-REGULAR.TTF',
                        'bold': 'RIGS/static/fonts/OPENSANS-BOLD.TTF',
                    }
                },
                'copy':copy,
                'current_user':request.user,
            })

            # context['copy'] = copy # this is the way to do it once we upgrade to Django 1.8.3

            rml = template.render(context)
            buffer = StringIO.StringIO()

            buffer = rml2pdf.parseString(rml)

            merger.append(PdfFileReader(buffer))

            buffer.close()

        terms = urllib2.urlopen(settings.TERMS_OF_HIRE_URL)
        merger.append(StringIO.StringIO(terms.read()))

        merged = BytesIO()
        merger.write(merged)

        response = HttpResponse(content_type='application/pdf')

        escapedEventName = re.sub('[^a-zA-Z0-9 \n\.]', '', object.name)

        response['Content-Disposition'] = "filename=N%05d | %s.pdf" % (object.pk, escapedEventName)
        response.write(merged.getvalue())
        return response
Exemple #33
0
def student_application_pdf_view(context, request):
    
    data = gained_competences(context)
    
    show_projects = request.GET.get('show_projects', False)
    show_journal = request.GET.get('show_journal', False)
    show_indcators = request.GET.get('show_indcators', False)
    
    result = render_template('templates/student_application_pdf.pt',
                             api=TemplateAPI(request),
                             student = context,
                             show_projects = show_projects,
                             show_journal = show_journal,
                             show_indcators = show_indcators,
                             data=data)
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type =  "application/pdf"
    return response
Exemple #34
0
def main(argv):
    # Load the rml template into the preprocessor, ...
    template = preppy.getModule('testDoc.prep')

    # ... fetch the table data ...
    table = fetchTable()

    # ... and do the preprocessing.
    rmlText = template.get(
        datetime.datetime.now().strftime("%Y-%m-%d"), 'Andreas Wilhelm',
        'www.avedo.net', '*****@*****.**', table)

    # Finally generate the *.pdf output ...
    pdf = rml2pdf.parseString(rmlText)

    # ... and save it.
    with open('rmlReport.pdf', 'w') as pdfFile:
        pdfFile.write(pdf.read())
Exemple #35
0
def student_application_pdf_view(context, request):

    data = gained_competences(context)

    show_projects = request.GET.get('show_projects', False)
    show_journal = request.GET.get('show_journal', False)
    show_indcators = request.GET.get('show_indcators', False)

    result = render_template('templates/student_application_pdf.pt',
                             api=TemplateAPI(request),
                             student=context,
                             show_projects=show_projects,
                             show_journal=show_journal,
                             show_indcators=show_indcators,
                             data=data)
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type = "application/pdf"
    return response
Exemple #36
0
def get_class_photo_pdf(request, year, classe, enseignement):
    students = StudentModel.objects.filter(classe__year=year,
                                           classe__letter=classe,
                                           classe__teaching__name=enseignement)

    students = sorted(students, key=lambda s: unidecode(s.last_name.lower()))
    rows = []
    student_by_row = 6
    row = []
    for i, student in enumerate(students):
        if i % student_by_row == 0:
            row = []
        row.append(student)
        if i % student_by_row == student_by_row - 1 or len(students) == i + 1:
            rows.append(row)

    context = {
        'classe': str(year) + classe,
        'list': rows,
        'students_numb': len(students)
    }

    # teaching = TeachingModel.objects.get(name=enseignement)
    classe = ClasseModel.objects.get(year=year,
                                     letter=classe,
                                     teaching__name=enseignement)
    tenures = ResponsibleModel.objects.filter(tenure=classe)
    # tenures = teacher_man.get_people(enseignement=enseignement,
    # filters=['tenure=%s%s' % (year, classe)])
    context['tenures'] = tenures

    context['absolute_path'] = settings.BASE_DIR
    t = get_template('annuaire/classe.rml')
    rml_str = t.render(context)

    pdf = rml2pdf.parseString(rml_str)
    if not pdf:
        return render(request, 'dossier_eleve/no_student.html')
    pdf_name = 'classes_%s%s.pdf' % (year, classe)

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename; filename="' + pdf_name + '"'
    response.write(pdf.read())
    return response
def view_invoice_pdf(request):
    session = DBSession()
    company = session.query(Company).first()
    
    invoice_id = request.matchdict['invoice']
    invoice = session.query(Invoice).filter_by(id=invoice_id).first()
    if not invoice:
        return Response(status=404)
    
    rml_template = 'templates/rml/' + company.invoice_template
        
    # Only jpeg without PIL
    logo_path = os.path.join(os.path.dirname(__file__), 'templates', 'static', 'uploads', 'logo.jpg')
        
    result = render_template(rml_template, invoice=invoice, logo_path=logo_path,
                             formatThousands=formatThousands)
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type =  "application/pdf"
    return response
Exemple #38
0
    def render(self):
        self.request.response.setHeader('content-type', 'application/pdf')
        #rmlPageTemplate = pagetemplate.RMLPageTemplateFile('casexit_templates/pdf.pt')
        #return rmlPageTemplate(
        #    Title=(self.context.Title()))
        rml_doc = ViewPageTemplateFile('casexit_templates/pdf.pt')(self)

        return parseString(rml_doc.encode('utf-8')).read()


    # def render(self):
    #     """Returns PDF as a binary stream."""
    #     # Use your favourite templating language here to create the RML string.
    #     # The generated document might depend on the web request parameters,
    #     # database lookups and so on - we'll leave that up to you.
    #     rml = getRML(request)
    #     buf = cStringIO.StringIO()
    #     rml2pdf.go(rml, outputFileName=buf)
    #     buf.reset()
    #     pdfData = buf.read()
    #     response = HttpResponse(mimetype='application/pdf')
Exemple #39
0
    def get(self, request, format=None):
        view_set = AskSanctionsViewSet.as_view({'get': 'list'})
        results = view_set(request._request).data['results']
        results = self.modify_entries(results)

        date_from = request.GET.get('datetime_%s__gt' % self.field_date)
        date_to = request.GET.get('datetime_%s__lt' % self.field_date)
        context = {'date_from': date_from, 'date_to': date_to, 'list': results}
        t = get_template(self.template)
        rml_str = t.render(context)

        pdf = rml2pdf.parseString(rml_str)
        if not pdf:
            return render(request, 'dossier_eleve/no_student.html')
        pdf_name = self.file_name + '_' + date_from + '_' + date_to + '.pdf'

        response = HttpResponse(content_type='application/pdf')
        response[
            'Content-Disposition'] = 'filename; filename="' + pdf_name + '"'
        response.write(pdf.read())
        return response
Exemple #40
0
  def handle_button_form_save_clicked(self):
 
    rmlText = self.rep_template.get(str(self.combo_zone.currentText())+' - '+
                                    str(self.combo_sensor.currentText()),
                                    datetime.datetime.now().strftime("%Y-%m-%d"),
                                    str(self.edit_requester_name.text()),
                                    str(self.edit_requester_addr.toPlainText()),
                                    '',
                                    str(self.edit_expert_name.text()),
                                    str(self.edit_expert_addr.toPlainText()),
                                    '',
                                    str(self.edit_observations.toPlainText()),
                                    self.cosmos_cli.local_filepath+'/plot.png')
    pdf = rml2pdf.parseString(rmlText)
    
    filename = QFileDialog().getSaveFileName()
    
    if str(filename == ''): return
    
    with open(str(filename), 'w+') as pdfFile:
      pdfFile.write(pdf.read())
def view_invoice_pdf(request):
    session = DBSession()
    company = session.query(Company).first()

    invoice_id = request.matchdict['invoice']
    invoice = session.query(Invoice).filter_by(id=invoice_id).first()
    if not invoice:
        return Response(status=404)

    rml_template = 'templates/rml/' + company.invoice_template

    # Only jpeg without PIL
    logo_path = os.path.join(os.path.dirname(__file__), 'templates', 'static',
                             'uploads', 'logo.jpg')

    result = render_template(rml_template,
                             invoice=invoice,
                             logo_path=logo_path,
                             formatThousands=formatThousands)
    response = Response(parseString(result.encode('utf-8')).read())
    response.content_type = "application/pdf"
    return response
Exemple #42
0
    def get(self, request, pk):
        object = get_object_or_404(models.Event, pk=pk)
        template = get_template('RIGS/event_print.xml')

        merger = PdfFileMerger()

        context = {
            'object': object,
            'fonts': {
                'opensans': {
                    'regular': 'RIGS/static/fonts/OPENSANS-REGULAR.TTF',
                    'bold': 'RIGS/static/fonts/OPENSANS-BOLD.TTF',
                }
            },
            'quote': True,
            'current_user': request.user,
        }

        rml = template.render(context)

        buffer = rml2pdf.parseString(rml)
        merger.append(PdfFileReader(buffer))
        buffer.close()

        terms = urllib.request.urlopen(settings.TERMS_OF_HIRE_URL)
        merger.append(BytesIO(terms.read()))

        merged = BytesIO()
        merger.write(merged)

        response = HttpResponse(content_type='application/pdf')

        escapedEventName = re.sub('[^a-zA-Z0-9 \n\.]', '', object.name)

        response['Content-Disposition'] = "filename=N%05d | %s.pdf" % (
            object.pk, escapedEventName)
        response.write(merged.getvalue())
        return response
Exemple #43
0
def get_pdf(request, file_type=None, partner_id=None, taxpayer_id=None, uuid=None, template_name='template.rml', context={}):
    from django.template.loader import render_to_string
    from z3c.rml import rml2pdf
    from django.http import HttpResponse
    from django.utils.http import http_date
    import time
    import StringIO
    resp = StringIO.StringIO()
    contract = get_object_or_404(Contract, uuid=uuid)
    path = '%s/%s/%s/' % (settings.AGR_STORAGE_PATH, contract.partner_uuid, contract.taxpayer_id)
    load_xml_from_ = '%s/%s_%s.xml' % (path, file_type, contract.id)
    f = open(load_xml_from_)
    xml_loaded = f.read()
    f.close()

    xml_signed = etree.parse(StringIO.StringIO(xml_loaded))
    manifest, signature, cert = utilities.get_text_from_seal(xml_signed.getroot())
    if file_type == 'privacy_notice_file':
        template_name = "template_privacy.rml"
    rml = render_to_string(template_name, {
        'manifest': manifest,
        'signature': signature,
        'contract': contract,
        'finkok_legal_person': settings.FINKOK_LEGAL_PERSON,
        'finkok_taxpayer_id': settings.FINKOK_TAXPAYER_ID,
        'finkok_address': settings.FINKOK_ADDRESS,
        'finkok_url': settings.FINKOK_URL,
        'finkok_email': settings.FINKOK_MAIL,
        }).encode('utf8')
    filename = "%s_%s.pdf" % (file_type, contract.taxpayer_id)
    #creates the pdf
    resp = rml2pdf.parseString(rml, filename=filename)
    response = HttpResponse(resp, mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s' % (filename)
    response["Last-Modified"] = http_date(int(time.mktime(timezone.now().timetuple())))

    return response
Exemple #44
0
def render_rml(data,card_no,request=None):

    # t = get_template('bingocard.xml')
    # c = RequestContext(request,{'data':data})
    # rml = t.render(c)
    templateLoader = jinja2.FileSystemLoader(searchpath="./")
    templateEnv = jinja2.Environment(loader=templateLoader)
    TEMPLATE_FILE = "static/tpl/bingocard.xml"
    template = templateEnv.get_template(TEMPLATE_FILE)
    rml = template.render(data=data,static=STATIC_ROOT)
    try:
        pdf = rml2pdf.parseString(rml)
    except Exception as e:
        print("Error %s" % e)
        return False


    # Save PDF to file and store
    filename = "bingocard_%s.pdf" % card_no
    pdf_filename = os.path.join(STATIC_ROOT,'cards',filename)
    # ... and save it.
    with open(pdf_filename, 'wb') as pdfFile:
       pdfFile.write(pdf.read())
    return True
 def __call__(self):
     self.request.response.setHeader('content-type', 'application/pdf')
     rml_doc = ViewPageTemplateFile('print_survey.pt')(self)
     return parseString(rml_doc.encode('utf-8')).read()
Exemple #46
0
reportlab.rl_config.warnOnMissingFontGlyphs = 0

font_dir = os.path.join(os.path.dirname(__file__), 'fonts')

# add necessary fonts
pdfmetrics.registerFont(TTFont('DejaVuSans',
    os.path.join(font_dir, 'DejaVuSans.ttf'), 'UTF-8'))
pdfmetrics.registerFont(TTFont('DejaVuSans-Bold',
    os.path.join(font_dir, 'DejaVuSans-Bold.ttf'), 'UTF-8'))
pdfmetrics.registerFont(TTFont('DejaVuSans-Oblique',
    os.path.join(font_dir, 'DejaVuSans-Oblique.ttf'), 'UTF-8'))
pdfmetrics.registerFont(TTFont('DejaVuSans-BoldOblique',
    os.path.join(font_dir, 'DejaVuSans-BoldOblique.ttf'), 'UTF-8'))

# and map them
addMapping('DejaVuSans', 0, 0, 'DejaVuSans')
addMapping('DejaVuSans-Bold', 1, 0, 'DejaVuSans')
addMapping('DejaVuSans-Oblique', 0, 1, 'DejaVuSans')
addMapping('DejaVuSans-BoldOblique', 1, 1, 'DejaVuSans')



with open('example.rml') as rml:
    data = rml.read()


pdf = rml2pdf.parseString(data.decode('utf-8'))

with open('example.pdf', 'w') as output:
    output.write(pdf.read())
Exemple #47
0
 def __call__(self):
     rml = self.template(self).encode(self.encoding)
     self.request.response.setHeader('content-type', 'application/pdf')
     return rml2pdf.parseString(rml).read()
Exemple #48
0
 def renderReport(self, renderer, stream, *args, **kw):
     renderer.update()
     rml = renderer.render()
     filename = renderer.filename
     pdf = rml2pdf.parseString(rml, filename=filename or None)
     stream.write(pdf.getvalue())
 def __call__(self):
     self.request.response.setHeader("content-type", "application/pdf")
     rml_doc = ViewPageTemplateFile("print_survey.pt")(self)
     return parseString(rml_doc.encode("utf-8")).read()
Exemple #50
0
 def renderReport(self, renderer, stream, *args, **kw):
     renderer.update()
     rml = renderer.render()
     filename = renderer.filename
     pdf = rml2pdf.parseString(rml, filename=filename or None)
     stream.write(pdf.getvalue())
 def __call__(self):
     self.request.response.setHeader('content-type', 'application/pdf')
     rml_doc = ViewPageTemplateFile('print_survey.pt')(self)
     return parseString(rml_doc.encode('utf-8')).read()
Exemple #52
0
row_tpl_filename = 'row.rml.tpl'

if sys.argv[1:]:
    pdf_filename = sys.argv[1]
else:
    output_filename = ntpath.basename(sys.argv[0])
    output_filename = os.path.splitext(output_filename)[0]
    pdf_filename = output_filename + '.pdf'

f = open(row_tpl_filename)
row_rml = f.read()
f.close()
rows = []
for i in range(1, 70):
    id = randrange(10000, 99999)
    hp = get_hp()
    nama = ' '.join([get_nama1(), get_nama2()])
    s = row_rml.format(no=i, id=id, nama=nama.title(), hp=hp)
    rows.append(s)
rows_rml = '\n'.join(rows)

f = open(tpl_filename)
rml = f.read()
f.close()
rml = rml.format(rows=rows_rml, waktu=waktu())

pdf = rml2pdf.parseString(rml)
f = open(pdf_filename, 'w')
f.write(pdf.read())
f.close()
Exemple #53
0
    def __call__(self, *args, **kwargs):
        rml = super(RMLPageTemplateFile, self).__call__(*args, **kwargs)

        return rml2pdf.parseString(
            rml, filename=self.pt_source_file()).getvalue()
Exemple #54
0
def generatePdf(request, cattle_id):
    # Load the rml template into the preprocessor, ...
    template = preppy.getModule('testDoc.prep')
    user = request.user
    farm = Ganaderia.objects.get(perfil=user)
    cattle = Ganado.objects.get(id=cattle_id)
    configuration = Configuracion.objects.get(id=farm.configuracion.id)
    if configuration.tipo_identificacion=='simple':
        nombre = cattle.identificacion_simple.nombre
        rp = cattle.identificacion_simple.rp
        raza = cattle.get_raza_display()
        nacimiento = str(cattle.nacimiento)
        concepcion = cattle.get_forma_concepcion_display()
        edad = str(cattle.edad_anios)+' años, '+str(cattle.edad_meses)+' meses y '+str(cattle.edad_dias)+' dias'
        try:
            cattle_mother = Ganado.objects.get(identificacion_simple__rp=cattle.identificacion_simple.rp_madre)
            cattle_mother = cattle_mother.identificacion_simple.nombre
        except ObjectDoesNotExist:
            cattle_mother = 'Madre Desconocida'
        try:
            cattle_father = Ganado.objects.get(identificacion_simple__rp=cattle.identificacion_simple.rp_padre)
            cattle_father = cattle_father.identificacion_simple.nombre
        except ObjectDoesNotExist:
            try:
                cattle_father = Insemination.objects.get(rp=cattle.identificacion_simple.rp_padre)
                cattle_father= cattle_father.name
            except ObjectDoesNotExist:
                cattle_father='Padre Desconocido'
        celos = cattle.celos.count()
        problem_gestacion=ProblemaGestacion.objects.filter(id=cattle.id)
        total_births = Gestacion.objects.filter(
                Q(ganado=cattle, is_active=False) &
                ~Q(problema=problem_gestacion)
                ).count()
        total_problems_births=ProblemaGestacion.objects.filter(id=cattle.id).count()
        ordenio = Ordenio.objects.filter(ganado=cattle)
        count_milk=0
        count=0
        for o in ordenio:
            if o.numero_ordenio == configuration.numero_ordenios:
                count_milk+=o.total
                count+=1
        if count_milk > 0:
            count_milk=count_milk/count

        application_food=ApplicationFood.objects.filter(cattle=cattle)
        food=[]
        i=1
        for f in application_food:
            aux = str(f.food.name+' - '+str(f.food.consumer_amount)+' '+f.food.get_unit_display()+'. (X'+str(i)+')')
            if aux not in food:
                food.append(aux)
            else:
                index=food.index(aux)
                i+=1
                food[index]=str(f.food.name+' - '+str(f.food.consumer_amount)+' '+f.food.get_unit_display()+'.')+' (X'+str(i)+')'
        medicament_wormer=Medicament.objects.filter(farm=farm, is_wormer=True)
        application_medicament_wormer=ApplicationMedicament.objects.filter(medicament=medicament_wormer, cattle=cattle).order_by('medicament')
        wormer=[]
        i=1
        for w in application_medicament_wormer:
            aux=str(w.medicament.name+' - '+str(w.medicament.amount_application)+' '+w.medicament.get_unit_display()+'. (X'+str(i)+')')
            if aux not in wormer:
                wormer.append(aux)
            else:
                index=wormer.index(aux)
                i+=1
                wormer[index]=str(w.medicament.name+' - '+str(w.medicament.amount_application)+' '+w.medicament.get_unit_display()+'.')+' (X'+str(i)+')'
        medicament_vaccine=Medicament.objects.filter(farm=farm, is_vaccine=True)
        application_medicament_vaccine=ApplicationMedicament.objects.filter(medicament=medicament_vaccine, cattle=cattle).order_by('medicament')
        vaccine=[]
        i=1
        for v in application_medicament_vaccine:
            aux=str(v.medicament.name+' - '+str(v.medicament.amount_application)+' '+v.medicament.get_unit_display()+'. (X'+str(i)+')')
            if aux not in vaccine:
                vaccine.append(aux)
            else:
                index=vaccine.index(aux)
                i+=1
                vaccine[index]=str(v.medicament.name+' - '+str(v.medicament.amount_application)+' '+v.medicament.get_unit_display()+'.')+' (X'+str(i)+')'

    else:
        nombre = cattle.identificacion_ecuador.nombre
        rp = cattle.identificacion_ecuador.rp
        raza = cattle.get_raza_display()
        nacimiento = str(cattle.nacimiento)
        concepcion = cattle.get_forma_concepcion_display()
        edad = str(cattle.edad_anios)+' años, '+str(cattle.edad_meses)+' meses y '+str(cattle.edad_dias)+' dias'
        try:
            cattle_mother = Ganado.objects.get(identificacion_ecuador__rp=cattle.identificacion_ecuador.rp_madre)
            cattle_mother = cattle_mother.identificacion_ecuador.nombre
        except ObjectDoesNotExist:
            cattle_mother = 'Madre Desconocida'
        try:
            cattle_father = Ganado.objects.get(identificacion_ecuador__rp=cattle.identificacion_ecuador.rp_padre)
            cattle_father = cattle_father.identificacion_ecuador.nombre
        except ObjectDoesNotExist:
            try:
                cattle_father = Insemination.objects.get(rp=cattle.identificacion_ecuador.rp_padre)
                cattle_father= cattle_father.name
            except ObjectDoesNotExist:
                cattle_father='Padre Desconocido'
        celos = cattle.celos.count()
        problem_gestacion=ProblemaGestacion.objects.filter(id=cattle.id)
        total_births = Gestacion.objects.filter(
                Q(ganado=cattle, is_active=False) &
                ~Q(problema=problem_gestacion)
                ).count()
        total_problems_births=ProblemaGestacion.objects.filter(id=cattle.id).count()
        ordenio = Ordenio.objects.filter(ganado=cattle)
        count_milk=0
        count=0
        for o in ordenio:
            if o.numero_ordenio == configuration.numero_ordenios:
                count_milk+=o.total
                count+=1
        if count_milk > 0:
            count_milk=count_milk/count
        application_food=ApplicationFood.objects.filter(cattle=cattle)
        food=[]
        i=1
        for f in application_food:
            aux = str(f.food.name+' - '+str(f.food.consumer_amount)+' '+f.food.get_unit_display()+'. (X'+str(i)+')')
            if aux not in food:
                food.append(aux)
            else:
                index=food.index(aux)
                i+=1
                food[index]=str(f.food.name+' - '+str(f.food.consumer_amount)+' '+f.food.get_unit_display()+'.')+' (X'+str(i)+')'
        medicament_wormer=Medicament.objects.filter(farm=farm, is_wormer=True)
        application_medicament_wormer=ApplicationMedicament.objects.filter(medicament=medicament_wormer, cattle=cattle).order_by('medicament')
        wormer=[]
        i=1
        for w in application_medicament_wormer:
            aux=str(w.medicament.name+' - '+str(w.medicament.amount_application)+' '+w.medicament.get_unit_display()+'. (X'+str(i)+')')
            if aux not in wormer:
                wormer.append(aux)
            else:
                index=wormer.index(aux)
                i+=1
                wormer[index]=str(w.medicament.name+' - '+str(w.medicament.amount_application)+' '+w.medicament.get_unit_display()+'.')+' (X'+str(i)+')'


    # ... and do the preprocessing.
    table=[]
    # date, name, website, email, description, farm, adress, table
    rmlText = template.get(
            table,
            datetime.datetime.now().strftime("%Y-%m-%d"),
            'Reporte Individual de Ganado',
            'www.hatosganaderos.com',
            '*****@*****.**',
            'HatosGanaderos te ayuda con el control y organización de reproducción, alimentación, sanidad y producción de toda tu entidad ganadera.',
            'Ganadería Lojana',
            'Ciudadela universitaria',
            nombre,
            rp,
            raza,
            nacimiento,
            concepcion,
            edad,
            cattle_mother,
            cattle_father,
            celos,
            total_births,
            total_problems_births,
            count_milk,
            food,
            wormer,
            vaccine)

    # Finally generate the *.pdf output ...
    pdf = rml2pdf.parseString(rmlText)

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="somefilename.pdf"'

    return response