def wrap(self, availWidth, availHeight): self.setMaxHeight(availHeight) # Strange bug, sometime the totalWidth is not set !? try: self.totalWidth except: self.totalWidth = availWidth # Prepare values totalWidth = self._normWidth(self.totalWidth, availWidth) remainingWidth = totalWidth remainingCols = 0 newColWidths = self._colWidths #print #print "TABLE", newColWidths # Calculate widths that are fix # IMPORTANT!!! We can not substitute the private value # self._colWidths therefore we have to modify list in place for i, colWidth in enumerate(newColWidths): if (colWidth is not None) or (colWidth == '*'): colWidth = self._normWidth(colWidth, totalWidth) remainingWidth -= colWidth else: remainingCols += 1 colWidth = None newColWidths[i] = colWidth # Distribute remaining space minCellWidth = totalWidth * 0.01 if remainingCols > 0: for i, colWidth in enumerate(newColWidths): if colWidth is None: # print "*** ", i, newColWidths[i], remainingWidth, remainingCols newColWidths[i] = max(minCellWidth, remainingWidth / remainingCols) # - 0.1 # Bigger than totalWidth? Lets reduce the fix entries propotionally # print "New values:", totalWidth, newColWidths, sum(newColWidths) # Call original method "wrap()" # self._colWidths = newColWidths if sum(newColWidths) > totalWidth: quotient = totalWidth / sum(newColWidths) # print quotient for i in range(len(newColWidths)): newColWidths[i] = newColWidths[i] * quotient # To avoid rounding errors adjust one col with the difference diff = sum(newColWidths) - totalWidth if diff > 0: newColWidths[0] -= diff # print "New values:", totalWidth, newColWidths, sum(newColWidths) return Table.wrap(self, availWidth, availHeight)
def create_detail(self): self.layout.append(Spacer(0, 20)) detail = Table([(key, ': {value}'.format(value=value)) for key, value in self.detail.items()], hAlign='LEFT') print(detail.wrap(0, 0)) self.layout.append(detail)
def _header_footer(self, canvas, doc): """ Renders a header and footer which will be inserted regardless of pdf method""" # Save the state of our canvas so we can draw on it canvas.saveState() stylesheet = getSampleStyleSheet() # Header logo = Image("http://www.fabco.la/fabco-seal-1.png", width=1.5*inch, height=1.5*inch) logo.hAlign = 'CENTER' stylesheet['BodyText'].fontSize = 10 stylesheet['BodyText'].leading = 14 stylesheet['BodyText'].leftIndent = 5 stylesheet['BodyText'].textColor = 'gray' FabcoAddress = "Fabco Art Services\n166 West Avenue 34\nLos Angeles CA 90031" project = get_object_or_404(Project, pk=self.pk) rightHeader = "Job #%s\nCompletion Date %s" % (project.project_id, project.due_date) # Build and format Left Header Table: leftHeaderData = [[FabcoAddress], [project.client.first_name + ' ' + project.client.last_name+'\n'+project.client.address.street+'\n'+project.client.address.city + ' ' + project.client.address.zip_code], ] leftHeaderTable = Table(leftHeaderData) leftHeaderTable.setStyle(TableStyle([ ('LEFTPADDING',(0,0),(0, 1),0), ('TOPPADDING',(0,1),(0, 1), 30), ('BOTTOMPADDING',(0,1),(0, 1), 0), ])) # Build and format Header Table: headerData = [([leftHeaderTable, logo, rightHeader])] headerTable = Table(headerData, colWidths=doc.width/3) headerTable.setStyle(TableStyle([ ('VALIGN', (0, 0), (-3, 0), 'MIDDLE'), ('VALIGN', (0, 0), (0, 0), 'TOP'), ('ALIGN',(1,0),(1,0),'CENTER'), ('ALIGN',(2,0),(2,0),'RIGHT'), ('LEFTPADDING',(0,0),(0,0),-1), ('RIGHTPADDING',(2,0),(2,0),-1), ])) # find required space | I don't really understand this.. w, h = headerTable.wrap(doc.width, doc.height) # render to canvas | I also don't really understand this.. headerTable.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - doc.bottomMargin) # Footer footer = Paragraph('Client Signature: _________________________', stylesheet['Normal']) w, h = footer.wrap(doc.width, doc.bottomMargin) footer.drawOn(canvas, doc.leftMargin, doc.bottomMargin) # Release the canvas canvas.restoreState()
def draw_totals(self, y_pos): """ Draws the boxes containing the totals and the tax id. """ totals_data = [[(_('Total')), self.total_cost], [(_('Payment Received')), self.payment_received], [(_('Balance')), self.balance]] if self.is_invoice: # only print TaxID if we are generating an Invoice totals_data.append([ '', '{tax_label}: {tax_id}'.format(tax_label=self.tax_label, tax_id=self.tax_id) ]) heights = 8 * mm totals_table = Table(totals_data, 40 * mm, heights) styles = [ # Styling for the totals table. ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), # Styling for the Amounts cells # NOTE: since we are not printing the TaxID for Credit Card # based receipts, we need to change the cell range for # these formatting rules ('RIGHTPADDING', (-1, 0), (-1, -2 if self.is_invoice else -1), 7 * mm), ('GRID', (-1, 0), (-1, -2 if self.is_invoice else -1), 3.0, colors.white), ('BACKGROUND', (-1, 0), (-1, -2 if self.is_invoice else -1), '#EEEEEE'), ] totals_table.setStyle(TableStyle(styles)) __, rendered_height = totals_table.wrap(0, 0) left_padding = 97 * mm if y_pos - (self.margin + self.min_clearance) <= rendered_height: # if space left on page is smaller than the rendered height, render the table on the next page. self.prepare_new_page() totals_table.drawOn(self.pdf, self.margin + left_padding, self.second_page_start_y_pos - rendered_height) return self.second_page_start_y_pos - rendered_height - self.min_clearance else: totals_table.drawOn(self.pdf, self.margin + left_padding, y_pos - rendered_height) return y_pos - rendered_height - self.min_clearance
def draw_totals(self, y_pos): """ Draws the boxes containing the totals and the tax id. """ totals_data = [ [(_('Total')), self.total_cost], [(_('Payment Received')), self.payment_received], [(_('Balance')), self.balance] ] if self.is_invoice: # only print TaxID if we are generating an Invoice totals_data.append( ['', u'{tax_label}: {tax_id}'.format(tax_label=self.tax_label, tax_id=self.tax_id)] ) heights = 8 * mm totals_table = Table(totals_data, 40 * mm, heights) styles = [ # Styling for the totals table. ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), # Styling for the Amounts cells # NOTE: since we are not printing the TaxID for Credit Card # based receipts, we need to change the cell range for # these formatting rules ('RIGHTPADDING', (-1, 0), (-1, 2), 7 * mm), ('GRID', (-1, 0), (-1, 2), 3.0, colors.white), ('BACKGROUND', (-1, 0), (-1, 2), '#EEEEEE'), ] totals_table.setStyle(TableStyle(styles)) __, rendered_height = totals_table.wrap(0, 0) left_padding = 97 * mm if y_pos - (self.margin + self.min_clearance) <= rendered_height: # if space left on page is smaller than the rendered height, render the table on the next page. self.prepare_new_page() totals_table.drawOn(self.pdf, self.margin + left_padding, self.second_page_start_y_pos - rendered_height) return self.second_page_start_y_pos - rendered_height - self.min_clearance else: totals_table.drawOn(self.pdf, self.margin + left_padding, y_pos - rendered_height) return y_pos - rendered_height - self.min_clearance
def wrap(self, availWidth, availHeight): # Strange bug, sometime the totalWidth is not set !? try: self.totalWidth except: self.totalWidth = availWidth # Prepare values totalWidth = self._normWidth(self.totalWidth, availWidth) remainingWidth = totalWidth remainingCols = 0 newColWidths = self._colWidths # Calculate widths that are fix # IMPORTANT!!! We can not substitute the private value # self._colWidths therefore we have to modify list in place for i in range(len(newColWidths)): colWidth = newColWidths[i] if (colWidth is not None) or (colWidth == '*'): colWidth = self._normWidth(colWidth, totalWidth) remainingWidth -= colWidth else: remainingCols += 1 colWidth = None newColWidths[i] = (colWidth) # Distribute remaining space if remainingCols: for i in range(len(newColWidths)): if newColWidths[i] is None: newColWidths[i] = (remainingWidth / remainingCols) - 0.1 # print "New values:", totalWidth, newColWidths, sum(newColWidths) # Call original method "wrap()" # self._colWidths = newColWidths return Table.wrap(self, availWidth, availHeight)
def wrap(self, availWidth, availHeight): # Strange bug, sometime the totalWidth is not set !? try: self.totalWidth except: self.totalWidth = availWidth # Prepare values totalWidth = self._normWidth(self.totalWidth, availWidth) remainingWidth = totalWidth remainingCols = 0 newColWidths = self._colWidths # Calculate widths that are fix # IMPORTANT!!! We can not substitute the private value # self._colWidths therefore we have to modify list in place for i in range(len(newColWidths)): colWidth = newColWidths[i] if (colWidth is not None) or (colWidth=='*'): colWidth = self._normWidth(colWidth, totalWidth) remainingWidth -= colWidth else: remainingCols += 1 colWidth = None newColWidths[i] = (colWidth) # Distribute remaining space if remainingCols: for i in range(len(newColWidths)): if newColWidths[i] is None: newColWidths[i] = (remainingWidth / remainingCols) - 0.1 # print "New values:", totalWidth, newColWidths, sum(newColWidths) # Call original method "wrap()" # self._colWidths = newColWidths return Table.wrap(self, availWidth, availHeight)
def draw_totals(self, y_pos): """ Draws the boxes containing the totals and the tax id. """ totals_data = [ [(_('Total')), self.total_cost], [(_('Payment Received')), self.payment_received], [(_('Balance')), self.balance], ['', '{tax_label}: {tax_id}'.format(tax_label=self.tax_label, tax_id=self.tax_id)] ] heights = 8 * mm totals_table = Table(totals_data, 40 * mm, heights) totals_table.setStyle(TableStyle([ # Styling for the totals table. ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), # Styling for the Amounts cells ('RIGHTPADDING', (-1, 0), (-1, -2), 7 * mm), ('GRID', (-1, 0), (-1, -2), 3.0, colors.white), ('BACKGROUND', (-1, 0), (-1, -2), '#EEEEEE'), ])) __, rendered_height = totals_table.wrap(0, 0) left_padding = 97 * mm if y_pos - (self.margin + self.min_clearance) <= rendered_height: # if space left on page is smaller than the rendered height, render the table on the next page. self.prepare_new_page() totals_table.drawOn(self.pdf, self.margin + left_padding, self.second_page_start_y_pos - rendered_height) return self.second_page_start_y_pos - rendered_height - self.min_clearance else: totals_table.drawOn(self.pdf, self.margin + left_padding, y_pos - rendered_height) return y_pos - rendered_height - self.min_clearance
class Signatories(Flowable): def __init__(self, master, margin=10): Flowable.__init__(self) self.master = master self.margin = 10 if master.medical_technologist or master.pathologist: self.has_data = True else: self.has_data = False def split(self, availWidth, availHeight): return [] def wrap(self, availWidth, availHeight): return self.do_table_wrap(availWidth, availHeight) def do_table_wrap(self, availWidth, availHeight): styles = getSampleStyleSheet() sN = styles['Normal'] sN.alignment = TA_CENTER data = [["" for x in range(12)] for y in range(3)] data[0][1] = Paragraph("<br/><br/><strong>%s</strong>" % self.master.pathologist.fullname, sN) data[1][1] = Paragraph(self.master.pathologist. get_designation_display(), sN) data[2][1] = Paragraph("PRC LIC #: %s" % self.master.pathologist.license, sN) data[0][7] = Paragraph("<br/><br/><br/><strong>%s</strong>" % self.master.medical_technologist.fullname, sN) data[1][7] = Paragraph(self.master.medical_technologist. get_designation_display(), sN) data[2][7] = Paragraph("PRC LIC #: %s" % self.master.medical_technologist.license, sN) w = availWidth - self.margin * 2 spacer = int(w * 0.05) remWidth = (w - (spacer * 4)) / 8 colWidths = [spacer] + \ [remWidth] * 4 + \ [spacer] * 2 + \ [remWidth] * 4 + \ [spacer] self.table = Table(data, colWidths=colWidths) self.table.setStyle(TableStyle([ # config padding ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), # lines ('LINEBELOW', (1, 0), (4, 0), 1, black), ('LINEBELOW', (7, 0), (10, 0), 1, black), # ('GRID', (0, 0), (-1, -1), 1, black), # Column 1 ('SPAN', (1, 0), (4, 0)), ('SPAN', (1, 1), (4, 1)), ('SPAN', (1, 2), (4, 2)), # Column 2 ('SPAN', (7, 0), (10, 0)), ('SPAN', (7, 1), (10, 1)), ('SPAN', (7, 2), (10, 2)), ])) self.table.canv = self.canv return self.table.wrap(availWidth, availHeight) def draw(self): self.table.draw()
def ingresopaciente(request): fechahoy = datetime.now() ancho, alto = letter # alto=792,ancho=612 - posicion normal nom_arch = "infoingreso" + nombrearch() + ".pdf" # gestion remota # # desarrollo logo_corp = os.getcwd( ) + "\\misitio\\ai\\static\\img\\Logo_AsistenciaIntegral.jpg" c = canvas.Canvas(os.getcwd() + "\\pdfs\\" + nom_arch, pagesize=letter) # #produccion #logo_corp = os.getcwd()+"/misitio/staticfiles/img/Logo_AsistenciaIntegral.jpg" #c = canvas.Canvas(os.getcwd() +"/misitio/pdfs/"+ nom_arch, pagesize=letter) # c.setPageSize((ancho, alto)) # rut_aux = request.session['rut_x'] paciente = Pacientes.objects.get(rut=rut_aux) if paciente.fe_ini == None: return HttpResponse("Paciente no posee fecha de inicio") fe_nac = paciente.fe_nac edad_x = edad(paciente.fe_nac) # en misfunciones.py sexo_x = "Masculino" if paciente.sexo == 2: sexo_x = "Femenino" domicilio_x = paciente.direccion fono_pcte = paciente.fono_pcte fe_nac = paciente.fe_nac region_x = "(sin definir)" region = Param.objects.filter(tipo='REGI', codigo=paciente.region) for re in region: region_x = re.descrip comuna_x = "(sin definir)" comuna = Param.objects.filter(tipo='COMU', codigo=paciente.comuna) for co in comuna: comuna_x = co.descrip # produccion #path_x = os.getcwd() +"/misitio/pdfs/" # Desarrollo path_x = os.getcwd() + '\\pdfs\\' arch_y = os.listdir(path_x) for arch_pdf in arch_y: remove(path_x + arch_pdf) # ## ####comienza primera pagina ############################## y = 710 c.drawImage(logo_corp, 25, y, 190, 80) # (IMAGEN, X,Y, ANCHO, ALTO) y = 700 c.setFont('Helvetica-Bold', 11) c.drawString(198, y, "INFORME INGRESO PACIENTE") c.setFont('Helvetica', 11) # subrrayado de "informe ingreso paciente" y = y - 20 c.line( 197, y + 16, 361, y + 16 ) # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final # # y = y - 10 c.drawString(420, y, "Fecha:_____/_____/______") # y = y - 30 # DEFINICION DE PRIMERA GRID ################################### c.setFont('Helvetica-Bold', 10) c.drawString(50, 620, "Datos del paciente") c.setFont('Helvetica', 10) y = y - 15 data = [ ["Nombre completo", paciente.nombre], ["RUT", paciente.rut], ["Fecha de nacimiento", fecha_ddmmaaaa(fe_nac)], ["Edad", edad(fe_nac)], ["Sexo", sexo_x], ["Dirección", paciente.direccion], ["Comuna", comuna_x], ["Región", region_x], ["Telofono", paciente.fono_pcte], ["Apoderado del paciente", paciente.n_apod], ["Teléfono del apoderado del paciente", paciente.f_apod], ["Personas que vive en el domicilio y parentesco", ""], ] # definicion de cada columna (primera grid) t = Table(data, colWidths=[230, 280]) t.setStyle( TableStyle([ ("ALIGN", (0, 0), (-1, -1), "LEFT"), ("ALIGN", (-2, 1), (-2, -1), "LEFT"), ("GRID", (0, 0), (-1, -1), 0.25, colors.black), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ])) w, h = t.wrap(100, 100) # OBLIGAORIO t.drawOn(c, 50, 390, 0) # DIBUJA LA GRID EN MEMORIA # FIN DE DEFINICION DE PRIMERA GRID # # # # INICIA DEFINICION DE SEGUNDA GRID ################################ y = 365 c.setFont('Helvetica-Bold', 10) c.drawString(50, y, "Datos de la empresa de cuidados domiciliarios:") c.setFont('Helvetica', 10) y = y - 15 # data = [ ["Nombre empresa", ""], ["Nombre enfermera", ""], ["Telefono enfermera o coordinador de la empresa", ""], ] # Definicion de cada columna (segunda grid) t = Table(data, colWidths=[230, 280]) t.setStyle( TableStyle([ ("ALIGN", (0, 0), (-1, -1), "LEFT"), ("ALIGN", (-2, 1), (-2, -1), "LEFT"), ("GRID", (0, 0), (-1, -1), 0.25, colors.black), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ])) w, h = t.wrap(100, 100) # OBLIGAORIO t.drawOn(c, 50, 300, 0) # DIBUJA LA GRID EN MEMORIA # INICIA DEFINICION DE TERCERA GRID ################################ y = 275 c.setFont('Helvetica-Bold', 10) c.drawString(50, y, "Datos contacto:") c.setFont('Helvetica', 10) y = y - 15 # data = [ ["Contacto", ""], ["Fono contacto", ""], ["", ""], ] # Definicion de cada columna (tercera grid) t = Table(data, colWidths=[230, 280]) t.setStyle( TableStyle([ ("ALIGN", (0, 0), (-1, -1), "LEFT"), ("ALIGN", (-2, 1), (-2, -1), "LEFT"), ("GRID", (0, 0), (-1, -1), 0.25, colors.black), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ])) w, h = t.wrap(100, 100) # OBLIGAORIO t.drawOn(c, 50, 210, 0) # posiciona y DIBUJA LA GRID EN MEMORIA # INICIA DEFINICION DE CUARTA GRID ################################ y = 190 c.setFont('Helvetica-Bold', 10) c.drawString(50, y, "Datos de accidente:") c.setFont('Helvetica', 10) y = y - 15 # data = [ ["Contacto", ""], ["Fono contacto", ""], ["", ""], ] # Definicion de cada columna (cuarta grid) t = Table(data, colWidths=[230, 280]) t.setStyle( TableStyle([ ("ALIGN", (0, 0), (-1, -1), "LEFT"), ("ALIGN", (-2, 1), (-2, -1), "LEFT"), ("GRID", (0, 0), (-1, -1), 0.25, colors.black), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ])) w, h = t.wrap(100, 100) # OBLIGAORIO t.drawOn(c, 50, 125, 0) # posiciona y DIBUJA LA GRID EN MEMORIA # ##### INICIA CAJA DE COMENTARIOS ############################# c.setFont('Helvetica-Bold', 10) c.drawString(50, 105, "Comentarios de ingreso:") c.setFont('Helvetica', 10) # rectangulo c.rect(50, 50, 510, 47) ## ######## FIN DEL REPORTE #################### c.showPage() #salto de pagina c.save() #Archivamos y cerramos el canvas #Lanzamos el pdf creado os.system(nom_arch) #desarrollo return FileResponse(open(os.getcwd() + '\\pdfs\\' + nom_arch, 'rb'), content_type='application/pdf')
class DelayedTable(Table): """A flowable that inserts a table for which it has the data. Needed so column widths can be determined after we know on what frame the table will be inserted, thus making the overal table width correct. """ def __init__(self, data, colWidths, style=None, repeatrows=False, splitByRow=True): self.data = data self._colWidths = colWidths if style is None: style = TableStyle([ ('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ]) self.style = style self.t = None self.repeatrows = repeatrows self.hAlign = TA_CENTER self.splitByRow = splitByRow def wrap(self, w, h): # Create the table, with the widths from colWidths reinterpreted # if needed as percentages of frame/cell/whatever width w is. # _tw = w/sum(self.colWidths) def adjust(*args, **kwargs): kwargs['total'] = w return styles.adjustUnits(*args, **kwargs) # adjust=functools.partial(styles.adjustUnits, total=w) self.colWidths = [adjust(x) for x in self._colWidths] # colWidths = [_w * _tw for _w in self.colWidths] self.t = Table( self.data, colWidths=self.colWidths, style=self.style, repeatRows=self.repeatrows, splitByRow=True, ) # splitByRow=self.splitByRow) self.t.hAlign = self.hAlign return self.t.wrap(w, h) def split(self, w, h): if self.splitByRow: if not self.t: self.wrap(w, h) return self.t.split(w, h) else: return [] def drawOn(self, canvas, x, y, _sW=0): self.t.drawOn(canvas, x, y, _sW) def identity(self, maxLen=None): return "<%s at %s%s%s> containing: %s" % ( self.__class__.__name__, hex(id(self)), self._frameName(), getattr(self, 'name', '') and (' name="%s"' % getattr(self, 'name', '')) or '', repr(self.data[0]), )[:180]
def split(self, w, h): _w, _h = self.wrap(w, h) if _h > h: # Can't split! # The right column data mandates the split # Find which flowable exceeds the available height dw = self.colWidths[0] + self.padding[1] + self.padding[3] dh = self.padding[0] + self.padding[2] bullet = self.data[0][0] text = self.data[0][1] for l in range(0, len(text)): _, fh = _listWrapOn(text[:l + 1], w - dw, None) if fh + dh > h: # The lth flowable is the guilty one # split it _, lh = _listWrapOn(text[:l], w - dw, None) # Workaround for Issue 180 text[l].wrap(w - dw, h - lh - dh) l2 = text[l].split(w - dw, h - lh - dh) if l2 == []: # Not splittable, push some to next page if l == 0: # Can't fit anything, push all to next page return l2 # We reduce the number of items we keep on the # page for two reasons: # 1) If an item is associated with the following # item (getKeepWithNext() == True), we have # to back up to a previous one. # 2) If we miscalculated the size required on # the first page (I dunno why, probably not # counting borders properly, but we do # miscalculate occasionally). Seems to # have to do with nested tables, so it might # be the extra space on the border on the # inner table. while l > 0: if not text[l - 1].getKeepWithNext(): first_t = Table( [[bullet, text[:l]]], colWidths=self.colWidths, style=self.style, ) _w, _h = first_t.wrap(w, h) if _h <= h: break l -= 1 if l > 0: # Workaround for Issue 180 with wordaxe: # if wordaxe is not None: # l3=[Table([ # [bullet, # text[:l]] # ], # colWidths=self.colWidths, # style=self.style), # Table([['',text[l:]]], # colWidths=self.colWidths, # style=self.style)] # else: l3 = [ first_t, SplitTable( [['', text[l:]]], colWidths=self.colWidths, style=self.style, padding=self.padding, ), ] else: # Everything flows l3 = [] else: l3 = [ Table( [[bullet, text[:l] + [l2[0]]]], colWidths=self.colWidths, rowHeights=[h], style=self.style, ) ] if l2[1:] + text[l + 1:]: l3.append( SplitTable( [['', l2[1:] + text[l + 1:]]], colWidths=self.colWidths, style=self.style, padding=self.padding, )) return l3 log.debug("Can't split splittable") return self.t.split(w, h) else: return DelayedTable.split(self, w, h)
def draw_footer(self, y_pos): """ Draws the footer. """ para_style = getSampleStyleSheet()["Normal"] para_style.fontSize = 8 footer_para = Paragraph(self.footer_text.replace("\n", "<br/>"), para_style) disclaimer_para = Paragraph(self.disclaimer_text.replace("\n", "<br/>"), para_style) billing_address_para = Paragraph(self.billing_address_text.replace("\n", "<br/>"), para_style) footer_data = [ ["", footer_para], [(_("Billing Address")), ""], ["", billing_address_para], [(_("Disclaimer")), ""], ["", disclaimer_para], ] footer_style = [ # Styling for the entire footer table. ("ALIGN", (0, 0), (-1, -1), "LEFT"), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("TEXTCOLOR", (0, 0), (-1, -1), colors.black), ("FONTSIZE", (0, 0), (-1, -1), 9), ("TEXTCOLOR", (0, 0), (-1, -1), "#AAAAAA"), # Billing Address Header styling ("LEFTPADDING", (0, 1), (0, 1), 5 * mm), # Disclaimer Header styling ("LEFTPADDING", (0, 3), (0, 3), 5 * mm), ("TOPPADDING", (0, 3), (0, 3), 2 * mm), # Footer Body styling # ('BACKGROUND', (1, 0), (1, 0), '#EEEEEE'), # Billing Address Body styling ("BACKGROUND", (1, 2), (1, 2), "#EEEEEE"), # Disclaimer Body styling ("BACKGROUND", (1, 4), (1, 4), "#EEEEEE"), ] if self.is_invoice: terms_conditions_para = Paragraph(self.terms_conditions_text.replace("\n", "<br/>"), para_style) footer_data.append([(_("TERMS AND CONDITIONS")), ""]) footer_data.append(["", terms_conditions_para]) # TERMS AND CONDITIONS header styling footer_style.append(("LEFTPADDING", (0, 5), (0, 5), 5 * mm)) footer_style.append(("TOPPADDING", (0, 5), (0, 5), 2 * mm)) # TERMS AND CONDITIONS body styling footer_style.append(("BACKGROUND", (1, 6), (1, 6), "#EEEEEE")) footer_table = Table(footer_data, [5 * mm, 176 * mm]) footer_table.setStyle(TableStyle(footer_style)) __, rendered_height = footer_table.wrap(0, 0) if y_pos - (self.margin + self.min_clearance) <= rendered_height: self.prepare_new_page() footer_table.drawOn(self.pdf, self.margin, self.margin + 5 * mm)
class Detail(Flowable): def __init__(self, results, components, references, title=""): self.styles = getSampleStyleSheet() self.has_references = bool(references) self.title = title comps = components.split(',') res = results.split(',') # self.data = [["" for x in range(3)] for y in len(comps)] self.data = [] if self.has_references: ref = references.split(",") for t in zip(comps, res, ref): self.data.append(list(t)) else: for t in zip(comps, res): self.data.append(list(t)) def split(self, availWidth, availHeight): return [] # do not split def wrap(self, availWidth, availHeight): width = availWidth * .8 colwidth = width / 3 row_count = len(self.data) row_height = availHeight / row_count fontsize = int((row_height * 1000) / 2) print "row_height = ", row_height print "fontsize = ", fontsize if fontsize > 14: fontsize = 14 sH = self.styles["Heading2"] sH.fontSize = fontsize + 2 sN = self.styles["Normal"] sN.fontSize = fontsize sN.alignment = TA_CENTER fontSmall = fontsize - 4 data = [] for l in self.data: row = [] for idx, m in enumerate(l): if m: if idx == 0: sN.alignment = TA_RIGHT else: sN.alignment = TA_CENTER if idx == 2: sN.fontSize = fontSmall else: sN.fontSize = fontsize row.append(Paragraph(m, sN)) else: row.append("xxx") data.append(row) self.table = Table(data, colWidths=[colwidth]*3, hAlign='CENTER') self.table.canv = self.canv return self.table.wrap(width, availHeight) def draw(self): self.table.draw()
class MasterInfo(Flowable): KEYS = { 'master': ['patient', 'date', 'room_number', 'case_number', 'physician'], 'patient': ['fullname', 'age', 'gender'], } def process_kwarg(self, data, kwargs): for objname in self.KEYS.keys(): if objname in kwargs.keys(): o = kwargs[objname] for k in self.KEYS[objname]: display = 'get_%s_display' % k if hasattr(o, display): data[k] = getattr(o, display)() else: data[k] = getattr(o, k) del kwargs[objname] p = data.get('patient', None) for k in chain(*self.KEYS.values()): if k in kwargs.keys(): data[k] = kwargs[k] del kwargs[k] elif p and hasattr(p, k): display = 'get_%s_display' % k if hasattr(p, display): data[k] = getattr(p, display)() else: data[k] = getattr(p, k) def __init__(self, **kwargs): data = {} self.process_kwarg(data, kwargs) self.config = {} for k in ['font', 'fontsize', 'offset', 'width', 'leftmargin', 'rightmargin']: if k in kwargs: # setattr(self, k, kwargs[k]) self.config[k] = kwargs[k] del kwargs[k] if len(kwargs): raise TypeError("__init__ got an unxepected keyworkd '%s'" % kwargs.keys()[0]) self.init_table(data) def init_table(self, data): styles = getSampleStyleSheet() sN = styles['Normal'] if 'font' in self.config: sN.fontName = self.config['font'] if 'fontsize' in self.config: sN.fontSize = self.config['fontsize'] sN.leading = sN.fontSize * 1.1 cell_data = [["" for x in range(12)] for y in range(3)] # Row 1 cell_data[0][0] = Paragraph("<b>Name:</b><u> %s</u>" % data.get('fullname', 'NO_VALUE'), sN) date_type = type(data['date']) if date_type in [datetime.datetime, datetime.date]: date = datetime.datetime.strftime(data['date'], "%m/%d/%Y") else: date = data['date'] cell_data[0][6] = Paragraph("<b>Date:</b><u> %s</u>" % date, sN) cell_data[0][9] = Paragraph("<b>Case #:</b><u> %s</u>" % data.get('case_number', 'NO_VALUE'), sN) # Row 2 cell_data[1][0] = Paragraph("<b>Room #:</b><u> %s</u>" % data.get('room_number', 'NO_VALUE'), sN) cell_data[1][4] = Paragraph("<b>Age:</b><u> %s</u>" % data['age'], sN) cell_data[1][8] = Paragraph("<b>Sex:</b><u> %s</u>" % data.get('gender', 'NO_VALUE'), sN) # Row 3 cell_data[2][0] = Paragraph("<b>Requesting Physician:</b><u> %s</u>" % data.get('physician', 'NO_VALUE'), sN) if 'width' in self.config: width = self.config['width'] else: width, height = landscape(A5) self.config['width'] = width lm = self.config.get('leftmargin', 10) rm = self.config.get('rightmargin', 10) width -= lm + rm self.table = Table(cell_data, colWidths=[width/12]*12) self.table.setStyle(TableStyle([ # ('GRID', (0, 0), (-1, -1), 1, black), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, -1), (0, -1), 3), ('LINEBELOW', (0, -1), (-1, -1), 1, black), # Row 1 ('SPAN', (0, 0), (5, 0)), ('SPAN', (6, 0), (8, 0)), ('SPAN', (9, 0), (11, 0)), # Row 2 ('SPAN', (0, 1), (3, 1)), ('SPAN', (4, 1), (7, 1)), ('SPAN', (8, 1), (11, 1)), # Row 3 ('SPAN', (0, 2), (11, 2)), ])) def split(self, availWidth, availHeight): return [] def wrap(self, availWidth, availHeight): width, height = self.table.wrap(availWidth, availHeight) return (width, height) def drawOn(self, canvas, x, y, _sW=0): return self.table.drawOn(canvas, x, y, _sW)
class DelayedTable(Table): """A flowable that inserts a table for which it has the data. Needed so column widths can be determined after we know on what frame the table will be inserted, thus making the overal table width correct. """ def __init__(self, data, colWidths, style=None, repeatrows=False, splitByRow=True): self.data = data self._colWidths = colWidths if style is None: style = TableStyle( [ ('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ] ) self.style = style self.t = None self.repeatrows = repeatrows self.hAlign = TA_CENTER self.splitByRow = splitByRow def wrap(self, w, h): # Create the table, with the widths from colWidths reinterpreted # if needed as percentages of frame/cell/whatever width w is. # _tw = w/sum(self.colWidths) def adjust(*args, **kwargs): kwargs['total'] = w return styles.adjustUnits(*args, **kwargs) # adjust=functools.partial(styles.adjustUnits, total=w) self.colWidths = [adjust(x) for x in self._colWidths] # colWidths = [_w * _tw for _w in self.colWidths] self.t = Table( self.data, colWidths=self.colWidths, style=self.style, repeatRows=self.repeatrows, splitByRow=True, ) self._set_max_page_height_on_cell_flowables(h) # splitByRow=self.splitByRow) self.t.hAlign = self.hAlign return self.t.wrap(w, h) def _set_max_page_height_on_cell_flowables(self, height): """Iterate over all cells in the table and set the maximum height onto the flowable. This is useful to the flowable if its data cannot be rendered over a page boundary (e.g. an image) as it can then resize itself to a valid height in its wrap() method. """ def set_max_page_height_on_flowable(flowable, cell_style): if hasattr(flowable, 'max_page_height'): # Subtract padding from h only if it is a positive value top_padding = cell_style.topPadding if cell_style.topPadding > 0 else 0 bottom_padding = ( cell_style.topPadding if cell_style.bottomPadding > 0 else 0 ) h = abs(height - top_padding - bottom_padding) - _FUZZ flowable.max_page_height = h for row_index, row in enumerate(self.data): for col_index, columns in enumerate(row): # columns is either a list or a cell (for a single cell table) if isinstance(columns, list): for cell in columns: set_max_page_height_on_flowable( cell, self.t._cellStyles[row_index][col_index] ) else: set_max_page_height_on_flowable( columns, self.t._cellStyles[row_index][col_index] ) def split(self, w, h): if self.splitByRow: if not self.t: self.wrap(w, h) return self.t.split(w, h) else: return [] def drawOn(self, canvas, x, y, _sW=0): self.t.drawOn(canvas, x, y, _sW) def identity(self, maxLen=None): return "<%s at %s%s%s> containing: %s" % ( self.__class__.__name__, hex(id(self)), self._frameName(), getattr(self, 'name', '') and (' name="%s"' % getattr(self, 'name', '')) or '', repr(self.data[0]), )[:180]
def draw_footer(self, y_pos): """ Draws the footer. """ para_style = getSampleStyleSheet()['Normal'] para_style.fontSize = 8 footer_para = Paragraph(self.footer_text.replace("\n", "<br/>"), para_style) disclaimer_para = Paragraph( self.disclaimer_text.replace("\n", "<br/>"), para_style) billing_address_para = Paragraph( self.billing_address_text.replace("\n", "<br/>"), para_style) footer_data = [['', footer_para], [(_('Billing Address')), ''], ['', billing_address_para], [(_('Disclaimer')), ''], ['', disclaimer_para]] footer_style = [ # Styling for the entire footer table. ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9), ('TEXTCOLOR', (0, 0), (-1, -1), '#AAAAAA'), # Billing Address Header styling ('LEFTPADDING', (0, 1), (0, 1), 5 * mm), # Disclaimer Header styling ('LEFTPADDING', (0, 3), (0, 3), 5 * mm), ('TOPPADDING', (0, 3), (0, 3), 2 * mm), # Footer Body styling # ('BACKGROUND', (1, 0), (1, 0), '#EEEEEE'), # Billing Address Body styling ('BACKGROUND', (1, 2), (1, 2), '#EEEEEE'), # Disclaimer Body styling ('BACKGROUND', (1, 4), (1, 4), '#EEEEEE'), ] if self.is_invoice: terms_conditions_para = Paragraph( self.terms_conditions_text.replace("\n", "<br/>"), para_style) footer_data.append([(_('TERMS AND CONDITIONS')), '']) footer_data.append(['', terms_conditions_para]) # TERMS AND CONDITIONS header styling footer_style.append(('LEFTPADDING', (0, 5), (0, 5), 5 * mm)) footer_style.append(('TOPPADDING', (0, 5), (0, 5), 2 * mm)) # TERMS AND CONDITIONS body styling footer_style.append(('BACKGROUND', (1, 6), (1, 6), '#EEEEEE')) footer_table = Table(footer_data, [5 * mm, 176 * mm]) footer_table.setStyle(TableStyle(footer_style)) __, rendered_height = footer_table.wrap(0, 0) if y_pos - (self.margin + self.min_clearance) <= rendered_height: self.prepare_new_page() footer_table.drawOn(self.pdf, self.margin, self.margin + 5 * mm)
class Detail(Flowable): def __init__(self, results, components, references, title=""): self.styles = getSampleStyleSheet() self.has_references = bool(references) self.title = title comps = components.split(',') res = results.split(',') # self.data = [["" for x in range(3)] for y in len(comps)] self.data = [] if self.has_references: ref = references.split(",") for t in zip(comps, res, ref): self.data.append(list(t)) else: for t in zip(comps, res): self.data.append(list(t)) def split(self, availWidth, availHeight): return [] # do not split def wrap(self, availWidth, availHeight): width = availWidth * .8 colwidth = width / 3 row_count = len(self.data) row_height = availHeight / row_count fontsize = int((row_height * 1000) / 2) print "row_height = ", row_height print "fontsize = ", fontsize if fontsize > 14: fontsize = 14 sH = self.styles["Heading2"] sH.fontSize = fontsize + 2 sN = self.styles["Normal"] sN.fontSize = fontsize sN.alignment = TA_CENTER fontSmall = fontsize - 4 data = [] for l in self.data: row = [] for idx, m in enumerate(l): if m: if idx == 0: sN.alignment = TA_RIGHT else: sN.alignment = TA_CENTER if idx == 2: sN.fontSize = fontSmall else: sN.fontSize = fontsize row.append(Paragraph(m, sN)) else: row.append("xxx") data.append(row) self.table = Table(data, colWidths=[colwidth] * 3, hAlign='CENTER') self.table.canv = self.canv return self.table.wrap(width, availHeight) def draw(self): self.table.draw()
class MasterInfo(Flowable): KEYS = { 'master': ['patient', 'date', 'room_number', 'case_number', 'physician'], 'patient': ['fullname', 'age', 'gender'], } def process_kwarg(self, data, kwargs): for objname in self.KEYS.keys(): if objname in kwargs.keys(): o = kwargs[objname] for k in self.KEYS[objname]: display = 'get_%s_display' % k if hasattr(o, display): data[k] = getattr(o, display)() else: data[k] = getattr(o, k) del kwargs[objname] p = data.get('patient', None) for k in chain(*self.KEYS.values()): if k in kwargs.keys(): data[k] = kwargs[k] del kwargs[k] elif p and hasattr(p, k): display = 'get_%s_display' % k if hasattr(p, display): data[k] = getattr(p, display)() else: data[k] = getattr(p, k) def __init__(self, **kwargs): data = {} self.process_kwarg(data, kwargs) self.config = {} for k in [ 'font', 'fontsize', 'offset', 'width', 'leftmargin', 'rightmargin' ]: if k in kwargs: # setattr(self, k, kwargs[k]) self.config[k] = kwargs[k] del kwargs[k] if len(kwargs): raise TypeError("__init__ got an unxepected keyworkd '%s'" % kwargs.keys()[0]) self.init_table(data) def init_table(self, data): styles = getSampleStyleSheet() sN = styles['Normal'] if 'font' in self.config: sN.fontName = self.config['font'] if 'fontsize' in self.config: sN.fontSize = self.config['fontsize'] sN.leading = sN.fontSize * 1.1 cell_data = [["" for x in range(12)] for y in range(3)] # Row 1 cell_data[0][0] = Paragraph( "<b>Name:</b><u> %s</u>" % data.get('fullname', 'NO_VALUE'), sN) date_type = type(data['date']) if date_type in [datetime.datetime, datetime.date]: date = datetime.datetime.strftime(data['date'], "%m/%d/%Y") else: date = data['date'] cell_data[0][6] = Paragraph("<b>Date:</b><u> %s</u>" % date, sN) cell_data[0][9] = Paragraph( "<b>Case #:</b><u> %s</u>" % data.get('case_number', 'NO_VALUE'), sN) # Row 2 cell_data[1][0] = Paragraph( "<b>Room #:</b><u> %s</u>" % data.get('room_number', 'NO_VALUE'), sN) cell_data[1][4] = Paragraph("<b>Age:</b><u> %s</u>" % data['age'], sN) cell_data[1][8] = Paragraph( "<b>Sex:</b><u> %s</u>" % data.get('gender', 'NO_VALUE'), sN) # Row 3 cell_data[2][0] = Paragraph( "<b>Requesting Physician:</b><u> %s</u>" % data.get('physician', 'NO_VALUE'), sN) if 'width' in self.config: width = self.config['width'] else: width, height = landscape(A5) self.config['width'] = width lm = self.config.get('leftmargin', 10) rm = self.config.get('rightmargin', 10) width -= lm + rm self.table = Table(cell_data, colWidths=[width / 12] * 12) self.table.setStyle( TableStyle([ # ('GRID', (0, 0), (-1, -1), 1, black), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, -1), (0, -1), 3), ('LINEBELOW', (0, -1), (-1, -1), 1, black), # Row 1 ('SPAN', (0, 0), (5, 0)), ('SPAN', (6, 0), (8, 0)), ('SPAN', (9, 0), (11, 0)), # Row 2 ('SPAN', (0, 1), (3, 1)), ('SPAN', (4, 1), (7, 1)), ('SPAN', (8, 1), (11, 1)), # Row 3 ('SPAN', (0, 2), (11, 2)), ])) def split(self, availWidth, availHeight): return [] def wrap(self, availWidth, availHeight): width, height = self.table.wrap(availWidth, availHeight) return (width, height) def drawOn(self, canvas, x, y, _sW=0): return self.table.drawOn(canvas, x, y, _sW)
def draw_footer(self, y_pos): """ Draws the footer. """ para_style = getSampleStyleSheet()['Normal'] para_style.fontSize = 8 footer_para = Paragraph(self.footer_text.replace("\n", "<br/>"), para_style) disclaimer_para = Paragraph(self.disclaimer_text.replace("\n", "<br/>"), para_style) billing_address_para = Paragraph(self.billing_address_text.replace("\n", "<br/>"), para_style) footer_data = [ ['', footer_para], [(_('Billing Address')), ''], ['', billing_address_para], [(_('Disclaimer')), ''], ['', disclaimer_para] ] footer_style = [ # Styling for the entire footer table. ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9), ('TEXTCOLOR', (0, 0), (-1, -1), '#AAAAAA'), # Billing Address Header styling ('LEFTPADDING', (0, 1), (0, 1), 5 * mm), # Disclaimer Header styling ('LEFTPADDING', (0, 3), (0, 3), 5 * mm), ('TOPPADDING', (0, 3), (0, 3), 2 * mm), # Footer Body styling # ('BACKGROUND', (1, 0), (1, 0), '#EEEEEE'), # Billing Address Body styling ('BACKGROUND', (1, 2), (1, 2), '#EEEEEE'), # Disclaimer Body styling ('BACKGROUND', (1, 4), (1, 4), '#EEEEEE'), ] if self.is_invoice: terms_conditions_para = Paragraph(self.terms_conditions_text.replace("\n", "<br/>"), para_style) footer_data.append([(_('TERMS AND CONDITIONS')), '']) footer_data.append(['', terms_conditions_para]) # TERMS AND CONDITIONS header styling footer_style.append(('LEFTPADDING', (0, 5), (0, 5), 5 * mm)) footer_style.append(('TOPPADDING', (0, 5), (0, 5), 2 * mm)) # TERMS AND CONDITIONS body styling footer_style.append(('BACKGROUND', (1, 6), (1, 6), '#EEEEEE')) footer_table = Table(footer_data, [5 * mm, 176 * mm]) footer_table.setStyle(TableStyle(footer_style)) __, rendered_height = footer_table.wrap(0, 0) if y_pos - (self.margin + self.min_clearance) <= rendered_height: self.prepare_new_page() footer_table.drawOn(self.pdf, self.margin, self.margin + 5 * mm)
def draw_course_info(self, y_pos): """ Draws the main table containing the data items. """ course_items_data = [ ['', (_('Description')), (_('Quantity')), (_('List Price\nper item')), (_('Discount\nper item')), (_('Amount')), ''] ] for row_item in self.items_data: course_items_data.append([ '', Paragraph(row_item['item_description'], getSampleStyleSheet()['Normal']), row_item['quantity'], '{currency}{list_price:.2f}'.format(list_price=row_item['list_price'], currency=self.currency), '{currency}{discount:.2f}'.format(discount=row_item['discount'], currency=self.currency), '{currency}{item_total:.2f}'.format(item_total=row_item['item_total'], currency=self.currency), '' ]) padding_width = 7 * mm desc_col_width = 60 * mm qty_col_width = 26 * mm list_price_col_width = 21 * mm discount_col_width = 21 * mm amount_col_width = 40 * mm course_items_table = Table( course_items_data, [ padding_width, desc_col_width, qty_col_width, list_price_col_width, discount_col_width, amount_col_width, padding_width ], splitByRow=1, repeatRows=1 ) course_items_table.setStyle(TableStyle([ #List Price, Discount, Amount data items ('ALIGN', (3, 1), (5, -1), 'RIGHT'), # Amount header ('ALIGN', (5, 0), (5, 0), 'RIGHT'), # Amount column (header + data items) ('RIGHTPADDING', (5, 0), (5, -1), 7 * mm), # Quantity, List Price, Discount header ('ALIGN', (2, 0), (4, 0), 'CENTER'), # Description header ('ALIGN', (1, 0), (1, -1), 'LEFT'), # Quantity data items ('ALIGN', (2, 1), (2, -1), 'CENTER'), # Lines below the header and at the end of the table. ('LINEBELOW', (0, 0), (-1, 0), 1.00, '#cccccc'), ('LINEBELOW', (0, -1), (-1, -1), 1.00, '#cccccc'), # Innergrid around the data rows. ('INNERGRID', (1, 1), (-2, -1), 0.50, '#cccccc'), # Entire table ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TOPPADDING', (0, 0), (-1, -1), 2 * mm), ('BOTTOMPADDING', (0, 0), (-1, -1), 2 * mm), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ])) rendered_width, rendered_height = course_items_table.wrap(0, 0) table_left_padding = (self.page_width - rendered_width) / 2 split_tables = course_items_table.split(0, self.first_page_available_height) if len(split_tables) > 1: # The entire Table won't fit in the available space and requires splitting. # Draw the part that can fit, start a new page # and repeat the process with the rest of the table. split_table = split_tables[0] __, rendered_height = split_table.wrap(0, 0) split_table.drawOn(self.pdf, table_left_padding, y_pos - rendered_height) self.prepare_new_page() split_tables = split_tables[1].split(0, self.second_page_available_height) while len(split_tables) > 1: split_table = split_tables[0] __, rendered_height = split_table.wrap(0, 0) split_table.drawOn(self.pdf, table_left_padding, self.second_page_start_y_pos - rendered_height) self.prepare_new_page() split_tables = split_tables[1].split(0, self.second_page_available_height) split_table = split_tables[0] __, rendered_height = split_table.wrap(0, 0) split_table.drawOn(self.pdf, table_left_padding, self.second_page_start_y_pos - rendered_height) else: # Table will fit without the need for splitting. course_items_table.drawOn(self.pdf, table_left_padding, y_pos - rendered_height) if not self.is_on_first_page(): y_pos = self.second_page_start_y_pos return y_pos - rendered_height - self.min_clearance
class Signatories(Flowable): def __init__(self, master, margin=10): Flowable.__init__(self) self.master = master self.margin = 10 if master.medical_technologist or master.pathologist: self.has_data = True else: self.has_data = False def split(self, availWidth, availHeight): return [] def wrap(self, availWidth, availHeight): return self.do_table_wrap(availWidth, availHeight) def do_table_wrap(self, availWidth, availHeight): styles = getSampleStyleSheet() sN = styles['Normal'] sN.alignment = TA_CENTER data = [["" for x in range(12)] for y in range(3)] data[0][1] = Paragraph( "<br/><br/><strong>%s</strong>" % self.master.pathologist.fullname, sN) data[1][1] = Paragraph( self.master.pathologist.get_designation_display(), sN) data[2][1] = Paragraph( "PRC LIC #: %s" % self.master.pathologist.license, sN) data[0][7] = Paragraph( "<br/><br/><br/><strong>%s</strong>" % self.master.medical_technologist.fullname, sN) data[1][7] = Paragraph( self.master.medical_technologist.get_designation_display(), sN) data[2][7] = Paragraph( "PRC LIC #: %s" % self.master.medical_technologist.license, sN) w = availWidth - self.margin * 2 spacer = int(w * 0.05) remWidth = (w - (spacer * 4)) / 8 colWidths = [spacer] + \ [remWidth] * 4 + \ [spacer] * 2 + \ [remWidth] * 4 + \ [spacer] self.table = Table(data, colWidths=colWidths) self.table.setStyle( TableStyle([ # config padding ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), # lines ('LINEBELOW', (1, 0), (4, 0), 1, black), ('LINEBELOW', (7, 0), (10, 0), 1, black), # ('GRID', (0, 0), (-1, -1), 1, black), # Column 1 ('SPAN', (1, 0), (4, 0)), ('SPAN', (1, 1), (4, 1)), ('SPAN', (1, 2), (4, 2)), # Column 2 ('SPAN', (7, 0), (10, 0)), ('SPAN', (7, 1), (10, 1)), ('SPAN', (7, 2), (10, 2)), ])) self.table.canv = self.canv return self.table.wrap(availWidth, availHeight) def draw(self): self.table.draw()
def gestionremota2(request): fechahoy = datetime.now() ancho, alto = letter # alto=792,ancho=612 - posicion normal nom_arch = "gestionre2" + nombrearch() + ".pdf" # gestion remota # # desarrollo logo_corp = os.getcwd( ) + "\\misitio\\ai\\static\\img\\Logo_AsistenciaIntegral.jpg" c = canvas.Canvas(os.getcwd() + "\\pdfs\\" + nom_arch, pagesize=letter) # #produccion #logo_corp = os.getcwd()+"/misitio/staticfiles/img/Logo_AsistenciaIntegral.jpg" #c = canvas.Canvas(os.getcwd() +"/misitio/pdfs/"+ nom_arch, pagesize=letter) # c.setPageSize((ancho, alto)) # rut_aux = request.session['rut_x'] paciente = Pacientes.objects.get(rut=rut_aux) if paciente.fe_ini == None: return HttpResponse("Paciente no posee fecha de inicio") # produccion #path_x = os.getcwd() +"/misitio/pdfs/" # Desarrollo path_x = os.getcwd() + '\\pdfs\\' arch_y = os.listdir(path_x) for arch_pdf in arch_y: remove(path_x + arch_pdf) # ## ####comienza primera pagina ############################## y = 710 c.drawImage(logo_corp, 10, y, 190, 80) # (IMAGEN, X,Y, ANCHO, ALTO) y = 700 c.setFont('Helvetica-Bold', 11) c.drawString(190, y, "GESTION REMOTA DE PACIENTES CIMAS + D") c.setFont('Helvetica', 11) # # subrrayado de "GESTION REMOTA DE PACIENTES" y = y - 20 c.line( 190, y + 16, 436, y + 16 ) # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final # c.setFont('Helvetica-Bold', 10) y = y - 20 c.drawString(50, y, "NOMBRE: " + str(paciente.nombre) + " R.U.T.:" + rut_aux) y = y - 20 c.drawString(50, y, "FECHA: " + "_______/_________/__________") y = y - 30 c.drawString( 50, y, "MOTIVO POR EL QUE SE REALIZA: ________________________________") y = y - 30 c.drawString(50, y, "2.-EVALUACION COGNITIVA:") # c.setFont('Helvetica', 10) y = y - 20 # rectangulo c.rect(50, y - 7, 510, 17) c.drawString(53, y, "Test Memoria Acortado - SPMSQ - E. PFEIFER 1975") y = y - 15 # rectangulo c.rect(50, y - 9, 510, 17) c.drawString(53, y - 3, "EVALUABLE:______________ NOEVALUABLE:_________________") y = y - 25 c.drawString( 50, y, "Pregunte desde el número 1 al 10, y complete las respuestas. Pregunte el número 4 A solo si el paciente no " ) y = y - 15 c.drawString(50, y, "tiene telefono. Anote al final el número de errores.") # y = y - 32 c.drawString( 50, y, "Se acepta UN ERROR MAS, si tiene educación basica o ninguna") y = y - 25 c.drawString(50, y, "Se acepta UN ERROR MENOS, si tiene educación superior") # ### COMIENZA DEFINICION GRID data = [ ["Bueno", "Malo", "Pregunta"], ["", "", "¿Que fecha es hoy? (dia-mes-año)"], ["", "", "¿ Que dia de la semana es hoy ?"], ["", "", "¿Cual es el nombre de este lugar o edificio?"], [ "", "", "¿Cual es su número de telefono? 4A ¿Cual es su dirección ?(solo si no tiene telefono)" ], ["", "", "¿Que edad tien usted?"], ["", "", "¿En que fecha nacio? (dia-mes-año)"], ["", "", "¿Cual es el presidente de Chile Actualmente?"], ["", "", "¿Cual fue el presidente anterior?"], ["", "", "¿Cual es el appellido de su madre?"], [ "", "", "A 20, restale 3, y continue restandole 3 a cada resultado hasta el final (20-17-14-11-8-5-2)" ], ] # definicion de cada columna (primera grid) t = Table(data, colWidths=[43, 43, 420]) t.setStyle( TableStyle([ ("ALIGN", (0, 0), (-1, -1), "LEFT"), ("ALIGN", (-2, 1), (-2, -1), "LEFT"), ("GRID", (0, 0), (-1, -1), 0.25, colors.black), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ])) w, h = t.wrap(100, 100) # OBLIGAORIO t.drawOn(c, 50, 220, 0) # DIBUJA LA GRID EN MEMORIA # FIN DE DEFINICION DE LA GRID # rectangulo y = 130 c.roundRect(50, y, 506, 91, 4, stroke=1, fill=0) c.drawString(53, y + 68, "Total") c.drawString(142, y + 68, "0-2 errores: Funciones intelectuales intactas") y = 178 c.drawString(142, y, "3-4 errores: Deterioro intelectual leve") y = y - 20 c.drawString(142, y, "5-7 errores: Deterioro intelectual moderado") y = y - 20 c.drawString(142, y, "8-10 errores: Deterioro intelectual severo") # c.setFont('Helvetica-Bold', 10) y = y - 30 c.drawString(50, y, "Observaciones:") c.setFont('Helvetica', 10) y = y - 30 c.line( 50, y + 16, 556, y + 16 ) # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final y = y - 30 c.line( 50, y + 16, 556, y + 16 ) # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final y = y - 30 c.line( 50, y + 16, 556, y + 16 ) # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final ## ######## FIN DEL REPORTE #################### c.showPage() #salto de pagina c.save() #Archivamos y cerramos el canvas #Lanzamos el pdf creado os.system(nom_arch) #desarrollo return FileResponse(open(os.getcwd() + '\\pdfs\\' + nom_arch, 'rb'), content_type='application/pdf')
def draw_course_info(self, y_pos): """ Draws the main table containing the data items. """ course_items_data = [[ '', (_('Description')), (_('Quantity')), (_('List Price\nper item')), (_('Discount\nper item')), (_('Amount')), '' ]] for row_item in self.items_data: course_items_data.append([ '', Paragraph(row_item['item_description'], getSampleStyleSheet()['Normal']), row_item['quantity'], '{list_price:.2f} {currency}'.format( list_price=row_item['list_price'], currency=self.currency), '{discount:.2f} {currency}'.format( discount=row_item['discount'], currency=self.currency), '{item_total:.2f} {currency}'.format( item_total=row_item['item_total'], currency=self.currency), '' ]) padding_width = 7 * mm desc_col_width = 60 * mm qty_col_width = 26 * mm list_price_col_width = 21 * mm discount_col_width = 21 * mm amount_col_width = 40 * mm course_items_table = Table(course_items_data, [ padding_width, desc_col_width, qty_col_width, list_price_col_width, discount_col_width, amount_col_width, padding_width ], splitByRow=1, repeatRows=1) course_items_table.setStyle( TableStyle([ #List Price, Discount, Amount data items ('ALIGN', (3, 1), (5, -1), 'RIGHT'), # Amount header ('ALIGN', (5, 0), (5, 0), 'RIGHT'), # Amount column (header + data items) ('RIGHTPADDING', (5, 0), (5, -1), 7 * mm), # Quantity, List Price, Discount header ('ALIGN', (2, 0), (4, 0), 'CENTER'), # Description header ('ALIGN', (1, 0), (1, -1), 'LEFT'), # Quantity data items ('ALIGN', (2, 1), (2, -1), 'CENTER'), # Lines below the header and at the end of the table. ('LINEBELOW', (0, 0), (-1, 0), 1.00, '#cccccc'), ('LINEBELOW', (0, -1), (-1, -1), 1.00, '#cccccc'), # Innergrid around the data rows. ('INNERGRID', (1, 1), (-2, -1), 0.50, '#cccccc'), # Entire table ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TOPPADDING', (0, 0), (-1, -1), 2 * mm), ('BOTTOMPADDING', (0, 0), (-1, -1), 2 * mm), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ])) rendered_width, rendered_height = course_items_table.wrap(0, 0) table_left_padding = (self.page_width - rendered_width) / 2 split_tables = course_items_table.split( 0, self.first_page_available_height) if len(split_tables) > 1: # The entire Table won't fit in the available space and requires splitting. # Draw the part that can fit, start a new page # and repeat the process with the rest of the table. split_table = split_tables[0] __, rendered_height = split_table.wrap(0, 0) split_table.drawOn(self.pdf, table_left_padding, y_pos - rendered_height) self.prepare_new_page() split_tables = split_tables[1].split( 0, self.second_page_available_height) while len(split_tables) > 1: split_table = split_tables[0] __, rendered_height = split_table.wrap(0, 0) split_table.drawOn( self.pdf, table_left_padding, self.second_page_start_y_pos - rendered_height) self.prepare_new_page() split_tables = split_tables[1].split( 0, self.second_page_available_height) split_table = split_tables[0] __, rendered_height = split_table.wrap(0, 0) split_table.drawOn(self.pdf, table_left_padding, self.second_page_start_y_pos - rendered_height) else: # Table will fit without the need for splitting. course_items_table.drawOn(self.pdf, table_left_padding, y_pos - rendered_height) if not self.is_on_first_page(): y_pos = self.second_page_start_y_pos return y_pos - rendered_height - self.min_clearance
def HeaderFooterTrans(canvas, doc): canvas.saveState() title = "Reporte de Transacciones" canvas.setTitle(title) Story = [] styles = getSampleStyleSheet() archivo_imagen = finders.find('assets/img/logo.jpg') canvas.drawImage(archivo_imagen, 30, 720, width=540, height=100, preserveAspectRatio=True) fecha = datetime.now().strftime('%d/%m/%Y ') # Estilos de Párrafos ta_c = ParagraphStyle( 'parrafos', alignment=TA_CENTER, fontSize=10, fontName="Helvetica", ) ta_l = ParagraphStyle( 'parrafos', alignment=TA_LEFT, fontSize=13, fontName="Helvetica-Bold", ) ta_l7 = ParagraphStyle( 'parrafos', alignment=TA_LEFT, fontSize=7, fontName="Helvetica-Bold", ) ta_r = ParagraphStyle( 'parrafos', alignment=TA_CENTER, fontSize=11, fontName="Helvetica-Bold", ) # Header header = Paragraph( "REPORTE DE TRANSACCIONES ", ta_l, ) w, h = header.wrap(doc.width + 250, doc.topMargin) header.drawOn(canvas, 215, doc.height - 10 + doc.topMargin - 80) total1 = Paragraph( "Total: " + str(total) + " bs.", ta_l, ) w, h = total1.wrap(doc.width + 250, doc.topMargin) total1.drawOn(canvas, 425, doc.height - 10 + doc.topMargin - 60) meses = Paragraph( "Mes: " + str(mes1) + ".", ta_l, ) w, h = meses.wrap(doc.width + 250, doc.topMargin) meses.drawOn(canvas, 75, doc.height - 10 + doc.topMargin - 60) #header1 = Paragraph("<u>DIRECCIÓN DE AGRICULTURA Y TIERRA</u> ",ta_r,) #w,h = header1.wrap(doc.width-115, doc.topMargin) #header1.drawOn(canvas, 140, doc.height -10 + doc.topMargin - 2) P1 = Paragraph('''N°''', ta_c) P2 = Paragraph('''FECHA''', ta_c) P3 = Paragraph('''TIPO''', ta_c) P4 = Paragraph('''MONTO''', ta_c) data = [[P1, P2, P3, P4]] header2 = Table(data, colWidths=[35, 85, 80, 250]) header2.setStyle( TableStyle([ ('GRID', (0, -1), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), '#50b7e6'), ('ALIGN', (0, 0), (-1, -3), "CENTER"), ])) w, h = header2.wrap(doc.width - 115, doc.topMargin) header2.drawOn(canvas, 72.5, doc.height - 40 + doc.topMargin - 93) # FOOTER footer4 = Paragraph("Fecha: " + str(fecha), ta_l7) w, h = footer4.wrap(doc.width - 200, doc.bottomMargin) footer4.drawOn(canvas, doc.height - 105, doc.topMargin + 620, h) canvas.restoreState()
def HeaderFooterSolicitudes(canvas,doc): canvas.saveState() title = "Reporte de las solicitudes - SolicitudeDV" canvas.setTitle(title) Story=[] styles = getSampleStyleSheet() archivo_imagen = finders.find('img/MDHV.png') canvas.drawImage(archivo_imagen, 30, 740, width=540,height=100,preserveAspectRatio=True) fecha = datetime.now().strftime('%d/%m/%Y ') # Estilos de Párrafos ta_c = ParagraphStyle('parrafos', alignestt = TA_CENTER, fontSize = 11, fontName="Helvetica-Bold", ) ta_l = ParagraphStyle('parrafos', alignestt = TA_LEFT, fontSize = 13, fontName="Helvetica-Bold", ) ta_l7 = ParagraphStyle('parrafos', alignestt = TA_LEFT, fontSize = 7, fontName="Helvetica-Bold", ) ta_r = ParagraphStyle('parrafos', alignestt = TA_RIGHT, fontSize = 13, fontName="Helvetica-Bold", ) # Header header = Paragraph("<u>REPORTE DE LAS SOLICITUDES</u> ",ta_l,) w,h = header.wrap(doc.width-130, doc.topMargin) header.drawOn(canvas, 35, doc.height +10 + doc.topMargin - 25) header1 = Paragraph("<u>MINISTERIO DE HÁBITAT Y VIVIENDA</u> ",ta_r,) w,h = header1.wrap(doc.width-115, doc.topMargin) header1.drawOn(canvas, 180, doc.height +40 + doc.topMargin - 2) P1 = Paragraph('''<b>N°</b>''',ta_c) P2 = Paragraph('''<b>NUMERO DE OFICIO</b>''',ta_c) P3 = Paragraph('''<b>SOLICITANTE</b>''',ta_c) P4 = Paragraph('''<b>FECHA</b>''',ta_c) data= [[P1, P2, P3, P4]] header2 = Table(data, colWidths = [35,150,150,80,255]) header2.setStyle(TableStyle( [ ('GRID', (0, -1), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.lightyellow) ] )) w,h = header2.wrap(doc.width-115, doc.topMargin) header2.drawOn(canvas, 75, doc.height +5 + doc.topMargin - 60) # Llamado del Modelo Director #director = get_object_or_404(Director) #if director.sexo == "Feestino": # sexo = "DIRECTORA" #else: # sexo = "DIRECTOR" # FOOTER footer = Paragraph("Atentamente,",ta_c) w, h = footer.wrap(doc.width -125, doc.bottomMargin -275) footer.drawOn(canvas, doc.height -230, doc.topMargin +35, h) footer1 = Paragraph("_______________________________",ta_c) w, h = footer1.wrap(doc.width -120, doc.bottomMargin - 15) footer1.drawOn(canvas, doc.height -290, doc.topMargin -1, w) footer2 = Paragraph("Luis R" + " Jiménez R",ta_c) w, h = footer2.wrap(doc.width -240, doc.bottomMargin -275) footer2.drawOn(canvas,doc.height -240, doc.topMargin -15, h) footer3 = Paragraph("Director Estadal"+" De Hábitat" + " y Vivienda",ta_c) w, h = footer3.wrap(doc.width -250, doc.bottomMargin) footer3.drawOn(canvas,doc.height -290, doc.topMargin -30, h) footer4 = Paragraph("Del Estado "+"Portuguesa",ta_c) w, h = footer4.wrap(doc.width -300, doc.bottomMargin) footer4.drawOn(canvas,doc.height -250, doc.topMargin -45, h) footer5 = Paragraph("Publicada en gaceta oficial Nº "+ " 41.356 " + " de fecha 08/03/2018",ta_c) w, h = footer5.wrap(doc.width -200, doc.bottomMargin) footer5.drawOn(canvas,doc.height -355, doc.topMargin -60, h) footer6 = Paragraph("Designada mendiante resolución Nº"+" 055 de fecha 06/03/2018",ta_c) w, h = footer6.wrap(doc.width -150, doc.bottomMargin) footer6.drawOn(canvas,doc.height -360, doc.topMargin -75, h) footer7 = Paragraph("Fecha de expedición: "+str(fecha),ta_l7) w, h = footer7.wrap(doc.width -200, doc.bottomMargin) footer7.drawOn(canvas,doc.height -470, doc.topMargin -185, h) canvas.restoreState()
def HeaderFooterPersona(canvas, doc): canvas.saveState() title = "Reporte de Personas" canvas.setTitle(title) Story = [] styles = getSampleStyleSheet() archivo_imagen = finders.find('assets/img/logo.jpg') canvas.drawImage(archivo_imagen, 30, 720, width=540, height=100, preserveAspectRatio=True) fecha = datetime.now().strftime('%d/%m/%Y ') # Estilos de Párrafos ta_c = ParagraphStyle( 'parrafos', alignment=TA_CENTER, fontSize=10, fontName="Helvetica", ) ta_l = ParagraphStyle( 'parrafos', alignment=TA_LEFT, fontSize=13, fontName="Helvetica-Bold", ) ta_l7 = ParagraphStyle( 'parrafos', alignment=TA_LEFT, fontSize=7, fontName="Helvetica-Bold", ) ta_r = ParagraphStyle( 'parrafos', alignment=TA_RIGHT, fontSize=13, fontName="Helvetica-Bold", ) # Header header = Paragraph( "REPORTE DE PERSONAS ", ta_l, ) w, h = header.wrap(doc.width + 250, doc.topMargin) header.drawOn(canvas, 215, doc.height - 10 + doc.topMargin - 80) #header1 = Paragraph("<u>DIRECCIÓN DE AGRICULTURA Y TIERRA</u> ",ta_r,) #w,h = header1.wrap(doc.width-115, doc.topMargin) #header1.drawOn(canvas, 140, doc.height -10 + doc.topMargin - 2) P1 = Paragraph('''N°''', ta_c) P2 = Paragraph('''CEDULA''', ta_c) P3 = Paragraph('''NOMBRE''', ta_c) P4 = Paragraph('''APELLIDO''', ta_c) P5 = Paragraph('''CORREO''', ta_c) P6 = Paragraph('''ROL''', ta_c) data = [[P1, P2, P3, P4, P5, P6]] header2 = Table(data, colWidths=[35, 85, 80, 80, 150, 80]) header2.setStyle( TableStyle([ ('GRID', (0, -1), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), '#50b7e6'), ('ALIGN', (0, 0), (-1, -3), "CENTER"), ])) w, h = header2.wrap(doc.width - 115, doc.topMargin) header2.drawOn(canvas, 42.5, doc.height - 40 + doc.topMargin - 93) # FOOTER footer4 = Paragraph("Fecha: " + str(fecha), ta_l7) w, h = footer4.wrap(doc.width - 200, doc.bottomMargin) footer4.drawOn(canvas, doc.height - 105, doc.topMargin + 620, h) canvas.restoreState()