def createBarCodes(path, barcode_value): from reportlab.graphics.barcode import eanbc from reportlab.graphics.shapes import Drawing from reportlab.pdfgen import canvas from reportlab.graphics import renderPDF from reportlab.lib.units import cm, mm from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus.para import Paragraph # draw the eanbc13 code barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) bounds = barcode_eanbc13.getBounds() barcode_eanbc13.barHeight = 19*mm width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing() d.add(barcode_eanbc13) c = canvas.Canvas(path, pagesize=(43*mm, 25*mm)) # print width, height text = "%s.%s" % (150, '00') p = Paragraph(text, getSampleStyleSheet()["Normal"]) p.wrapOn(c, 43*mm, 5*mm) p.drawOn(c, 16*mm, 20*mm) renderPDF.draw(d, c, 3*mm, 1*mm) c.save()
def set_cabec(self, h5): cabec = [Paragraph(_('Cidade'), h5)] cabec.append(Paragraph(_('Grupo'), h5)) cabec.append(Paragraph(_('Nome'), h5)) cabec.append(Paragraph(_('Endereço'), h5)) cabec.append(Paragraph(_('Telefone'), h5)) self.cabec = cabec
def set_cabec(self, h5): cabec = [Paragraph(_('Data'), h5)] if self.agrupamento != 'titulo': cabec.append(Paragraph(_('Título'), h5)) cabec.append(Paragraph(_('Nome'), h5)) cabec.append(Paragraph(_('Endereço'), h5)) cabec.append(Paragraph(_('Telefone'), h5)) self.cabec = cabec
def _draw_audit_trail(self, story): s = self.styles["line_data_small"] t = Table( [[ Paragraph("Document", s), Paragraph("Changed by", s), Paragraph("Date", s), Paragraph("Action", s), ]], (3 * cm, 3 * cm, 3 * cm, 9 * cm), ) self.set_table_style(t, bg_cmd=("BACKGROUND", (0, 0), (3, -1), colors.lightgrey)) story.append(t) qs = DeathReportModel.history.filter( id=self.death_report.id).order_by("-history_date") for obj in qs: username = (obj.user_created if obj.history_type == "+" else obj.user_modified) t = Table( [[ Paragraph(DeathReportModel._meta.verbose_name, s), Paragraph(username, s), Paragraph(obj.modified.strftime("%Y-%m-%d %H:%M"), s), Paragraph(fill(self.history_change_message(obj), width=60), s), ]], (3 * cm, 3 * cm, 3 * cm, 9 * cm), ) self.set_table_style(t) story.append(t)
def add_relat_title(self, corpo_relatorio): tit_relatorio = _(self.relat_title) tit_relatorio = force_text(tit_relatorio) + ' ' tit_relatorio += force_text(_('Agrupados')) corpo_relatorio.append([Paragraph(tit_relatorio, self.h3)]) corpo_relatorio.append(self.cabec)
def get_data(self): self.set_headings() self.set_styles() cleaned_data = self.filterset.form.cleaned_data agrupamento = cleaned_data['agrupamento'] agrupamento = '' if agrupamento == 'sem_agrupamento' else agrupamento self.agrupamento = agrupamento data = [] self.set_cabec(self.h5) self.set_object_list() where = self.object_list.query.where for p in self.object_list.all(): item = [] self.set_label_agrupamento(p) if not data: self.add_relat_title(data) if not p or isinstance(p, str): self.add_group_title(data, p) contatos_query = self.build_query(p, where) else: if len(p.titulo) < self.MAX_TITULO: paragrafo = str(p.titulo) estilo = self.h_style else: paragrafo = (p.titulo[:self.MAX_TITULO] + force_text(_(' (Continua...)'))) estilo = self.s_min item = [ Paragraph(p.data.strftime('%d/%m/%Y'), self.s_center), Paragraph(paragrafo, estilo) ] contatos_query = p.contatos.all() self.set_body_data(where, contatos_query, data, item) return data
def add_group_title(self, corpo_relatorio, registro_principal): import pdb pdb.set_trace() corpo_relatorio.append([]) lbl_group = self.label_agrupamento if registro_principal: paragrafo = lbl_group + ' - ' + str(registro_principal) else: paragrafo = (force_text(_('Sem Agrupamento')) + ' ' + lbl_group) corpo_relatorio.append([Paragraph(paragrafo, self.h4)]) corpo_relatorio.append(self.cabec)
def add_relat_title(self, data): tit_relatorio = _(self.relat_title) tit_relatorio = force_text(tit_relatorio) + ' ' if self.label_agrupamento: tit_relatorio += force_text(_('Agrupados')) else: tit_relatorio += force_text(_('Sem Agrupamento')) tit_relatorio += ' ' + self.label_agrupamento data.append([Paragraph(tit_relatorio, self.h3)]) if not self.label_agrupamento: data.append(self.cabec)
def generate_barcode(self, value, left_margin, bottom_margin, out_dir, logo_path, description, page_size=( 200, 100, )): """ Generates a barcode from a value and save it on a PDF file. e.g >> from barcodelib import BarCode >> BarCode().generate_barcode('SBLS12-12', 2.8, 2, '.', logo_path=logo_dir, description="Stailess Style Standoff Diameter: 1/2, Standoff: 1/2 Satin Finish (For Inside Use Only)") :param left_margin: :param bottom_margin: :param out_dir: :return: """ width, height = page_size value = str(value) filename = 'barcode_%s.pdf' % value file_path = os.path.join(out_dir, filename) c = canvas.Canvas(file_path, pagesize=page_size) c.drawImage(logo_path, 5, height - 35, height=30, width=30) # stamp the bar code # drawOn puts the barcode on the canvas at the specified coordinates # stamp the bar code d = Drawing(50, 10) d.add( createBarcodeDrawing('Standard39', value=value, barHeight=10 * mm, humanReadable=True, checksum=0)) # drawOn puts the barcode on the canvas at the specified coordinates d.drawOn(c, left_margin * cm, bottom_margin * cm) styles = getSampleStyleSheet() p = Paragraph('<font size="10">{}</font>'.format(description), styles["Normal"]) p.wrapOn(c, width - 85, height) p.drawOn(c, 51, 10) # now create the actual PDF c.showPage() c.save() return file_path
def _build_invoices(prestations, invoice_number, invoice_date, accident_id, accident_date): # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. # import pydevd; pydevd.settrace() elements = [] i = 0 data = [] patientSocNumber = '' patientNameAndFirstName = '' patientName = '' patientFirstName = '' patientAddress = '' data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'Net', 'Heure', 'P. Pers', 'Executant')) pytz_luxembourg = pytz.timezone("Europe/Luxembourg") for presta in prestations: patient = presta.invoice_item.patient patientSocNumber = patient.code_sn patientNameAndFirstName = patient patientName = patient.name patientFirstName = patient.first_name patientAddress = patient.address patientZipCode = patient.zipcode patientCity = patient.city if presta.carecode.reimbursed: i += 1 data.append(( i, presta.carecode.code, (pytz_luxembourg.normalize(presta.date)).strftime('%d/%m/%Y'), '1', presta.carecode.gross_amount(presta.date), presta.carecode.gross_amount(presta.date), (pytz_luxembourg.normalize(presta.date)).strftime('%H:%M'), "", #TODO : replace with Global setting "300744-44")) for x in range(len(data), 22): data.append((x, '', '', '', '', '', '', '', '')) newData = [] for y in range(0, len(data) - 1): newData.append(data[y]) if y % 10 == 0 and y != 0: _gross_sum = _compute_sum(data[y - 9:y + 1], 4) _net_sum = _compute_sum(data[y - 9:y + 1], 5) newData.append( ('', '', '', 'Sous-Total', _gross_sum, _net_sum, '', '', '')) newData.append(('', '', '', 'Total', _compute_sum(data[1:], 4), _compute_sum(data[1:], 5), '', '', '')) _total_facture = _compute_sum(data[1:], 5) headerData = [ [ 'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n' # TODO : replace with Global setting + 'Regine SIMBA\n' + '1A, rue fort wallis\n' + 'L-2714 Luxembourg\n' + u'Tél: 691.30.85.84', 'CODE DU FOURNISSEUR DE SOINS DE SANTE\n' + '300744-44' ], [ u'Matricule patient: %s' % smart_text(patientSocNumber.strip()) + "\n" + u'Nom et Pr' + smart_text("e") + u'nom du patient: %s' % smart_text(patientNameAndFirstName), u'Nom: %s' % smart_text(patientName.strip()) + '\n' + u'Pr' + smart_text(u"é") + u'nom: %s' % smart_text(patientFirstName.strip()) + '\n' + u'Rue: %s' % patientAddress.strip() + '\n' + u'Code postal: %s' % smart_text(patientZipCode.strip()) + '\n' + u'Ville: %s' % smart_text(patientCity.strip()) ], [ u'Date accident: %s\n' % (accident_date if accident_date else "") + u'Num. accident: %s' % (accident_id if accident_id else "") ] ] headerTable = Table(headerData, 2 * [10 * cm], [2.5 * cm, 1 * cm, 1.5 * cm]) headerTable.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('SPAN', (1, 1), (1, 2)), ])) table = Table(newData, 9 * [2 * cm], 24 * [0.5 * cm]) table.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, -1), (-6, -1), 'RIGHT'), ('INNERGRID', (0, -1), (-6, -1), 0, colors.white), ('ALIGN', (0, -2), (-6, -2), 'RIGHT'), ('INNERGRID', (0, -2), (-6, -2), 0, colors.white), ('FONTSIZE', (0, 0), (-1, -1), 8), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) elements.append(headerTable) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) elements.append(Spacer(1, 18)) elements.append( Paragraph( u"Mémoire d'Honoraires Num. %s en date du : %s" % (invoice_number, invoice_date), styles['Center'])) elements.append(Spacer(1, 18)) elements.append(table) elements.append(Spacer(1, 18)) _total_a_payer = Table( [["Total facture:", "%10.2f Euros" % _total_facture]], [10 * cm, 5 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(Spacer(1, 18)) elements.append(_total_a_payer) elements.append(Spacer(1, 18)) return { "elements": elements, "invoice_number": invoice_number, "patient_name": patientName + " " + patientFirstName, "invoice_amount": newData[23][5] }
def _build_invoices(prestations, invoice_number, invoice_date, prescription_date, accident_id, accident_date): # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. #import pydevd; pydevd.settrace() elements = [] i = 0 data = [] patientSocNumber = '' patientNameAndFirstName = '' patientName = '' patientFirstName = '' patientAddress = '' data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'Net', 'Heure', 'P. Pers', 'Executant')) for presta in prestations: i += 1 patientSocNumber = presta.patient.code_sn patientNameAndFirstName = presta.patient patientName = presta.patient.name patientFirstName = presta.patient.first_name patientAddress = presta.patient.address patientZipCode = presta.patient.zipcode patientCity = presta.patient.city data.append( (i, presta.carecode.code, (presta.date).strftime('%d/%m/%Y'), '1', presta.carecode.gross_amount, presta.net_amount, (presta.date).strftime('%H:%M'), "", "300744-44")) for x in range(len(data), 22): data.append((x, '', '', '', '', '', '', '', '')) newData = [] for y in range(0, len(data) - 1): newData.append(data[y]) if (y % 10 == 0 and y != 0): _gross_sum = _compute_sum(data[y - 9:y + 1], 4) _net_sum = _compute_sum(data[y - 9:y + 1], 5) newData.append( ('', '', '', 'Sous-Total', _gross_sum, _net_sum, '', '', '')) _total_facture = _compute_sum(data[1:], 5) newData.append(('', '', '', 'Total', _compute_sum(data[1:], 4), _compute_sum(data[1:], 5), '', '', '')) headerData = [ [ 'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n' + 'Regine SIMBA\n' + '1A, rue fort wallis\n' + 'L-2714 Luxembourg\n' + 'T' + u"é".encode("utf-8") + "l: 691.30.85.84", 'CODE DU FOURNISSEUR DE SOINS DE SANTE\n' + '300744-44' ], [ u'Matricule patient: %s' % smart_unicode(patientSocNumber.strip()) + "\n" + u'Nom et Pr' + smart_unicode("e") + u'nom du patient: %s' % smart_unicode(patientNameAndFirstName), u'Nom: %s' % smart_unicode(patientName.strip()) + '\n' + u'Pr' + smart_unicode(u"é") + u'nom: %s' % smart_unicode(patientFirstName.strip()) + '\n' + u'Rue: %s' % patientAddress.strip() + '\n' + u'Code postal: %s' % smart_unicode(patientZipCode.strip()) + '\n' + u'Ville: %s' % smart_unicode(patientCity.strip()) ], [ u'Date accident: %s\n' % (accident_date if accident_date else "") + u'Num. accident: %s' % (accident_id if accident_id else "") ] ] headerTable = Table(headerData, 2 * [10 * cm], [2.5 * cm, 1 * cm, 1.5 * cm]) headerTable.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('SPAN', (1, 1), (1, 2)), ])) table = Table(newData, 9 * [2 * cm], 24 * [0.5 * cm]) table.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, -1), (-6, -1), 'RIGHT'), ('INNERGRID', (0, -1), (-6, -1), 0, colors.white), ('ALIGN', (0, -2), (-6, -2), 'RIGHT'), ('INNERGRID', (0, -2), (-6, -2), 0, colors.white), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) elements.append(headerTable) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) elements.append(Spacer(1, 18)) if (prescription_date is not None): elements.append( Paragraph( "Memoire d'Honoraires Num. %s en date du : %s Ordonnance du %s " % (invoice_number, invoice_date, prescription_date), styles['Heading4'])) else: elements.append( Paragraph( "Memoire d'Honoraires Num. %s en date du : %s " % (invoice_number, invoice_date), styles['Heading4'])) elements.append(Spacer(1, 18)) elements.append(table) _2derniers_cases = Table([["", "Paiement Direct"]], [1 * cm, 4 * cm], 1 * [0.5 * cm], hAlign='LEFT') _2derniers_cases.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'RIGHT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9), ('BOX', (0, 0), (0, 0), 0.75, colors.black), ('SPAN', (1, 1), (1, 2)), ])) elements.append(Spacer(1, 18)) elements.append(_2derniers_cases) _2derniers_cases = Table([["", "Tiers payant"]], [1 * cm, 4 * cm], 1 * [0.5 * cm], hAlign='LEFT') _2derniers_cases.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'RIGHT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9), ('BOX', (0, 0), (0, 0), 0.75, colors.black), ('SPAN', (1, 1), (1, 2)), ])) elements.append(Spacer(1, 18)) elements.append(_2derniers_cases) elements.append(Spacer(1, 18)) _total_a_payer = Table( [["Total facture:", "%10.2f Euros" % _total_facture]], [10 * cm, 5 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(Spacer(1, 18)) elements.append(_total_a_payer) elements.append(Spacer(1, 18)) _pouracquit_signature = Table( [["Pour acquit, le:", "Signature et cachet"]], [10 * cm, 10 * cm], 1 * [0.5 * cm], hAlign='LEFT') _infos_iban = Table([["LU55 0019 4555 2516 1000 BCEELULL"]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(Spacer(1, 10)) #elements.append(_infos_iban) if prescription_date is not None: _infos_iban = Table([[ "Lors du virement, veuillez indiquer la r" + u"é" + "f" + u"é" + "rence: %s Ordonnance du %s " % (invoice_number, prescription_date) ]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') else: _infos_iban = Table([[ "Lors du virement, veuillez indiquer la r" + u"é" + "f" + u"é" + "rence: %s " % invoice_number ]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') #elements.append( _infos_iban ) #elements.append(_pouracquit_signature) return { "elements": elements, "invoice_number": invoice_number, "patient_name": patientName + " " + patientFirstName, "invoice_amount": newData[23][5] }
def _build_invoices(prestations, invoice_number, invoice_date, prescription_date, accident_id, accident_date, invoice_send_date, patient): # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. elements = [] i = 0 data = [] patientSocNumber = ''; patientNameAndFirstName = ''; patientName = ''; patientFirstName = ''; patientAddress = '' data.append(('Num. titre', 'Prestation', 'Date', 'Heure', 'Nombre', 'Brut', 'P. CNS', 'P. Pers','Executant')) pytz_luxembourg = pytz.timezone("Europe/Luxembourg") for presta in prestations: i+=1 patientSocNumber = patient.code_sn patientNameAndFirstName = patient patientName = patient.name patientFirstName = patient.first_name patientAddress = patient.address patientZipCode = patient.zipcode patientCity = patient.city data.append((i, presta.carecode.code, (pytz_luxembourg.normalize(presta.date)).strftime('%d/%m/%Y'), (pytz_luxembourg.normalize(presta.date)).strftime('%H:%M'), presta.quantity, presta.carecode.gross_amount(presta.date) * presta.quantity, presta.carecode.net_amount(presta.date, patient.is_private, patient.participation_statutaire and patient.age > 18) * presta.quantity, "%10.2f" % ((decimal.Decimal(presta.carecode.gross_amount(presta.date)) - decimal.Decimal(presta.carecode.net_amount(presta.date, patient.is_private, patient.participation_statutaire and patient.age > 18))) * decimal.Decimal(presta.quantity)), presta.employee)) for x in range(len(data) , 22): data.append((x, '', '', '', '', '', '', '','')) newData = [] for y in range(0, len(data) -1) : newData.append(data[y]) if(y % 10 == 0 and y != 0): _qty_sum = _compute_sum(data[y - 9:y + 1], 4) _gross_sum = _compute_sum(data[y-9:y+1], 5) _net_sum = _compute_sum(data[y-9:y+1], 6) _part_sum = _compute_sum(data[y - 9:y + 1], 7) newData.append(('', '', '', 'Sous-Total', _qty_sum, _gross_sum, _net_sum, _part_sum,'')) _total_facture = _compute_sum(data[1:], 7) newData.append(('', '', '', 'Total', _compute_sum(data[1:], 4), _compute_sum(data[1:], 5), _compute_sum(data[1:], 6), _compute_sum(data[1:], 7),'')) headerData = [['IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n' + "{0}\n{1}\n{2}\n{3}".format(config.NURSE_NAME, config.NURSE_ADDRESS, config.NURSE_ZIP_CODE_CITY, config.NURSE_PHONE_NUMBER), 'CODE DU FOURNISSEUR DE SOINS DE SANTE\n{0}'.format(config.MAIN_NURSE_CODE) ], [u'Matricule patient: %s' % smart_text(patientSocNumber.strip()) + "\n" + u'Nom et Pr'+ smart_text("e") + u'nom du patient: %s' % smart_text(patientNameAndFirstName) , u'Nom: %s' % smart_text(patientName.strip()) +'\n' + u'Prénom: %s' % smart_text(patientFirstName.strip()) +'\n' + u'Rue: %s' % patientAddress.strip() + '\n' + u'Code postal: %s' % smart_text(patientZipCode.strip()) + '\n' + u'Ville: %s' % smart_text(patientCity.strip()) ], [ u'Date accident: %s\n' % (accident_date if accident_date else "") + u'Num. accident: %s' % (accident_id if accident_id else "")]] headerTable = Table(headerData, 2*[10*cm], [2.5*cm, 1*cm, 1.5*cm] ) headerTable.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'LEFT'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 9), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('SPAN', (1, 1) , (1,2)), ])) table = Table(newData, 9*[2*cm], 24*[0.5*cm] ) table.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'LEFT'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('ALIGN',(0,-1), (-6,-1),'RIGHT'), ('INNERGRID', (0,-1), (-6,-1), 0, colors.white), ('ALIGN',(0,-2), (-6,-2),'RIGHT'), ('INNERGRID', (0,-2), (-6,-2), 0, colors.white), ('FONTSIZE', (0,0), (-1,-1), 7), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) elements.append(headerTable) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) elements.append(Spacer(1, 18)) if(prescription_date is not None): elements.append(Paragraph(u"Mémoire d'Honoraires Num. %s en date du : %s Ordonnance du %s " %( invoice_number, invoice_date, prescription_date), styles['Heading4'])) else: elements.append(Paragraph(u"Mémoire d'Honoraires Num. %s en date du : %s " %( invoice_number, invoice_date), styles['Heading4'])) elements.append(Spacer(1, 18)) elements.append(table) _2derniers_cases = Table([["", "Paiement Direct"]], [1*cm, 4*cm], 1*[0.5*cm], hAlign='LEFT' ) _2derniers_cases.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 9), ('BOX', (0,0), (0,0), 0.75, colors.black), ('SPAN', (1, 1) , (1,2)), ])) elements.append(Spacer(1, 18)) elements.append(_2derniers_cases) _2derniers_cases = Table([["", "Tiers payant"]], [1*cm, 4*cm], 1*[0.5*cm], hAlign='LEFT' ) _2derniers_cases.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 9), ('BOX', (0,0), (0,0), 0.75, colors.black), ('SPAN', (1, 1) , (1,2)), ])) elements.append(Spacer(1, 18)) elements.append(_2derniers_cases) elements.append(Spacer(1, 18)) elements.append(PageBreak()) return {"elements" : elements , "invoice_number" : invoice_number , "patient_name" : patientName + " " + patientFirstName , "invoice_amount" : newData[23][5]}
def normal_text(text): return [Paragraph('<para autoLeading="off" align="left"><font face="song" fontsize="9">%s</font></para>' % text, normalStyle), Spacer(6, 20)]
def second_title(text): return [Paragraph('<para autoLeading="off" align="left"><font face="hei" fontsize="10">%s</font></para>' % text, normalStyle), Spacer(6, 10)]
def _build_recap(recaps, payment_ref): elements = [] data = [] i = 0 styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) elements.append(Spacer(3, 18)) elements.append(Paragraph(u"Récapitulatif des notes", styles['Center'])) elements.append(Spacer(3, 18)) data.append(("No d'ordre", u"Note no°", u"Nom et prénom", "Montant")) total = 0.0 for recap in recaps: i += 1 data.append((i, recap[0], recap[1], recap[2])) total = decimal.Decimal(total) + decimal.Decimal(recap[2]) data.append(("", "", u"Total", round(total, 2))) table = Table(data, [2 * cm, 3 * cm, 7 * cm, 3 * cm, 3 * cm]) table.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) elements.append(table) elements.append(Spacer(3, 18)) _intro = Table([[ u"Veuillez trouver ci-joint le récapitulatif des notes ainsi que le montant total payer" ]], [10 * cm, 5 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(_intro) _total_a_payer = Table( [["Total " + u"à" + " payer:", "%10.2f Euros" % total]], [10 * cm, 5 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(_total_a_payer) elements.append(Spacer(1, 18)) _infos_iban = Table( [[u"Numéro compte IBAN: LU55 0019 4555 2516 1000 BCEELULL"]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(_infos_iban) elements.append(Spacer(1, 18)) _infos_iban = Table([[ u"Lors du virement, veuillez indiquer la référence: %s " % payment_ref.upper() ]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(_infos_iban) return elements
def _build_final_page(total, order_number): elements = [] data = [["RELEVE DES NOTES D’HONORAIRES DES"], ["ACTES ET SERVICES DES INFIRMIERS"]] table = Table(data, [10 * cm], [0.75 * cm, 0.75 * cm]) table.setStyle( TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('INNERGRID', (0, 0), (-1, -1), 0, colors.white), ('FONTSIZE', (0, 0), (-1, -1), 12), ('BOX', (0, 0), (-1, -1), 1.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) elements.append(table) elements.append(Spacer(1, 18)) data2 = [[ u"Identification du fournisseur de", config.NURSE_NAME, "", u"réservé à l’union des caisses de maladie" ], [u"soins de santé", "", "", ""], [u"Coordonnées bancaires :", config.MAIN_BANK_ACCOUNT, "", ""], ["Code: ", config.MAIN_NURSE_CODE, "", ""]] table2 = Table(data2, [5 * cm, 3 * cm, 3 * cm, 7 * cm], [1.25 * cm, 0.5 * cm, 1.25 * cm, 1.25 * cm]) table2.setStyle( TableStyle([('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('ALIGN', (3, 0), (3, 0), 'CENTER'), ('INNERGRID', (0, 0), (-1, -1), 0, colors.white), ('SPAN', (1, 2), (2, 2)), ('FONTSIZE', (0, 0), (-1, -1), 8), ('BOX', (3, 0), (3, 3), 0.25, colors.black), ('BOX', (3, 0), (3, 1), 0.25, colors.black), ('BOX', (1, 3), (1, 3), 1, colors.black)])) elements.append(table2) elements.append(Spacer(1, 20)) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) elements.append( Paragraph( u"Récapitulation des notes d’honoraires du chef de la fourniture de soins de santé dispensés aux personnes protégées relevant de l’assurance maladie / assurance accidents ou de l’assurance dépendance.", styles['Justify'])) elements.append(Spacer(2, 20)) elements.append( Paragraph( u"Pendant la période du :.................................. au :..................................", styles['Justify'])) data3 = [[ "Nombre des mémoires d’honoraires ou\nd’enregistrements du support informatique:", order_number ]] table3 = Table(data3, [9 * cm, 8 * cm], [1.25 * cm]) table3.setStyle( TableStyle([('ALIGN', (0, 0), (0, 0), 'LEFT'), ('ALIGN', (-1, -1), (-1, -1), 'CENTER'), ('VALIGN', (-1, -1), (-1, -1), 'MIDDLE'), ('INNERGRID', (0, 0), (-1, -1), 0, colors.white), ('FONTSIZE', (0, 0), (-1, -1), 9), ('BOX', (1, 0), (-1, -1), 1.25, colors.black)])) elements.append(Spacer(2, 20)) elements.append(table3) elements.append(Spacer(2, 20)) data4 = [[ u"Montant total des honoraires à charge de\nl’organisme assureur (montant net cf. zone 14) du\nmém. d’honoraires):", "%.2f EUR" % round(total, 2) ]] table4 = Table(data4, [9 * cm, 8 * cm], [1.25 * cm]) table4.setStyle( TableStyle([('ALIGN', (0, 0), (0, 0), 'LEFT'), ('ALIGN', (-1, -1), (-1, -1), 'CENTER'), ('VALIGN', (-1, -1), (-1, -1), 'MIDDLE'), ('INNERGRID', (0, 0), (-1, -1), 0, colors.white), ('FONTSIZE', (0, 0), (-1, -1), 9), ('BOX', (1, 0), (-1, -1), 1.25, colors.black)])) elements.append(table4) elements.append(Spacer(40, 60)) styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT)) elements.append( Paragraph( u"Certifié sincère et véritable, mais non encore acquitté: ________________ ,le ______________________", styles['Left'])) return elements
def report_reserva(request, fecha1, fecha2, estado): #Create the HttpResponse headers with PDF response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="reporte-reserva.pdf"' #Create the pdf object, using the BytesIO object as its "file." buffer = BytesIO() c = canvas.Canvas(buffer, pagesize=A4) # Header c.setLineWidth(.3) c.setFont('Helvetica', 22) c.drawString(30, 750, 'Hotel Amanecer') c.setFont('Helvetica', 12) c.drawString(30, 735, 'Reporte de Reservas') c.setFont('Helvetica-Bold', 12) c.drawString(480, 750, str(datetime.date.today())) # start X, height end y, heigth c.line(460, 747, 560, 747) # Tabla Reservas reservas = Reserva.objects.none() if estado == 'Todos': reservas = list( Reserva.objects.exclude(estado="Anulado").filter( fecha_entrada__gte=fecha1, fecha_entrada__lt=fecha2, )) else: reservas = list( Reserva.objects.filter(fecha_entrada__gte=fecha1, fecha_entrada__lt=fecha2, estado=estado)) # Table header styles = getSampleStyleSheet() styleBH = styles["Normal"] styleBH.alignment = TA_CENTER styleBH.fontSize = 18 cliente = Paragraph('''Cliente''', styleBH) habitacion = Paragraph('''Habitacion''', styleBH) fecha_entrada = Paragraph('''Entrada''', styleBH) fecha_salida = Paragraph('''Salida''', styleBH) costo_alojamiento = Paragraph('''Importe''', styleBH) data = [] data.append( [cliente, habitacion, fecha_entrada, fecha_salida, costo_alojamiento]) # Table body styleN = styles["Normal"] styleN.alignment = TA_CENTER styleN.fontSize = 7 high = 650 for reserva in reservas: this_reserva = [ reserva.id_cliente_fk, reserva.id_habitacion_fk, reserva.fecha_entrada, reserva.fecha_salida, reserva.costo_alojamiento, ] data.append(this_reserva) high = high - 18 # Table size width, height = A4 table = Table(data, colWidths=[ 4.125 * cm, 2.5 * cm, 4.125 * cm, 4.125 * cm, 4.125 * cm, ]) table.setStyle( TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) # Pdf size table.wrapOn(c, width, height) table.drawOn(c, 30, high) # End writing c.showPage() c.save() # get the value of BytesIO buffer and write response pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def get_data(self): """data ini 2016-08-29 09:45:43.018039 data fim 2016-08-29 09:47:16.667659 enumerate ini 2016-08-29 09:47:16.667745 enumerate fim 2016-08-29 09:47:16.671923 table ini 2016-08-29 09:47:16.671954 table fim 2016-08-29 09:47:17.233298 doc ini 2016-08-29 09:47:17.233338 doc fim 2016-08-29 10:13:36.675347""" # 211 páginas # 6723 MAX_TITULO = 80 s = getSampleStyleSheet() h3 = s["Heading3"] h3.fontName = _baseFontNameB h3.alignment = TA_CENTER h4 = s["Heading4"] h4.fontName = _baseFontNameB h5 = s["Heading5"] h5.fontName = _baseFontNameB h5.alignment = TA_CENTER s = s["BodyText"] s.wordWrap = None # 'LTR' s.spaceBefore = 0 s.fontSize = 8 s.leading = 8 s_min = getSampleStyleSheet() s_min = s_min["BodyText"] s_min.wordWrap = None # 'LTR' s_min.spaceBefore = 0 s_min.fontSize = 6 s_min.leading = 8 s_center = getSampleStyleSheet() s_center = s_center["BodyText"] s_center.wordWrap = None # 'LTR' s_center.spaceBefore = 0 s_center.alignment = TA_CENTER s_center.fontSize = 8 s_center.leading = 8 s_right = getSampleStyleSheet() s_right = s_right["BodyText"] s_right.wordWrap = None # 'LTR' s_right.spaceBefore = 0 s_right.alignment = TA_RIGHT s_right.fontSize = 8 s_right.leading = 8 cleaned_data = self.filterset.form.cleaned_data agrupamento = cleaned_data['agrupamento'] agrupamento = '' if agrupamento == 'sem_agrupamento' else agrupamento if not agrupamento: self.object_list = self.object_list.order_by( 'data', 'titulo', 'contatos__nome') else: self.object_list = self.object_list.order_by(agrupamento).distinct( agrupamento).values_list(agrupamento, flat=True) data = [] cabec = [] cabec.append(Paragraph(_('Data'), h5)) if agrupamento != 'titulo': cabec.append(Paragraph(_('Título'), h5)) cabec.append(Paragraph(_('Nome'), h5)) cabec.append(Paragraph(_('Endereço'), h5)) cabec.append(Paragraph(_('Telefone'), h5)) where = self.object_list.query.where for p in self.object_list.all(): contatos_query = [] item = [] label_agrupamento = '' if not p or isinstance(p, str): label_agrupamento = dict( ContatoAgrupadoPorProcessoFilterSet.AGRUPAMENTO_CHOICE) label_agrupamento = force_text(label_agrupamento[agrupamento]) if not data: tit_relatorio = _('Relatório de Contatos e Processos') tit_relatorio = force_text(tit_relatorio) + ' ' + ( (force_text(_('Agrupados')) + ' ' + label_agrupamento) if label_agrupamento else (force_text(_('Sem Agrupamento')) + ' ' + label_agrupamento)) data.append([Paragraph(tit_relatorio, h3)]) if not label_agrupamento: data.append(cabec) if not p or isinstance(p, str): data.append([]) data.append([ Paragraph((label_agrupamento + ' - ' + str(p)) if p else (force_text(_('Sem Agrupamento')) + ' ' + label_agrupamento), h4) ]) data.append(cabec) p_filter = (('processo_set__' + agrupamento, p), ) if not p: p_filter = ((p_filter[0][0] + '__isnull', True), (p_filter[0][0] + '__exact', '')) q = Q() for filtro in p_filter: filtro_dict = {filtro[0]: filtro[1]} q = q | Q(**filtro_dict) contatos_query = Contato.objects.all() contatos_query.query.where = where.clone() contatos_query = contatos_query.filter(q) params = {self.container_field: self.request.user.pk} contatos_query = contatos_query.filter(**params) contatos_query = contatos_query.order_by( 'processo_set__' + agrupamento, 'processo_set__data', 'nome', 'endereco_set__bairro__nome', 'endereco_set__endereco').distinct( 'processo_set__' + agrupamento, 'processo_set__data', 'nome') else: item = [ Paragraph(p.data.strftime('%d/%m/%Y'), s_center), Paragraph( str(p.titulo) if len(p.titulo) < MAX_TITULO else p.titulo[:MAX_TITULO] + force_text(_(' (Continua...)')), s if len(p.titulo) < MAX_TITULO else s_min) ] contatos_query = p.contatos.all() contatos = [] enderecos = [] telefones = [] for contato in contatos_query: if agrupamento: contatos = [] enderecos = [] telefones = [] item = [] if contatos: contatos.append(Paragraph('--------------', s_center)) enderecos.append(Paragraph('--------------', s_center)) telefones.append(Paragraph('--------------', s_center)) contatos.append(Paragraph(str(contato.nome), s)) endpref = contato.endereco_set.filter( preferencial=True).first() endereco = '' if endpref: endereco = endpref.endereco +\ (' - ' + endpref.numero if endpref.numero else '') +\ (' - ' + endpref.complemento if endpref.complemento else '') endereco = '%s - %s - %s - %s' % ( endereco, endpref.bairro if endpref.bairro else '', endpref.municipio.nome if endpref.municipio else '', endpref.uf) enderecos.append(Paragraph(endereco, s)) tels = '\n'.join( map(lambda x: str(x), list(contato.telefone_set.all())) ) if contato.telefone_set.exists() else '' telefones.append((Paragraph(tels, s_center))) if agrupamento: params = { 'contatos': contato, self.container_field: self.request.user.pk } processos = Processo.objects.all() processos.query.where = where.clone() processos = processos.filter(**params) ps = None data_abertura = [] titulo = [] for ps in processos: if data_abertura: data_abertura.append( Paragraph('--------------', s_center)) if agrupamento != 'titulo': titulo.append( Paragraph('--------------', s_center)) data_abertura.append( Paragraph(ps.data.strftime('%d/%m/%Y'), s_center)) if agrupamento != 'titulo': titulo.append( Paragraph( str(ps.titulo) if len(ps.titulo) < MAX_TITULO else ps.titulo[:MAX_TITULO] + force_text(_(' (Continua...)')), s if len(ps.titulo) < MAX_TITULO else s_min)) if not ps: data_abertura.append(Paragraph('-----', s_center)) if agrupamento != 'titulo': titulo.append(Paragraph('-----', s_center)) if len(data_abertura) == 1: item += data_abertura if agrupamento != 'titulo': item += titulo else: item.append(data_abertura) if agrupamento != 'titulo': item.append(titulo) item.append(contatos[0]) item.append(enderecos[0]) item.append(telefones[0]) data.append(item) """if len(data) > 2000: return data""" if not agrupamento: if len(contatos) == 0: item.append('-----') else: item.append(contatos) item.append(enderecos) item.append(telefones) data.append(item) """if len(data) > 2000: return data""" return data
def append_para(self, text, in_style='Normal', bulletText=None): if type(text) in (ListType, TupleType): text = ''.join([self.encode(t) for t in text]) style = self.styleSheet[in_style] self.story.append(Paragraph(self.encode(text), style, \ bulletText=bulletText, context=self.styleSheet))
def build_pdf(self, response): CONTATO = 0 TELEFONES_PREFERENCIAL = 1 CIDADE = 0 ENDERECO = 1 BAIRRO = 2 NUMERO = 3 GRUPO = 4 ID = 5 NOME = 6 self.set_headings() self.set_styles() self.set_cabec(self.h5) estilo = self.h_style corpo_relatorio = [] self.add_relat_title(corpo_relatorio) registros = self.get_data() for dados in registros: endereco = ','.join(dados[CONTATO][ENDERECO:NUMERO]) item = [ Paragraph(dados[CONTATO][CIDADE], estilo), Paragraph(dados[CONTATO][GRUPO], estilo), Paragraph(dados[CONTATO][NOME], estilo), Paragraph(endereco, estilo), Paragraph(dados[TELEFONES_PREFERENCIAL], estilo), ] corpo_relatorio.append(item) style = TableStyle([ ('FONTSIZE', (0, 0), (-1, -1), 8), ('LEADING', (0, 0), (-1, -1), 7), ('GRID', (0, 0), (-1, -1), 0.1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('LEFTPADDING', (0, 0), (-1, -1), 3), ('RIGHTPADDING', (0, 0), (-1, -1), 3), ]) style.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE') for i, value in enumerate(corpo_relatorio): if len(value) <= 1: style.add('SPAN', (0, i), (-1, i)) if len(value) == 0: style.add('INNERGRID', (0, i), (-1, i), 0, colors.black), style.add('GRID', (0, i), (-1, i), -1, colors.white) style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black) if len(value) == 1: style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black) rowHeights = 20 t = LongTable(corpo_relatorio, rowHeights=rowHeights, splitByRow=True) t.setStyle(style) if len(t._argW) == 5: t._argW[0] = 1.8 * cm t._argW[1] = 6 * cm t._argW[2] = 6.5 * cm t._argW[3] = 9.5 * cm t._argW[4] = 2.4 * cm elif len(t._argW) == 4: t._argW[0] = 2 * cm t._argW[1] = 10 * cm t._argW[2] = 11.5 * cm t._argW[3] = 3 * cm for i, value in enumerate(corpo_relatorio): if len(value) == 0: t._argH[i] = 7 continue for cell in value: if isinstance(cell, list): t._argH[i] = (rowHeights) * (len(cell) - (0 if len(cell) > 1 else 0)) break elements = [t] doc = SimpleDocTemplate(response, pagesize=landscape(A4), rightMargin=1.25 * cm, leftMargin=1.25 * cm, topMargin=1.1 * cm, bottomMargin=0.8 * cm) doc.build(elements)
def set_body_data(self, where, contatos_query, data, item): contatos = [] enderecos = [] telefones = [] for contato in contatos_query: if self.agrupamento: contatos = [] enderecos = [] telefones = [] item = [] if contatos: contatos.append(Paragraph('--------------', self.s_center)) enderecos.append(Paragraph('--------------', self.s_center)) telefones.append(Paragraph('--------------', self.s_center)) contatos.append(Paragraph(str(contato.nome), self.h_style)) endpref = contato.endereco_set.filter(preferencial=True).first() endereco = '' if endpref: endereco = endpref.endereco + \ (' - ' + endpref.numero if endpref.numero else '') + \ (' - ' + endpref.complemento if endpref.complemento else '') endereco = '%s - %s - %s - %s' % ( endereco, endpref.bairro if endpref.bairro else '', endpref.municipio.nome if endpref.municipio else '', endpref.uf) enderecos.append(Paragraph(endereco, self.h_style)) tels = '\n'.join( map(lambda x: str(x), list(contato.telefone_set.all())) ) if contato.telefone_set.exists() else '' telefones.append((Paragraph(tels, self.s_center))) if self.agrupamento: params = { 'contatos': contato, self.container_field: self.request.user.pk } processos = Processo.objects.all() processos.query.where = where.clone() processos = processos.filter(**params) ps = None data_abertura = [] titulo = [] for ps in processos: if data_abertura: data_abertura.append( Paragraph('--------------', self.s_center)) if self.agrupamento != 'titulo': titulo.append( Paragraph('--------------', self.s_center)) data_abertura.append( Paragraph(ps.data.strftime('%d/%m/%Y'), self.s_center)) if self.agrupamento != 'titulo': if len(ps.titulo) < self.MAX_TITULO: paragrafo = str(ps.titulo) estilo = self.h_style else: paragrafo = (ps.titulo[:self.MAX_TITULO] + force_text(_(' (Continua...)'))) estilo = self.s_min titulo.append(Paragraph(paragrafo, estilo)) if not ps: data_abertura.append(Paragraph('-----', self.s_center)) if self.agrupamento != 'titulo': titulo.append(Paragraph('-----', self.s_center)) if len(data_abertura) == 1: item += data_abertura if self.agrupamento != 'titulo': item += titulo else: item.append(data_abertura) if self.agrupamento != 'titulo': item.append(titulo) item.append(contatos[0]) item.append(enderecos[0]) item.append(telefones[0]) data.append(item) if not self.agrupamento: if len(contatos) == 0: item.append('-----') else: item.append(contatos) item.append(enderecos) item.append(telefones) data.append(item)
def createParagraphs(self, contato, stylesheet): cleaned_data = self.filterset.form.cleaned_data imprimir_cargo = (cleaned_data['imprimir_cargo'] == 'True')\ if 'imprimir_cargo' in cleaned_data and\ cleaned_data['imprimir_cargo'] else False local_cargo = cleaned_data['local_cargo']\ if 'local_cargo' in cleaned_data and\ cleaned_data['local_cargo'] else '' story = [] linha_pronome = '' prefixo_nome = '' if contato.pronome_tratamento: if 'imprimir_pronome' in cleaned_data and\ cleaned_data['imprimir_pronome'] == 'True': linha_pronome = getattr( contato.pronome_tratamento, 'enderecamento_singular_%s' % lower(contato.sexo)) prefixo_nome = getattr( contato.pronome_tratamento, 'prefixo_nome_singular_%s' % lower(contato.sexo)) if local_cargo == ImpressoEnderecamentoContatoFilterSet.DEPOIS_PRONOME\ and imprimir_cargo and (linha_pronome or contato.cargo): linha_pronome = '%s - %s' % (linha_pronome, contato.cargo) if linha_pronome: story.append(Paragraph(linha_pronome, stylesheet['pronome_style'])) linha_nome = '%s %s' % (prefixo_nome, contato.nome)\ if prefixo_nome else contato.nome if local_cargo == ImpressoEnderecamentoContatoFilterSet.LINHA_NOME\ and imprimir_cargo: linha_nome = '%s %s' % (contato.cargo, linha_nome) linha_nome = linha_nome.strip() linha_nome = linha_nome.upper()\ if 'nome_maiusculo' in cleaned_data and\ cleaned_data['nome_maiusculo'] == 'True' else linha_nome story.append(Paragraph(linha_nome, stylesheet['nome_style'])) if local_cargo == ImpressoEnderecamentoContatoFilterSet.DEPOIS_NOME\ and imprimir_cargo and contato.cargo: story.append(Paragraph(contato.cargo, stylesheet['endereco_style'])) endpref = contato.endereco_set.filter(preferencial=True).first() if endpref: endereco = endpref.endereco +\ (' - ' + endpref.numero if endpref.numero else '') +\ (' - ' + endpref.complemento if endpref.complemento else '') story.append(Paragraph(endereco, stylesheet['endereco_style'])) b_m_uf = '%s - %s - %s' % (endpref.bairro if endpref.bairro else '', endpref.municipio.nome if endpref.municipio else '', endpref.uf) story.append(Paragraph(b_m_uf, stylesheet['endereco_style'])) story.append(Paragraph(endpref.cep, stylesheet['endereco_style'])) return story
def _build_invoices(prestations, invoice_number, invoice_date, prescription_date, accident_id, accident_date, patient_invoice_date, patient): # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. elements = [] i = 0 data = [] patientSocNumber = '' patientNameAndFirstName = '' patientName = '' patient_first_name = '' patient_address = '' data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'CNS', 'Part. Client')) for presta in prestations: i += 1 patientSocNumber = patient.code_sn patientNameAndFirstName = patient patientName = patient.name patient_first_name = patient.first_name patient_address = patient.address patientZipCode = patient.zipcode patientCity = patient.city data.append(( i, presta.carecode.code, (presta.date).strftime('%d/%m/%Y'), '1', presta.carecode.gross_amount(presta.date), presta.carecode.net_amount( presta.date, patient.is_private, patient.participation_statutaire and patient.age > 18), "%10.2f" % (decimal.Decimal(presta.carecode.gross_amount(presta.date)) - decimal.Decimal( presta.carecode.net_amount(presta.date, patient.is_private, patient.participation_statutaire))) )) for x in range(len(data), 22): data.append((x, '', '', '', '', '', '')) newData = [] for y in range(0, len(data) - 1): newData.append(data[y]) if (y % 10 == 0 and y != 0): _gross_sum = _compute_sum(data[y - 9:y + 1], 4) _net_sum = _compute_sum(data[y - 9:y + 1], 5) _part_sum = _compute_sum(data[y - 9:y + 1], 6) newData.append(('', '', '', 'Sous-Total', "%10.2f" % _gross_sum, "%10.2f" % _net_sum, "%10.2f" % _part_sum)) _total_facture = _compute_sum(data[1:], 5) _participation_personnelle = decimal.Decimal(_compute_sum( data[1:], 4)) - decimal.Decimal(_total_facture) newData.append(('', '', '', 'Total', "%10.2f" % _compute_sum(data[1:], 4), "%10.2f" % _compute_sum(data[1:], 5), "%10.2f" % _compute_sum(data[1:], 6))) headerData = [ [ 'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n' + 'Regine SIMBA\n' + '1A, rue fort wallis\n' + 'L-2714 Luxembourg\n' + u"Tél: 691.30.85.84", 'CODE DU FOURNISSEUR DE SOINS DE SANTE\n' + '300744-44' ], [ u'Matricule patient: %s' % smart_text(patientSocNumber.strip()) + "\n" + u'Nom et Pr' + smart_text("e") + u'nom du patient: %s' % smart_text(patientNameAndFirstName), u'Nom: %s' % smart_text(patientName.strip()) + '\n' + u'Pr' + smart_text(u"é") + u'nom: %s' % smart_text(patient_first_name.strip()) + '\n' + u'Rue: %s' % patient_address.strip() + '\n' + u'Code postal: %s' % smart_text(patientZipCode.strip()) + '\n' + u'Ville: %s' % smart_text(patientCity.strip()) ], [ u'Date accident: %s\n' % (accident_date if accident_date else "") + u'Num. accident: %s' % (accident_id if accident_id else "") ] ] headerTable = Table(headerData, 2 * [10 * cm], [2.5 * cm, 1 * cm, 1.5 * cm]) headerTable.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('SPAN', (1, 1), (1, 2)), ])) table = Table(newData, 9 * [2.5 * cm], 24 * [0.5 * cm]) table.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, -1), (-6, -1), 'RIGHT'), ('INNERGRID', (0, -1), (-6, -1), 0, colors.white), ('ALIGN', (0, -2), (-6, -2), 'RIGHT'), ('INNERGRID', (0, -2), (-6, -2), 0, colors.white), ('FONTSIZE', (0, 0), (-1, -1), 8), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) elements.append(headerTable) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) elements.append(Spacer(1, 18)) if (prescription_date is not None): elements.append( Paragraph( u"Mémoire d'Honoraires Num. %s en date du : %s Ordonnance du %s " % (invoice_number, invoice_date, prescription_date), styles['Heading4'])) else: elements.append( Paragraph( u"Mémoire d'Honoraires Num. %s en date du : %s " % (invoice_number, invoice_date), styles['Heading4'])) elements.append(Spacer(1, 18)) elements.append(table) elements.append(Spacer(1, 18)) _total_a_payer = Table([[ "Total participation personnelle:", "%10.2f Euros" % _participation_personnelle ]], [10 * cm, 5 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(Spacer(1, 18)) elements.append(_total_a_payer) elements.append(Spacer(1, 18)) elements.append(Spacer(1, 10)) if patient_invoice_date is not None: from utils import setlocale with setlocale('en_GB.utf8'): if isinstance(patient_invoice_date, unicode): elements.append( Table([[ u"Date envoi de la présente facture: %s " % patient_invoice_date.strftime('%d %B %Y').encode( 'utf-8') ]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT')) else: elements.append( Table([[ u"Date envoi de la présente facture: %s " % patient_invoice_date.strftime('%d %B %Y').decode( 'utf-8') ]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT')) elements.append(Spacer(1, 10)) return { "elements": elements, "invoice_number": invoice_number, "patient_name": patientName + " " + patient_first_name, "invoice_amount": newData[23][5], "invoice_pp": newData[23][6] }
def generate_road_book_2016(modeladmin, request, queryset): import datetime # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') now = timezone.now() response[ 'Content-Disposition'] = 'attachment; filename="road-book-2016-%s.pdf"' % now.strftime( '%d-%m-%Y') name_map = {'zipcode': 'zipcode', 'address': 'address', 'pk': 'id'} allyear_patients = Patient.objects.raw( "select prst.date,p.* from invoices_invoiceitem pr, invoices_patient p, invoices_carecode cc, invoices_prestation prst where cc.id = prst.carecode_id and cc.code like '%NF%' and pr.patient_id = p.id and prst.date >= '2016-01-01' and prst.date <= '2016-12-31' and prst.invoice_item_id = pr.id group by prst.date,p.id order by prst.date asc" ) from django.db import connection with connection.cursor() as cursor: cursor.execute( "select prst.date,p.* from invoices_invoiceitem pr, invoices_patient p, invoices_carecode cc, invoices_prestation prst where cc.id = prst.carecode_id and cc.code like '%NF%' and pr.patient_id = p.id and prst.date >= '2016-01-01' and prst.date <= '2016-12-31' and prst.invoice_item_id = pr.id group by prst.date,p.id order by prst.date asc" ) row = cursor.fetchall() elements = [] data = [] #data.append(('Nom Patient', 'Adresse', 'Date', 'Distance')) import csv # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="roadbook2016.csv"' writer = csv.writer(response) writer.writerow(['Nom Patient', 'Adresse', 'Date', 'Distance']) sumdistance = 0 counter = 1 for p in row: counter = counter + 1 if counter == 5: break _patient_address = u"%s %s, %s" % (p[5], p[6], p[7]) if now != p[0]: _point_start = "1A rue fort wallis,Luxembourg" else: _point_start = _point_start now = p[0] _point_end = _patient_address r = requests.get( 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=fort%s&destinations=%s&mode=car&language=en-EN&sensor=false' % (_point_start, _point_end)) if r.status_code == 200 and 'OK' == r.json()['status'] and r.json( )['rows'][0]['elements'][0]['status'] != u'NOT_FOUND': pdistance = r.json()['rows'][0]['elements'][0]['distance']['text'] sumdistance += r.json( )['rows'][0]['elements'][0]['distance']['value'] elif r.status_code == 200 and 'OK' == r.json()['status'] and r.json( )['rows'][0]['elements'][0]['status'] == u'NOT_FOUND': _point_start = p[7] r = requests.get( 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=fort%s&destinations=%s&mode=car&language=en-EN&sensor=false' % (_point_start, _point_end)) # should be 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=fort%s&destinations=%s&mode=car&language=en-EN&sensor=false&key=XXXX' % (_point_start, _point_end)) if r.status_code == 200 and 'OK' == r.json()['status'] and r.json( )['rows'][0]['elements'][0]['status'] != u'NOT_FOUND': pdistance = r.json( )['rows'][0]['elements'][0]['distance']['text'] sumdistance += r.json( )['rows'][0]['elements'][0]['distance']['value'] else: pdistance = 0 _point_end = _point_start # Log an error message eprint('Something went wrong!', r.json()['status'], r.json()['status'] and r.json()['rows'][0]['elements'][0]['status'], "p.end:" + _point_end, "p.start:" + _point_start, r.json()['rows'][0]['elements'][0], sep='--') else: pdistance = 0 _point_end = _point_start # Log an error message eprint('Something went wrong!', r.json()['status'], r.json()['status'] and r.json()['rows'][0]['elements'][0]['status'], "p.end:" + _point_end, "p.start:" + _point_start, r.json()['rows'][0]['elements'][0], sep='--') writer.writerow([ p[4] + ' ' + p[3], _patient_address, (p[0]).strftime('%d/%m/%Y %H:%M'), pdistance ]) _point_start = _point_end table = Table(data, [7 * cm, 9 * cm, 2.5 * cm, 2 * cm], len(data) * [0.8 * cm]) table.setStyle( TableStyle([ ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, -1), (-6, -1), 'RIGHT'), ('ALIGN', (0, -2), (-6, -2), 'RIGHT'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) elements.append( Paragraph(u"Livre de bord pour l'année 2016 (génération automatique)", styles['Center'])) elements.append(table) elements.append(Spacer(1, 18)) elements.append( Paragraph( "La distance totale parcourue en 2016 est de %s KM" % (sumdistance / 1000), styles['Center'])) doc = SimpleDocTemplate(response, pagesize=letter, rightMargin=2 * cm, leftMargin=2 * cm, topMargin=1 * cm, bottomMargin=1 * cm) #doc.build(elements) return response
def factura(request, pk, pago, vuelto): #Create the HttpResponse headers with PDF response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="reporte-reserva.pdf"' #Create the pdf object, using the BytesIO object as its "file." buffer = BytesIO() c = canvas.Canvas(buffer, pagesize=A4) # Tabla Reservas reserva = Reserva.objects.get(id_reserva=pk) detalle_venta_prod = reserva.detalle_venta_prod.all() # Header c.setLineWidth(.3) c.setFont('Helvetica', 22) c.drawString(30,750,'Hotel Amanecer') c.setFont('Helvetica', 12) c.drawString(30,730, f'{"Factura - "} {reserva.id_reserva}') c.drawString(30,710, f'{"Costo de Alojamiento: "} {reserva.tag_costo_alojamiento()}') c.drawString(300,710, f'{"Consumo: "} {reserva.tag_total_consumo()}') c.drawString(30,690, f'{"Total: "} {reserva.tag_total()}') c.drawString(30,670, f'{"Total Abonado: "} {reserva.tag_total_pagos()}') c.drawString(300,670, f'{"Saldo Pendiente: "} {reserva.tag_saldo_pendiente()}') #c.drawString(30,675, f'{"Monto Pagado: "} {"..."}') #c.drawString(300,675, f'{"Vuelto: "} {"..."}') c.setFont('Helvetica-Bold', 12) c.drawString(480,750, str(datetime.date.today())) # start X, height end y, heigth c.line(460, 747, 560, 747) # Table header styles = getSampleStyleSheet() styleBH = styles["Normal"] styleBH.alignment = TA_CENTER styleBH.fontSize = 18 producto = Paragraph('''Producto''', styleBH) cantidad = Paragraph('''Cantidad''', styleBH) precio = Paragraph('''Precio''', styleBH) subtotal = Paragraph('''Subtotal''', styleBH) data = [] data.append([producto, cantidad, precio, subtotal]) # Table body styleN = styles["Normal"] styleN.alignment = TA_CENTER styleN.fontSize = 7 high = 630 for consumo in detalle_venta_prod: this_consumo = [consumo.id_producto_fk, consumo.tag_cantidad(), consumo.tag_precio(), consumo.tag_sub_total() ] data.append(this_consumo) high = high - 18 # Table size width, height = A4 table = Table(data, colWidths=[4.75 * cm, 4.75 * cm, 4.75 * cm, 4.75 * cm, 4.75 * cm]) table.setStyle(TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) # Pdf size table.wrapOn(c, width, height) table.drawOn(c, 30, high) high = high - 35 c.drawString(30,high, f'{"Monto Pagado: "} {pago}') if int(vuelto) > 0: c.drawString(300,high, f'{"Vuelto: "} {vuelto}') # End writing c.showPage() c.save() # get the value of BytesIO buffer and write response pdf = buffer.getvalue() buffer.close() response.write(pdf) return response