def table(data): """ return list, so "extend" method should be used. """ """ para_style = STYLES["BodyText"] para_style.wordWrap = 'CJK' para_style.backColor = colors.red table_data = [[Paragraph(cell, para_style) for cell in row] for row in data] """ table_data = data table_style = TableStyle([ ('ALIGN',(0,0),(-1,0),'CENTER'), ('ALIGN',(0,1),(0,-1),'LEFT'), ('ALIGN',(1,1),(-1,-1),'RIGHT'), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('BOX', (0,0), (-1,0), 2, colors.black), ('LINEBELOW', (0,-1), (-1,-1), 2, colors.black), ('TEXTCOLOR',(1,1),(-2,-2),colors.red), ('BACKGROUND', (0,0), (-1,0), colors.black), ('TEXTCOLOR',(0,0),(-1,0),colors.white), ('TEXTCOLOR',(0,1),(-1,-1),colors.black), #('VALIGN',(0,0),(0,-1),'TOP'), #('TEXTCOLOR',(0,0),(0,-1),colors.blue), ]) for i in range(1, len(table_data)): if i%2 == 0: table_style.add('BACKGROUND', (0,i), (-1,i), colors.Color(.835,.91,.976)) t = Table(table_data) t.setStyle(table_style) return [t]
def buildTable(data): doc = SimpleDocTemplate("MOOSE_requirements_tracability.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18) doc.pagesize = landscape(A4) elements = [] #Configure style and word wrap s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' pdf_data = [["Requirement", "Description", "Test Case(s)"]] #TODO: Need a numerical sort here keys = sorted(data.keys()) for key in keys: data[key][2] = '\n'.join(data[key][2]) pdf_data.append([Paragraph(cell, s) for cell in data[key]]) # Build the Table and Style Information tableThatSplitsOverPages = Table(pdf_data, repeatRows=1) tableThatSplitsOverPages.hAlign = 'LEFT' tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),colors.black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('LINEBELOW',(0,0),(-1,-1),1,colors.black), ('INNERGRID', (0,0), (-1,-1),1,colors.black), ('BOX',(0,0),(-1,-1),1,colors.black), ('BOX',(0,0),(0,-1),1,colors.black)]) tblStyle.add('BACKGROUND',(0,0),(-1,-1),colors.lightblue) tblStyle.add('BACKGROUND',(0,1),(-1,-1),colors.white) tableThatSplitsOverPages.setStyle(tblStyle) elements.append(tableThatSplitsOverPages) doc.build(elements)
def make_table(printable): style = TableStyle() style.add('VALIGN', (0,0), (-1,-1), 'TOP') style.add('GRID', (0,0), (-1,-1), 1, colors.black) table = Table(printable, [col_width*0.4,col_width*0.6]) table.setStyle(style) return table
def generate_monthly_summary_table(huc12): """Make a table of monthly summary stats.""" data = [] data.append(['Year', 'Month', 'Precip', "Runoff", "Loss", "Delivery", '2+" Precip', 'Events']) data.append(['', '', '[inch]', "[inch]", "[tons/acre]", "[tons/acre]", "[days]", "[days]"]) pgconn = get_dbconn('idep') huc12col = "huc_12" if len(huc12) == 8: huc12col = "substr(huc_12, 1, 8)" df = read_sql(""" WITH data as ( SELECT extract(year from valid)::int as year, extract(month from valid)::int as month, huc_12, (sum(qc_precip) / 25.4)::numeric as sum_qc_precip, (sum(avg_runoff) / 25.4)::numeric as sum_avg_runoff, (sum(avg_loss) * 4.463)::numeric as sum_avg_loss, (sum(avg_delivery) * 4.463)::numeric as sum_avg_delivery, sum(case when qc_precip >= 50.8 then 1 else 0 end) as pdays, sum(case when avg_loss > 0 then 1 else 0 end) as events from results_by_huc12 WHERE scenario = 0 and """ + huc12col + """ = %s and valid >= '2016-01-01' GROUP by year, month, huc_12) SELECT year, month, round(avg(sum_qc_precip), 2), round(avg(sum_avg_runoff), 2), round(avg(sum_avg_loss), 2), round(avg(sum_avg_delivery), 2), round(avg(pdays)::numeric, 1), round(avg(events)::numeric, 1) from data GROUP by year, month ORDER by year, month """, pgconn, params=(huc12, ), index_col=None) for _, row in df.iterrows(): vals = [int(row['year']), calendar.month_abbr[int(row['month'])]] vals.extend(["%.2f" % (f, ) for f in list(row)[2:-2]]) vals.extend(["%.0f" % (f, ) for f in list(row)[-2:]]) data.append(vals) data[-1][1] = "%s*" % (data[-1][1], ) totals = df.iloc[:-1].mean() vals = ['', 'Average'] vals.extend(["%.2f" % (f, ) for f in list(totals[2:])]) data.append(vals) style = TableStyle( [('LINEBELOW', (2, 1), (-1, 1), 0.5, '#000000'), ('LINEAFTER', (1, 2), (1, -2), 0.5, '#000000'), ('LINEABOVE', (2, -1), (-1, -1), 0.5, '#000000'), ('ALIGN', (0, 0), (-1, -1), 'RIGHT')] ) for rownum in range(3, len(data)+1, 2): style.add('LINEBELOW', (0, rownum), (-1, rownum), 0.25, '#EEEEEE') return Table(data, style=style, repeatRows=2)
def print_entries(self, eh, ehds): buffer = self.buffer styles = getSampleStyleSheet() data = [] ts = TableStyle() d = [] hs = styles['Heading1'] hs.alignment = TA_CENTER d.append(Paragraph('<b>Producto</b>', hs)) d.append(Paragraph('<b>Descripción</b>', hs)) d.append(Paragraph('<b>Cantidad</b>', hs)) if eh.printed: if(eh.action == 'altas'): title = Paragraph('<b> Entrada de Mercancía - REIMPRESIÓN</b>', hs) else: title = Paragraph('<b> Salida de Mercancía - REIMPRESIÓN</b>', hs) else: if(eh.action == 'altas'): title = Paragraph('<b> Entrada de Mercancía </b>', hs) else: title = Paragraph('<b> Salida de Mercancía </b>', hs) data.append(d) total_qty = 0 sp = styles['BodyText'] sp.alignment = TA_CENTER sq = styles['BodyText'] sq.alignment = TA_RIGHT spb = styles['Heading3'] spb.alignment = TA_RIGHT sl = styles['Normal'] sl.alignment = TA_CENTER for ehd in ehds: d = [] d.append(ehd.product.name) p = Paragraph(ehd.product.description.encode('utf-8'), sp) d.append(p) pq = Paragraph(str(ehd.quantity), sq) d.append(pq) data.append(d) total_qty += ehd.quantity t = Table(data, colWidths = [(letter[0] * .20), (letter[0] * .50), (letter[0] * .20)]) ts.add('LINEBELOW', (0,1), (-1,-1), 0.25, colors.black) t.setStyle(ts) elements = [] elements.append(title) elements.append(t) elements.append(Paragraph('<br /><p> <b>Cantidad total de artículos:</b> ' + str(total_qty) + '</p>', spb)) if(eh.action == 'altas'): elements.append(Paragraph('<br /><p> Al firmar este documento acepto que estoy recibiendo la mercancía listada y me responsabilizo por la mercancía. <br /><br /><br/> Nombre:_____________________ Firma: _____________________________</p>',sl)) else: elements.append(Paragraph('<br /><p> Al firmar este documento acepto la salida de esta mercancía. <br /><br /><br/> Nombre:_____________________ Firma: _____________________________</p>',sl)) doc = SimpleDocTemplate(buffer, pagesize=letter) doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer, canvasmaker = NumberedCanvas) return buffer
def get_underline(): data = [[None], [None]] line = Table( data, colWidths=[6.2 * inch], rowHeights=[0.03 * inch, 0.14 * inch]) table_style = TableStyle() table_style.add('LINEBELOW', (0, 0), (0, 0), 1, colors.black) line.setStyle(table_style) return line
def getTableStyle(): ts = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBELOW', (0, 0), (-1, -1), 0.8, colors.black), ('BOX', (0, 0), (-1, -1), 0.75, colors.black), ('BOX', (0, 0), (0, -1), 0.75, colors.black), ('BOX', (1, 0), (1, -1), 0.75, colors.black), ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('FONTNAME', (0, 0), (-1, -1), 'Arabic'), ('FONTSIZE', (0, 0), (-1, -1), TABLE_FONT_SIZE), ]) ts.add('BACKGROUND', (0, 0), (-1, 1), colors.lightgrey) # header lightgrey ts.add('BACKGROUND', (0, 1), (-1, -1), colors.white) # rest of table return ts
def gather_elements(self, client, node, style): if node.children and isinstance(node.children[0], docutils.nodes.title): title=[] else: title= [Paragraph(client.text_for_label(node.tagname, style), style=client.styles['%s-heading'%node.tagname])] rows=title + client.gather_elements(node, style=style) st=client.styles[node.tagname] if 'commands' in dir(st): t_style = TableStyle(st.commands) else: t_style = TableStyle() t_style.add("ROWBACKGROUNDS", [0, 0], [-1, -1],[st.backColor]) t_style.add("BOX", [ 0, 0 ], [ -1, -1 ], st.borderWidth , st.borderColor) if client.splittables: node.elements = [MySpacer(0,st.spaceBefore), SplitTable([['',rows]], style=t_style, colWidths=[0,None], padding=st.borderPadding), MySpacer(0,st.spaceAfter)] else: padding, p1, p2, p3, p4=tablepadding(padding=st.borderPadding) t_style.add(*p1) t_style.add(*p2) t_style.add(*p3) t_style.add(*p4) node.elements = [MySpacer(0,st.spaceBefore), DelayedTable([['',rows]], style=t_style, colWidths=[0,None]), MySpacer(0,st.spaceAfter)] return node.elements
def getTableStyleThreeCol(): ts = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBELOW', (0, 0), (-1, -1), 0.8, colors.black), ('BOX', (0, 0), (-1, -1), 0.75, colors.black), ('BOX', (0, 0), (0, -1), 0.75, colors.black), ('BOX', (1, 0), (1, -1), 0.75, colors.black), ('ALIGN', (0, 0), (0, -1), 'CENTER'), # center number column ('ALIGN', (1, 0), (1, -1), 'RIGHT'), # right align name column ('ALIGN', (2, 0), (2, -1), 'CENTER'), # center number column ('FONTNAME', (0, 0), (-1, -1), 'Arabic'), ('FONTSIZE', (0, 0), (-1, -1), TABLE_FONT_SIZE), ]) ts.add('BACKGROUND', (0, 0), (-1, 1), colors.lightgrey) # header lightgrey ts.add('BACKGROUND', (0, 1), (-1, -1), colors.white) # rest of table return ts
def _new_style(self, header_line_idx=None, header_line_width=1, header_line_color="black", debug_grid=False): ts = TableStyle() if debug_grid: ts.add("GRID", (0, 0), (-1, -1), 1, colors.red) if isinstance(header_line_color, str): try: header_line_color = getattr(colors, header_line_color) except AttributeError: header_line_color = colors.black if header_line_idx is not None: ts.add("LINEBELOW", (0, header_line_idx), (-1, header_line_idx), header_line_width, header_line_color) return ts
def print_inventory_surplus(self, entries, title): buffer = self.buffer styles = getSampleStyleSheet() data = [] ts = TableStyle() d = [] hs = styles['Heading1'] hs.alignment = TA_CENTER d.append(Paragraph('<b>Código</b>', styles['Normal'])) d.append(Paragraph('<b>Descripción</b>', styles['Normal'])) d.append(Paragraph('<b>Existencia</b>', styles['Normal'])) d.append(Paragraph('<b>Sistema</b>', styles['Normal'])) d.append(Paragraph('<b>Sobrante</b>', styles['Normal'])) title = Paragraph('<b> ' + title + '</b>', hs) data.append(d) total_qty = 0 sp = styles['BodyText'] sp.alignment = TA_CENTER sq = styles['BodyText'] sq.alignment = TA_RIGHT spb = styles['Heading3'] spb.alignment = TA_RIGHT sl = styles['Normal'] sl.alignment = TA_CENTER for e in entries: if e['entry'].product is None: continue d = [] d.append(e['entry'].product.name) p = Paragraph(e['entry'].product.description.encode('utf-8'), sp) d.append(p) pq = Paragraph(str(e['entry'].quantity), sq) d.append(pq) d.append(Paragraph(str(e['tcount']), sq)) d.append(Paragraph(str(e['diff'] * -1), sq)) data.append(d) t = Table(data, colWidths = [(letter[0] * .15), (letter[0] * .45), (letter[0] * .12), (letter[0] * .12), (letter[0] * .12)]) ts.add('LINEBELOW', (0,1), (-1, -1), 0.25, colors.black) t.setStyle(ts) elements = [] elements.append(title) elements.append(t) doc = SimpleDocTemplate(buffer, pagesize=letter) doc.build(elements, onFirstPage=self._header_footer_inventory, onLaterPages=self._header_footer_inventory, canvasmaker = NumberedCanvas) return buffer
def print_inventory_existence(self, entries, title): buffer = self.buffer styles = getSampleStyleSheet() data = [] ts = TableStyle() d = [] hs = styles['Heading1'] hsc = styles['Heading3'] hs.alignment = TA_CENTER d.append(Paragraph('<b>Código</b>', styles['Normal'])) d.append(Paragraph('<b>Descripción</b>', styles['Normal'])) d.append(Paragraph('<b>Cantidad</b>', styles['Normal'])) title = Paragraph('<b> ' + title + '</b>', styles['Normal']) data.append(d) total_qty = 0 sp = styles['BodyText'] sp.alignment = TA_CENTER sq = styles['BodyText'] sq.alignment = TA_RIGHT spb = styles['Heading3'] spb.alignment = TA_RIGHT sl = styles['Normal'] sl.alignment = TA_CENTER for e in entries: if e.quantity == 0: continue d = [] d.append(e.product.name) p = Paragraph(e.product.description.encode('utf-8'), sp) d.append(p) pq = Paragraph(str(e.quantity), sq) d.append(pq) data.append(d) total_qty += e.quantity t = Table(data, colWidths = [(letter[0] * .20), (letter[0] * .50), (letter[0] * .20)]) ts.add('LINEBELOW', (0,1), (-1, -1), 0.25, colors.black) t.setStyle(ts) elements = [] elements.append(title) elements.append(t) elements.append(Paragraph('<br /><p> <b>Cantidad total de artículos:</b> ' + str(total_qty) + '</p>', spb)) doc = SimpleDocTemplate(buffer, pagesize=letter) doc.build(elements, onFirstPage=self._header_footer_inventory, onLaterPages=self._header_footer_inventory, canvasmaker = NumberedCanvas) return buffer
def buildTable(data): style = TableStyle() style.add('VALIGN', (0,0), (-1,-1), 'TOP') style.add('GRID', (0,0), (-1,-1), 1, colors.black) style.add('ALIGN', (1,0), (1,-1), 'RIGHT') table = Table(data, [width*0.2,width*0.4,width*0.4]) table.setStyle(style) return table
def _build_spectrum_table_style(self): tblstyle = TableStyle([ ('SPAN', (0, 0), (-1, 0)), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, -1), 9), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black), ('LINEBELOW', (0, 1), (-1, 1), 1, colors.black), # ('ALIGN', (2, 0), (2, 0), 'LEFT'), ('LINEBELOW', (0, 3), (-1, 3), 1.5, colors.black), # ('LINEBELOW', (0, 0), (-1, -1), 1, colors.red), # ('LINEBEFORE', (0, 0), (-1, -1), 1, colors.black), ('ALIGN', (2, 0), (-1, -1), 'CENTER') ]) for ir in self.int_plat_age_rowids: tblstyle.add('SPAN', (1, ir), (3, ir)) tblstyle.add('SPAN', (1, ir + 1), (2, ir + 1)) for si in self.sample_rowids: tblstyle.add('SPAN', (1, si), (-1, si)) return tblstyle
def print_history(request): """Печать истории забора материала за день""" from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus import Table, TableStyle from reportlab.lib import colors from reportlab.platypus import Paragraph from reportlab.lib.styles import getSampleStyleSheet styleSheet = getSampleStyleSheet() import os.path import collections filter = False filterArray = [] if "filter" in request.GET.keys(): filter = True filterArray = json.loads(request.GET["filter"]) pdfmetrics.registerFont( TTFont('OpenSans', os.path.join(FONTS_FOLDER, 'OpenSans.ttf'))) # Загрузка шрифта response = HttpResponse( content_type='application/pdf') # Формирование ответа response[ 'Content-Disposition'] = 'inline; filename="napr.pdf"' # Content-Disposition inline для показа PDF в браузере buffer = BytesIO() # Буфер c = canvas.Canvas(buffer, pagesize=A4) # Холст tubes = [] if not filter: tubes = TubesRegistration.objects.filter( doc_get=request.user.doctorprofile).order_by('time_get').exclude( time_get__lt=datetime.now().date()) else: for v in filterArray: tubes.append(TubesRegistration.objects.get(pk=v)) labs = {} # Словарь с пробирками, сгруппироваными по лаборатории for v in tubes: # Перебор пробирок iss = Issledovaniya.objects.filter( tubes__id=v.id) # Получение исследований для пробирки iss_list = [] # Список исследований k = v.doc_get.podrazdeleniye.title + "@" + str( iss[0].research.get_podrazdeleniye().title) for val in iss: # Цикл перевода полученных исследований в список iss_list.append(val.research.title) if k not in labs.keys( ): # Добавление списка в словарь если по ключу k нету ничего в словаре labs labs[k] = [] for value in iss_list: # Перебор списка исследований labs[k].append( { "type": v.type.tube.title, "researches": value, "client-type": iss[0].napravleniye.client.base.short_title, "lab_title": iss[0].research.get_podrazdeleniye().title, "time": strtime(v.time_get), "dir_id": iss[0].napravleniye_id, "podr": v.doc_get.podrazdeleniye.title, "reciver": None, "tube_id": str(v.id), "history_num": iss[0].napravleniye.history_num, "fio": iss[0].napravleniye.client.individual.fio(short=True, dots=True), } ) # Добавление в список исследований и пробирок по ключу k в словарь labs labs = collections.OrderedDict(sorted(labs.items())) # Сортировка словаря c.setFont('OpenSans', 20) paddingx = 17 data_header = [ "№", "ФИО, № истории", "№ емкости", "Тип емкости", "Наименования исследований", "Емкость не принята (замечания)" ] tw = w - paddingx * 4.5 tx = paddingx * 3 ty = 90 c.setFont('OpenSans', 9) styleSheet["BodyText"].fontName = "OpenSans" styleSheet["BodyText"].fontSize = 7 doc_num = 0 for key in labs: doc_num += 1 p = Paginator(labs[key], 47) i = 0 if doc_num >= 2: c.showPage() for pg_num in p.page_range: pg = p.page(pg_num) if pg_num >= 0: draw_tituls(c, p.num_pages, pg_num, paddingx, pg[0], request.user.doctorprofile.hospital_safe_title) data = [] tmp = [] for v in data_header: tmp.append(Paragraph(str(v), styleSheet["BodyText"])) data.append(tmp) merge_list = {} num = 0 lastid = "-1" for obj in pg.object_list: tmp = [] if lastid != obj["tube_id"]: i += 1 lastid = obj["tube_id"] shownum = True else: shownum = False if lastid not in merge_list.keys(): merge_list[lastid] = [] merge_list[lastid].append(num) if shownum: tmp.append(Paragraph(str(i), styleSheet["BodyText"])) fio = obj["fio"] if obj["history_num"] and len(obj["history_num"]) > 0: fio += ", " + obj["history_num"] tmp.append(Paragraph(fio, styleSheet["BodyText"])) tmp.append( Paragraph(obj["tube_id"], styleSheet["BodyText"])) tmp.append(Paragraph(obj["type"], styleSheet["BodyText"])) else: tmp.append("") tmp.append("") tmp.append("") tmp.append("") research_tmp = obj["researches"] if len(research_tmp) > 38: research_tmp = research_tmp[0:-(len(research_tmp) - 38)] + "..." tmp.append(Paragraph(research_tmp, styleSheet["BodyText"])) tmp.append(Paragraph("", styleSheet["BodyText"])) data.append(tmp) num += 1 style = TableStyle([ ('TEXTCOLOR', (0, -1), (-1, -1), colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), ('LEFTPADDING', (0, 0), (-1, -1), 1), ('RIGHTPADDING', (0, 0), (-1, -1), 1), ('TOPPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 1), ]) for span in merge_list: # Цикл объединения ячеек for pos in range(0, 6): style.add( 'INNERGRID', (pos, merge_list[span][0]), (pos, merge_list[span][0] + len(merge_list[span])), 0.28, colors.white) style.add( 'BOX', (pos, merge_list[span][0]), (pos, merge_list[span][0] + len(merge_list[span])), 0.2, colors.black) t = Table(data, colWidths=[ int(tw * 0.03), int(tw * 0.23), int(tw * 0.08), int(tw * 0.23), int(tw * 0.31), int(tw * 0.14) ], style=style) t.canv = c wt, ht = t.wrap(0, 0) t.drawOn(c, tx, h - ht - ty) if pg.has_next(): c.showPage() c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) slog.Log(key="", type=10, body="", user=request.user.doctorprofile).save() return response
def print_entries(self, eh, ehds): buffer = self.buffer styles = getSampleStyleSheet() data = [] ts = TableStyle() d = [] hs = styles['Heading1'] hs.alignment = TA_CENTER d.append(Paragraph('<b>Producto</b>', hs)) d.append(Paragraph('<b>Descripción</b>', hs)) d.append(Paragraph('<b>Cantidad</b>', hs)) if eh.printed: if (eh.action == 'altas'): title = Paragraph( '<b> Entrada de Mercancía - REIMPRESIÓN</b>', hs) else: title = Paragraph( '<b> Salida de Mercancía - REIMPRESIÓN</b>', hs) else: if (eh.action == 'altas'): title = Paragraph('<b> Entrada de Mercancía </b>', hs) else: title = Paragraph('<b> Salida de Mercancía </b>', hs) data.append(d) total_qty = 0 sp = styles['BodyText'] sp.alignment = TA_CENTER sq = styles['BodyText'] sq.alignment = TA_RIGHT spb = styles['Heading3'] spb.alignment = TA_RIGHT sl = styles['Normal'] sl.alignment = TA_CENTER for ehd in ehds: d = [] d.append(ehd.product.name) p = Paragraph(ehd.product.description.encode('utf-8'), sp) d.append(p) pq = Paragraph(str(ehd.quantity), sq) d.append(pq) data.append(d) total_qty += ehd.quantity t = Table(data, colWidths=[(letter[0] * .20), (letter[0] * .50), (letter[0] * .20)]) ts.add('LINEBELOW', (0, 1), (-1, -1), 0.25, colors.black) t.setStyle(ts) elements = [] elements.append(title) elements.append(t) elements.append( Paragraph( '<br /><p> <b>Cantidad total de artículos:</b> ' + str(total_qty) + '</p>', spb)) if (eh.action == 'altas'): elements.append( Paragraph( '<br /><p> Al firmar este documento acepto que estoy recibiendo la mercancía listada y me responsabilizo por la mercancía. <br /><br /><br/> Nombre:_____________________ Firma: _____________________________</p>', sl)) else: elements.append( Paragraph( '<br /><p> Al firmar este documento acepto la salida de esta mercancía. <br /><br /><br/> Nombre:_____________________ Firma: _____________________________</p>', sl)) doc = SimpleDocTemplate(buffer, pagesize=letter) doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer, canvasmaker=NumberedCanvas) return buffer
tabla = Table(data=datos, style=[ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), ('BOX', (0, 0), (-1, -1), 2, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.pink), ]) story.append(tabla) story.append(Spacer(0, 15)) # Ejemplo 03 estiloTabla = TableStyle([ ('LINEABOVE', (0, 0), (-1, 0), 2, colors.green), ('ALIGN', (1, 1), (-1, -1), 'RIGHT'), ('ROWBACKGROUNDS', (0, 0), (-1, -1), (colors.yellow, None)), ]) estiloTabla.add('BACKGROUND', (0, 0), (-1, 0), colors.Color(0, 0.7, 0.7)) t = Table( [['', 'Ventas', 'Compras'], ['Enero', 1000, 2000], ['Febrero', 3000, 100.5], ['Marzo', 2000, 1000], ['Abril', 1500, 1500]], style=estiloTabla) # Ejemplo 04: CELDAS COMPLEJAS estilo = getSampleStyleSheet() I = Image('imgs/tuxTemplario.jpg', width=100, height=100) P1 = Paragraph('''El tux templario''', estilo["BodyText"]) P2 = Paragraph('''Viva Linux''', estilo["BodyText"]) t = Table(data=[['A', 'B', 'C', P1, 'D'], ['00', '01', '02', [I, P2], '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']],
def createDoc(rows, rptType): flightroute = dbMgr(config.flightRoute) doc = SimpleDocTemplate(rptType + baseReport, rightMargin=margin, leftMargin=margin, topMargin=margin, bottomMargin=margin, pagesize=landscape(letter)) # container for the 'Flowable' objects elements = [] elements.append( Paragraph(rptType + " Flights seen on:" + " " + rptDate, styleHeading)) # elements.append(PageBreak) # Set Column Headers even_rows = [] poi = [] chk = [] colWidths = [.75 * inch] + [.8 * inch] + [1 * inch] + [2.2 * inch] + [ 1.45 * inch ] + [.65 * inch] + [.65 * inch] + [.65 * inch] + [.65 * inch] + [ .65 * inch ] + [.65 * inch] rowHeights = [.16 * inch] * ((len(rows) * 2) + 2) index = 0 data = [[ "Start Time", "Mode S", "Call Sign", "Country", "Manufacturer", "First Sqwk", "First Alt", "First GS", "First VR", "First Track", "#MsgRcvd" ], [ 'End Time', 'Registration', 'Route', 'Owner', 'Type', 'Last Sqwk', "Last Alt", "Last GS", "Last VR", "Last Track" ]] for row in rows: # Change "N" to "United States" if row[4] == 'N': country = 'United States' else: country = row[4] # Check for missing start_time try: start_time = str(row[53][11:]) except TypeError: start_time = 'UNKNOWN' # Check for missing end_time try: end_time = str(row[54][11:]) except TypeError: end_time = 'UNKNOWN' try: mode_s = str(row[3]) except TypeError: mode_s = "UNKNOWN" try: registration = str(row[6]).strip() except TypeError: registration = '------' try: manufacturer = str(row[12]).strip() except TypeError: manufacturer = '------' try: mfr_type = str(row[14]).strip() except TypeError: mfr_type = '------' try: owner = str(row[21]).strip() except TypeError: owner = '-----' if str(row[81]).strip() == '': firstSquawk = '----' else: firstSquawk = str(row[81]) if str(row[82]).strip() == '': lastSquawk = '----' else: lastSquawk = str(row[82]) if str(row[75]).strip() == '': firstAlt = '------' else: firstAlt = str(row[75]) if str(row[76]).strip() == '': lastAlt = '------' else: lastAlt = str(row[76]) if str(row[55]).strip() == 'None': callsign = '------' route = '------' else: callsign = str(row[55]).strip() route = flightroute.query( "select route from FlightRoute where FlightRoute.flight like '" + callsign + "'").fetchall() if len(route) > 0: route = str(route[0][0]) else: route = '------' try: firstGS = str(int(float(row[73]))) except TypeError: firstGS = '------' try: lastGS = str(int(float(row[74]))) except TypeError: lastGS = '------' msg_rcvd = calcMsgCount(row) try: firstVR = str(int(float(row[77]))) except TypeError: firstVR = "------" try: lastVR = str(int(float(row[78]))) except TypeError: lastVR = "------" try: firstTrk = str(int(float(row[79]))) except TypeError: firstTrk = '----' try: lastTrk = str(int(float(row[80]))) except TypeError: lastTrk = '----' data.append([ start_time, mode_s, callsign, country, manufacturer, firstSquawk, firstAlt, firstGS, firstVR, firstTrk, msg_rcvd ]) data.append([ end_time, registration, route, owner, mfr_type, lastSquawk, lastAlt, lastGS, lastVR, lastTrk ]) index += 1 if index % 2 == 0: even_rows.append(index) if row[28] == 1: poi.append(index) if str(row[6]).strip() == 'None': chk.append(index) # Reminder: (column, row) starting at 0 # (0,0) is upper left, (-1,-1) is lower right (row,0),(row,-1) is entire row # t = Table(data, colWidths=colWidths, rowHeights=rowHeights, repeatRows=2) t = Table(data, colWidths=colWidths, rowHeights=rowHeights, repeatRows=2, hAlign='LEFT') t.hAlign = 'LEFT' t.vAlign = 'CENTER' # Define default table attributes tblStyle = TableStyle([]) tblStyle.add('FONTSIZE', (0, 0), (-1, -1), page_font_size) tblStyle.add('TEXTFONT', (0, 0), (-1, -1), page_font) tblStyle.add('TEXTCOLOR', (0, 0), (-1, -1), colors.black) tblStyle.add('TOPPADDING', (0, 0), (-1, -1), 6) tblStyle.add('BOTTOMPADDING', (0, 0), (-1, -1), 0) tblStyle.add('BOX', (0, 0), (-1, 1), .25, colors.black) tblStyle.add('BOX', (0, 0), (-1, -1), 2, colors.black) tblStyle.add('INNERGRID', (0, 0), (-1, 1), 0.15, colors.gray) tblStyle.add('BACKGROUND', (0, 0), (-1, 1), colors.lightblue) tblStyle.add('BACKGROUND', (0, 2), (-1, -1), colors.white) for row in even_rows: row1 = (row) * 2 row2 = row1 + 1 tblStyle.add('BACKGROUND', (0, row1), (-1, row2), colors.lightgreen) if rptType == 'all': for row in poi: row1 = row * 2 row2 = row1 + 1 tblStyle.add('BACKGROUND', (0, row1), (-1, row1), colors.red) tblStyle.add('BACKGROUND', (0, row2), (-1, row2), colors.red) tblStyle.add('TEXTCOLOR', (0, row1), (-1, row1), colors.white) tblStyle.add('TEXTCOLOR', (0, row2), (-1, row2), colors.white) for row in chk: row1 = row * 2 row2 = row1 + 1 tblStyle.add('BACKGROUND', (0, row1), (-1, row1), colors.yellow) tblStyle.add('BACKGROUND', (0, row2), (-1, row2), colors.yellow) tblStyle.add('TEXTCOLOR', (0, row1), (-1, row1), colors.black) tblStyle.add('TEXTCOLOR', (0, row2), (-1, row2), colors.black) t.setStyle(tblStyle) elements.append(t) # write the document to disk doc.build(elements)
def xnotmotherpdf(request, bdd, lid, xlid): project = Project.objects.using(bdd).all().order_by('pk')[0].name filename = bdd + '_' + lid + '.pdf' dirfile = "/tmp/" + filename libname = Library.objects.using(bdd).get(lid=lid).name doc = SimpleDocTemplate(filename="{}".format(dirfile), pagesize=landscape(A4)) elements = [] #For the lid identified library, getting ressources whose the resulting \ #collection has been entirely completed and may consequently be edited. #Trick : These ressources have two instructions with name = 'checker' : #This is like "tobeedited" (see below) l = ItemRecord.objects.using(bdd).filter(lid=lid).exclude(rank=1).exclude( rank=0) #Initializing a list of ressources to edit : resslist = [] for e in l: nl = Instruction.objects.using(bdd).filter(sid=e.sid) kd = nl.filter(name="checker") if len(kd) == 2 and Instruction.objects.using(bdd).filter( sid=e.sid, name=Library.objects.using(bdd).get(lid=xlid)): resslist.append(e) for r in resslist: # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. title = ItemRecord.objects.using(bdd).get(sid=r.sid, lid=lid).title sid = ItemRecord.objects.using(bdd).get(sid=r.sid, lid=lid).sid cn = ItemRecord.objects.using(bdd).get(sid=sid, lid=lid).cn issn = ItemRecord.objects.using(bdd).get(sid=r.sid, lid=lid).issn pubhist = ItemRecord.objects.using(bdd).get(sid=r.sid, lid=lid).pubhist instructions = Instruction.objects.using(bdd).filter( sid=r.sid).order_by('line') properinstructions = Instruction.objects.using(bdd).filter( sid=r.sid, name=libname) otherinstructions = Instruction.objects.using(bdd).filter( sid=r.sid, oname=libname) libinstructions = properinstructions.union(otherinstructions).order_by( 'line') controlbd = Instruction.objects.using(bdd).get(sid=r.sid, bound='x', name='checker').descr controlnotbd = Instruction.objects.using(bdd).exclude(bound='x').get( sid=r.sid, name='checker').descr mothercollection = Library.objects.using(bdd).get( lid=ItemRecord.objects.using(bdd).get(sid=r.sid, rank=1).lid).name datap = [ [_('Projet'), project], [_("Titre"), Paragraph(title, styles['Normal'])], [ _("Collection"), str(libname + " -----> " + _('cote') + " : " + cn) ], ] tp = Table(datap) table_stylep = TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ]) tp.setStyle(table_stylep) elements.append(tp) datas = [[ str(_('issn') + " : " + issn), str(_('ppn') + " : " + sid), str(_('historique de la publication') + " : " + pubhist) ]] ts = Table(datas) table_styles = TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ]) ts.setStyle(table_styles) elements.append(ts) datacoll = [] datacoll.append( [_("rang"), _("bibliothèque"), _("info"), _("commentaire")]) for e in ItemRecord.objects.using(bdd).filter( sid=sid).order_by("rank"): if e.rank == 1: datacoll.append([ e.rank, Library.objects.using(bdd).get(lid=e.lid).name, _("collection mère"), e.comm ]) elif e.rank == 0: datacoll.append([ e.rank, Library.objects.using(bdd).get(lid=e.lid).name, e.excl, e.comm ]) else: datacoll.append([ e.rank, Library.objects.using(bdd).get(lid=e.lid).name, _("a pris part"), e.comm ]) tcoll = Table(datacoll) table_stylecoll = TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ]) tcoll.setStyle(table_stylecoll) elements.append(tcoll) data = [["", "", "", "", "", "", ""], [ '#', _('bibliothèque'), _('relié ?'), _('bib. remédiée'), _('segment'), _('exception'), _('améliorable') ]] Table(data, colWidths=None, rowHeights=None, style=None, splitByRow=1, repeatRows=0, repeatCols=0, rowSplitRange=None, spaceBefore=None, spaceAfter=None) for i in instructions: data.append([ i.line, i.name, i.bound, i.oname, i.descr, Paragraph(i.exc, styles['Normal']), Paragraph(i.degr, styles['Normal']) ]) t = Table(data) table_style = TableStyle([ ('ALIGN', (1, 1), (6, 1), 'CENTER'), ('INNERGRID', (0, 1), (-1, -1), 0.25, colors.black), ('BOX', (0, 1), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ]) k = 1 for i in libinstructions: row = i.line + 1 k += 1 #row number table_style.add('TEXTCOLOR', (0, row), (6, row), colors.red) table_style.add('ALIGN', (0, 1), (-7, -1), 'CENTER') table_style.add('ALIGN', (0, 2), (-5, -1), 'CENTER') table_style.add('ALIGN', (1, 1), (-6, -1), 'LEFT') t.setStyle(table_style) elements.append(t) elements.append(PageBreak()) doc.build(elements) fs = FileSystemStorage("/tmp") with fs.open(filename) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="{}"'.format( filename) return response return response
def header(canvas, doc): global margin canvas.saveState() canvas.setFont('Helvetica-Bold', 11) canvas.drawString( margin, pagesizes.letter[1] - margin * 1.2, "%s: verses %d-%d words long, at least %d verses apart" % (TITLE, MIN_WORDS, MAX_WORDS, MIN_DISTANCE)) canvas.drawString(margin, margin, "Page %d" % (doc.page)) canvas.restoreState() # convert verses into pdf paragraphs selected = map(verse_to_table, selected) # build pdf table style = TableStyle() style.add('VALIGN', (0, 0), (-1, -1), 'TOP') style.add('GRID', (0, 0), (-1, -1), 1, colors.black) table = Table(selected, [width * 0.2, width * 0.8]) table.setStyle(style) # build pdf output doc = SimpleDocTemplate("out_quotingbee.pdf", pagesize=pagesizes.letter, topMargin=margin * 1.5, leftMargin=margin, bottomMargin=margin * 1.5, rightMargin=margin) doc.build([table], onFirstPage=header, onLaterPages=header)
def tablacuadro(self, pdf, doc, y, userdjango, formulario_id): usuariomodelo = Usuario.objects.get(usuario=userdjango) formularios = usuariomodelo.formulario_set.get( pk=formulario_id) # lista delformulario nuevas_condiciones = formularios.condiciones.split( ",") # arreglo de string ['0.0121', '0.0106'] condiciones_id = [ int(valor_condi) for valor_condi in nuevas_condiciones ] # arreglo de enteros styles = getSampleStyleSheet() style = ParagraphStyle(name='right', parent=styles['Normal'], fontName='Helvetica', fontSize=8.2, leading=8) stylecondi = ParagraphStyle(name='right', parent=styles['Normal'], fontName='Helvetica', fontSize=8, leading=8) encabezados = ('Criterio 1', 'Criterio 2', 'Parámetro y criterio 3', 'Condición') # Creamos una lista de tuplas que van a contener a las personas tabla1 = [] tabla2 = [] tabla3 = [] filasPagina = 28 tabla4 = [] cantidad = 0 tablitas = [] dimensiones = [] for criterios1 in Criterio.objects.filter(nivel=0): for criterios2 in Criterio.objects.filter( nivel=1, idCriterioPadre=criterios1.idCriterio): for criterios3 in Criterio.objects.filter( nivel=2, idCriterioPadre=criterios2.idCriterio): # Aqui el código para las condiciones (Solo si se seleccionaron en el formulario) for valor in condiciones_id: if Condicion.objects.filter( idCondicion=valor, idCriterio=criterios3.idCriterio).exists(): nuevovalor = Condicion.objects.get( idCondicion=valor) C4 = Paragraph(nuevovalor.nombre, stylecondi) tabla4 = tabla4 + [(C4, '')] cantidad = cantidad + 1 if cantidad > filasPagina: dimensiones.append(cantidad) if len(tabla4) < 1: print("hola") if True: tablaCriterio4 = Table( tabla4, colWidths=[4.6 * cm, 0 * cm]) # Estilos para las tablas de criterios 4 tablaCriterio4.setStyle( TableStyle([ # La primera fila(encabezados) va a estar centrada ('ALIGN', (0, 0), (-1, -1), 'LEFT' ), # Los bordes de todas las celdas serán de color negro y con un grosor de 1 ('LINEBELOW', (0, 0), (-1, -1), 0, colors.white), # ('BOX',(0,0),(-1,-1),0,colors.white), # El tamaño de las letras de cada una de las celdas será de 10 ('FONTSIZE', (0, 0), (-1, -1), 8), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) c3 = Paragraph(criterios3.nombre, style) tabla3 = tabla3 + [(c3, tablaCriterio4)] print("hola") if True: tablaCriterio3 = Table( tabla3, colWidths=[7 * cm, 4.6 * cm]) # Estilos para las tablas de criterios 3 tablaCriterio3.setStyle( TableStyle([ # La primera fila(encabezados) va a estar centrada ('ALIGN', (0, 0), (-1, -1), 'LEFT' ), # Los bordes de todas las celdas serán de color negro y con un grosor de 1 ('LINEBELOW', (0, 0), (-1, -1), 0, colors.black), # ('BOX',(0,0),(-1,-1),0,colors.white), # El tamaño de las letras de cada una de las celdas será de 10 ('FONTSIZE', (0, 0), (-1, -1), 8), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) c2 = Paragraph(criterios2.nombre, style) tabla2 = tabla2 + [(c2, tablaCriterio3)] tabla3 = [] print("hola") if True: tablaCriterio2 = Table( tabla2, colWidths=[2.8 * cm, 7 * cm]) # Estilos para las tablas de criterios 2 tablaCriterio2.setStyle( TableStyle([ # La primera fila(encabezados) va a estar centrada ('ALIGN', (0, 0), (-1, -1), 'LEFT' ), # Los bordes de todas las celdas serán de color negro y con un grosor de 1 ('INNERGRID', (0, 0), (-1, -1), 1, colors.black), # El tamaño de las letras de cada una de las celdas será de 10 ('FONTSIZE', (0, 0), (-1, -1), 8), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) c1 = Paragraph(criterios1.nombre, style) tabla1 = tabla1 + [ (c1, tablaCriterio2, '', '') ] print("hola") tablitas.append(tabla1) cantidad = 0 tabla1 = [] tabla2 = [] tabla3 = [] tabla4 = [] C4 = Paragraph(nuevovalor.nombre, stylecondi) tabla4 = tabla4 + [(C4, '')] cantidad = cantidad + 1 if not tabla4: tabla4 = tabla4 + [('', '')] tablaCriterio4 = Table(tabla4, colWidths=[4.6 * cm, 0 * cm]) # Estilos para las tablas de criterios 4 tablaCriterio4.setStyle( TableStyle([ # La primera fila(encabezados) va a estar centrada ('ALIGN', (0, 0), (-1, -1), 'LEFT'), # Los bordes de todas las celdas serán de color negro y con un grosor de 1 ('LINEBELOW', (0, 0), (-1, -1), 0, colors.white), # ('BOX',(0,0),(-1,-1),0,colors.white), # El tamaño de las letras de cada una de las celdas será de 10 ('FONTSIZE', (0, 0), (-1, -1), 8), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) c3 = Paragraph(criterios3.nombre, style) tabla3 = tabla3 + [(c3, tablaCriterio4)] tabla4 = [] tablaCriterio3 = Table(tabla3, colWidths=[7 * cm, 4.6 * cm]) # Estilos para las tablas de criterios 3 tablaCriterio3.setStyle( TableStyle([ # La primera fila(encabezados) va a estar centrada ('ALIGN', (0, 0), (-1, -1), 'LEFT'), # Los bordes de todas las celdas serán de color negro y con un grosor de 1 ('LINEBELOW', (0, 0), (-1, -1), 0, colors.black), # ('BOX',(0,0),(-1,-1),0,colors.white), # El tamaño de las letras de cada una de las celdas será de 10 ('FONTSIZE', (0, 0), (-1, -1), 8), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) c2 = Paragraph(criterios2.nombre, style) tabla2 = tabla2 + [(c2, tablaCriterio3)] tabla3 = [] tablaCriterio2 = Table(tabla2, colWidths=[2.8 * cm, 7 * cm]) # Estilos para las tablas de criterios 2 tablaCriterio2.setStyle( TableStyle([ # La primera fila(encabezados) va a estar centrada ('ALIGN', (0, 0), (-1, -1), 'LEFT'), # Los bordes de todas las celdas serán de color negro y con un grosor de 1 ('INNERGRID', (0, 0), (-1, -1), 1, colors.black), # El tamaño de las letras de cada una de las celdas será de 10 ('FONTSIZE', (0, 0), (-1, -1), 8), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) c1 = Paragraph(criterios1.nombre, style) tabla1 = tabla1 + [(c1, tablaCriterio2, '', '')] tabla2 = [] tablitas.append(tabla1) dimensiones.append(cantidad) # Establecemos el tamaño de cada una de las columnas de la tabla for tablita, dim in zip(tablitas, dimensiones): print("debe de haber varias" + str(dim)) detalle_orden = Table([encabezados] + tablita, colWidths=[2.7 * cm, 3 * cm, 7 * cm, 5 * cm], repeatRows=1) tblStyle = TableStyle([ ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBELOW', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (0, -1), 1, colors.black) ]) tblStyle.add('BACKGROUND', (0, 0), (1, 0), colors.lightblue) tblStyle.add( 'BACKGROUND', (0, 1), (-1, -1), colors.white ) # Aplicamos estilos a la celda principal de la tabla detalle_orden detalle_orden.setStyle( TableStyle([ # La primera fila(encabezados) va a estar centrada ('ALIGN', (0, 0), (-1, -3), 'CENTER'), # Los bordes de todas las celdas serán de color negro y con un grosor de 1 ('GRID', (0, 0), (-1, -1), 1, colors.black), # El tamaño de las letras de cada una de las celdas será de 10 ('FONTSIZE', (0, 0), (-1, -1), 8), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) detalle_orden.wrapOn(pdf, 800, 600) # Definimos la coordenada donde se dibujará la tabl detalle_orden.drawOn(pdf, 30, 20 * (filasPagina + 1 - dim) + 50) pdf.showPage()
def _base_table_style(self): style = TableStyle([]) style.add('FONT', (0, 0), (-1, -1), self.font_name) return style
balance += local rows.append([None, other_name, other_val]) rows.append([None, split.account.get_full_name().replace('.', ':') + (' @ ' + str(rate) if rate != 1 else ''), None, local_val]) rows.append([None, None, None, None, LOCAL + str(balance)]) rows.append(['Grand Total', None, None, None, LOCAL + str(balance)]) ts.add('LINEABOVE', (0, -1), (-1, -1), 1.0, colors.black) ts.add('FONT', (0, -1), (-1, -1), 'Helvetica-BoldOblique') t = Table(rows, [1 * inch, 3.25 * inch, 0.75 * inch, 0.75 * inch, 0.75 * inch], repeatRows=1) t.setStyle(ts) elements.append(t) space = PageBreak() elements.append(space) header = Paragraph('Expenses', styles['Heading1']) elements.append(header) expense_local = Decimal()
class pdfgen: def __init__(self, crossword, savename): self.key = crossword.mergekey self.bars = crossword.bars self.c = canvas.Canvas(savename) #self.c.save() pdfmetrics.registerFont(TTFont('David', 'DavidCLM-Medium.ttf')) self.styles = { 'default': ParagraphStyle('default', fontSize=8, fontName='David', alignment=TA_RIGHT), 'subtitle': ParagraphStyle('subtitle', fontSize=11, fontName='David', alignment=TA_RIGHT, spaceAfter=5) } self.keyStyle = self.styles['default'] self.keyh = [Paragraph('<u>ןזואמ</u>', self.styles['subtitle'])] self.keyv = [Paragraph('<u>ךנואמ</u>', self.styles['subtitle'])] self.gridsize = crossword.gridsize self.tableData = [['' for l in range(crossword.gridsize)] for i in range(crossword.gridsize)] self.tableStyle = TableStyle([('FONT', (0, 0), (-1, -1), 'David'), ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('FONTSIZE', (0, 0), (-1, -1), 9), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('BOX', (0, 0), (-1, -1), 0.7, black), ('GRID', (0, 0), (-1, -1), 0.7, black)]) self.table = None def pdfkeycreate(self): for i, intersection in enumerate(self.key): try: temph = simpleSplit((intersection['H']), 'David', 8, 3.9 * cm) #temph.reverse() temph[0] = ((temph[0][::-1] + "." + str(i + 1))) self.keyh.append(Paragraph(temph[0], self.styles['default'])) for item in temph[1:]: self.keyh.append( Paragraph((item[::-1]), self.styles['default'])) except KeyError: pass try: tempv = simpleSplit((intersection['V']), 'David', 8, 3.9 * cm) tempv[0] = ((tempv[0][::-1] + "." + str(i + 1))) self.keyv.append(Paragraph(tempv[0], self.styles['default'])) for item in tempv[1:]: self.keyv.append( Paragraph((item[::-1]), self.styles['default'])) except KeyError: pass def tableDataCreate(self): for i, intersection in enumerate(self.key): self.tableData[intersection['P'][1]][self.gridsize - 1 - intersection['P'][0]] = i + 1 def tableStyleCreate(self): for i, line in enumerate(self.bars): for l, bar in enumerate(line): if ('H' in bar) and ('V' in bar) and ('V' in self.bars[ i - 1][l]) and ('H' in self.bars[i][l - 1]): self.tableStyle.add('BACKGROUND', (self.gridsize - 1 - l, i), (self.gridsize - 1 - l, i), black) if 'H' in bar: self.tableStyle.add('LINEBEFORE', (self.gridsize - 1 - l, i), (self.gridsize - 1 - l, i), 1.6, black) if 'V' in bar: self.tableStyle.add('LINEBELOW', (self.gridsize - 1 - l, i), (self.gridsize - 1 - l, i), 1.6, black) def tableCreate(self): self.table = Table(self.tableData, colWidths=1.2 * cm, rowHeights=1.2 * cm, style=self.tableStyle) def keydraw(self): hFrame1 = Frame(15.45 * cm, 1 * cm, 4.75 * cm, 11.5 * cm) hFrame2 = Frame(10.55 * cm, 1 * cm, 4.75 * cm, 11.5 * cm) hFrame1.addFromList(self.keyh[:26], self.c) hFrame2.addFromList(self.keyh[26:], self.c) vFrame1 = Frame(5.7 * cm, 1 * cm, 4.75 * cm, 11.5 * cm) vFrame2 = Frame(0.8 * cm, 1 * cm, 4.75 * cm, 11.5 * cm) vFrame1.addFromList(self.keyv[:26], self.c) vFrame2.addFromList(self.keyv[26:], self.c) tFrame = Frame(0.8 * cm, 11.3 * cm, 19.4 * cm, 16.1 * cm, showBoundary=1) tFrame.add(self.table, self.c) self.c.drawCentredString(10.5 * cm, 28.4 * cm, 'Created with WordCrusader by Yotam Hochman') self.c.save()
def ramassagePdfParClasse(request,id_ramassage,totalParmois): """Renvoie le fichier PDF du ramassage par classe correspondant au ramassage dont l'id est id_ramassage si total vaut 1, les totaux par classe et matière sont calculés""" parmois, total = divmod(int(totalParmois),2) ramassage=get_object_or_404(Ramassage,pk=id_ramassage) LISTE_MOIS=["","Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"] response = HttpResponse(content_type='application/pdf') if Ramassage.objects.filter(moisFin__lt=ramassage.moisFin).exists():# s'il existe un ramassage antérieur debut = Ramassage.objects.filter(moisFin__lt=ramassage.moisFin).aggregate(Max('moisFin'))['moisFin__max'] + timedelta(days=1) else: debut = Semaine.objects.aggregate(Min('lundi'))['lundi__min'] fin = ramassage.moisFin moisdebut = 12*debut.year+debut.month-1 decomptes = Ramassage.objects.decompteRamassage(ramassage, csv = False, parClasse = True, parMois=bool(parmois)) nomfichier="ramassagePdfParclasse{}_{}-{}_{}.pdf".format(debut.month,debut.year,fin.month,fin.year) response['Content-Disposition'] = "attachment; filename={}".format(nomfichier) pdf = easyPdf(titre="Ramassage des colles de {} {} à {} {}".format(LISTE_MOIS[debut.month],debut.year,LISTE_MOIS[fin.month],fin.year),marge_x=30,marge_y=30) largeurcel=(pdf.format[0]-2*pdf.marge_x)/(10+parmois) hauteurcel=30 total=int(total) for classe, listeClasse, nbMatieres in decomptes: totalclasse = 0 pdf.debutDePage(soustitre = classe) nbKolleurs = nbMatieres if total: nbKolleurs += 1 + len([x for x,y,z in listeClasse]) # on rajoute le nombre de matières et 1 pour la classe LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),1,(0,0,0)) ,('BACKGROUND',(0,0),(-1,0),(.6,.6,.6)) ,('VALIGN',(0,0),(-1,-1),'MIDDLE') ,('ALIGN',(0,0),(-1,-1),'CENTRE') ,('FACE',(0,0),(-1,-1),"Helvetica-Bold") ,('SIZE',(0,0),(-1,-1),8)]) data = [["Matière","Établissement","Grade","Colleur"] + (["mois"] if parmois else []) + ["heures"]]+[[""]*(5+parmois) for i in range(min(22,nbKolleurs))] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneMat=ligneEtab=ligneGrade=ligneColleur=ligneMois=1 for matiere, listeEtabs, nbEtabs in listeClasse: totalmatiere = 0 data[ligneMat][0]=matiere if nbEtabs>1: LIST_STYLE.add('SPAN',(0,ligneMat),(0,min(ligneMat+nbEtabs-1,22))) ligneMat+=nbEtabs for etablissement, listeGrades, nbGrades in listeEtabs: data[ligneEtab][1]='Inconnu' if not etablissement else etablissement.title() if nbGrades>1: LIST_STYLE.add('SPAN',(1,ligneEtab),(1,min(ligneEtab+nbGrades-1,22))) ligneEtab+=nbGrades for grade, listeColleurs, nbColleurs in listeGrades: data[ligneGrade][2]=grade if nbColleurs>1: LIST_STYLE.add('SPAN',(2,ligneGrade),(2,min(ligneGrade+nbColleurs-1,22))) ligneGrade+=nbColleurs if parmois:# si on ramassage pour chaque mois for colleur, listeMois, nbMois in listeColleurs: data[ligneColleur][3]=colleur if nbMois>1: LIST_STYLE.add('SPAN',(3,ligneColleur),(3,min(ligneColleur+nbMois-1,22))) ligneColleur+=nbMois for moi, heures in listeMois: totalmatiere += heures if moi<moisdebut: LIST_STYLE.add('TEXTCOLOR',(4,ligneMois),(5,ligneMois),(1,0,0)) data[ligneMois][4]=LISTE_MOIS[moi%12+1] data[ligneMois][5]="{:.02f}h".format(heures/60).replace('.',',') ligneMois+=1 if ligneMois==23 and nbKolleurs>22: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t=Table(data,colWidths=[2*largeurcel,3*largeurcel,largeurcel,3*largeurcel, largeurcel, largeurcel],rowHeights=min((1+nbKolleurs),23)*[hauteurcel]) t.setStyle(LIST_STYLE) w,h=t.wrapOn(pdf,0,0) t.drawOn(pdf,(pdf.format[0]-w)/2,pdf.y-h-hauteurcel/2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage(soustitre = classe) LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),1,(0,0,0)) ,('BACKGROUND',(0,0),(-1,0),(.6,.6,.6)) ,('VALIGN',(0,0),(-1,-1),'MIDDLE') ,('ALIGN',(0,0),(-1,-1),'CENTRE') ,('FACE',(0,0),(-1,-1),"Helvetica-Bold") ,('SIZE',(0,0),(-1,-1),8)]) nbKolleurs-=22 data = [["Matière","Établissement","Grade","Colleur","mois","heures"]]+[[""]*6 for i in range(min(22,nbKolleurs))] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab-=22 ligneGrade-=22 ligneMat-=22 ligneColleur-=22 ligneMois = 1 if ligneMat>1: data[1][0]=matiere if ligneMat>2: LIST_STYLE.add('SPAN',(0,1),(0,min(ligneMat-1,22))) if ligneEtab>1: data[1][1]='Inconnu' if not etablissement else etablissement.title() if ligneEtab>2: LIST_STYLE.add('SPAN',(1,1),(1,min(ligneEtab-1,22))) if ligneGrade>1: data[1][2]=grade if ligneGrade>2: LIST_STYLE.add('SPAN',(2,1),(2,min(ligneGrade-1,22))) if ligneColleur>1: data[1][3]=colleur if ligneColleur>2: LIST_STYLE.add('SPAN',(3,1),(3,min(ligneColleur-1,22))) # fin matière else:# si on ne ramasse pas pour chaque mois mais globalement sur la période de ramassage for colleur, heures in listeColleurs: totalmatiere += heures data[ligneColleur][3]=colleur data[ligneColleur][4]="{:.02f}h".format(heures/60).replace('.',',') ligneColleur+=1 if ligneColleur==23 and nbKolleurs>22: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t=Table(data,colWidths=[2*largeurcel,3*largeurcel,largeurcel,3*largeurcel, largeurcel],rowHeights=min((1+nbKolleurs),23)*[hauteurcel]) t.setStyle(LIST_STYLE) w,h=t.wrapOn(pdf,0,0) t.drawOn(pdf,(pdf.format[0]-w)/2,pdf.y-h-hauteurcel/2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage(soustitre = classe.nom) LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),1,(0,0,0)) ,('BACKGROUND',(0,0),(-1,0),(.6,.6,.6)) ,('VALIGN',(0,0),(-1,-1),'MIDDLE') ,('ALIGN',(0,0),(-1,-1),'CENTRE') ,('FACE',(0,0),(-1,-1),"Helvetica-Bold") ,('SIZE',(0,0),(-1,-1),8)]) nbKolleurs-=22 data = [["Matière","Établissement","Grade","Colleur", "heures"]]+[[""]*5 for i in range(min(22,nbKolleurs))] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab-=22 ligneGrade-=22 ligneMat-=22 ligneColleur=1 if ligneMat>1: data[1][0]=matiere.title() if ligneMat>2: LIST_STYLE.add('SPAN',(0,1),(0,min(ligneMat-1,22))) if ligneEtab>1: data[1][1]='Inconnu' if not etablissement else etablissement.title() if ligneEtab>2: LIST_STYLE.add('SPAN',(1,1),(1,min(ligneEtab-1,22))) if ligneGrade>1: data[1][2]=grade if ligneGrade>2: LIST_STYLE.add('SPAN',(2,1),(2,min(ligneGrade-1,22))) # fin matière totalclasse += totalmatiere if total: LIST_STYLE.add('SPAN',(0,ligneColleur),(3+parmois,ligneColleur)) LIST_STYLE.add('BACKGROUND',(0,ligneColleur),(-1,ligneColleur),(.8,.8,.8)) data[ligneColleur] = ["total {}".format(matiere.title())]+[""]*(3+parmois)+["{:.02f}h".format(totalmatiere/60).replace('.',',')] ligneEtab+=1 ligneGrade+=1 ligneMat+=1 ligneColleur+=1 ligneMois+=1 if ligneColleur==23 and nbKolleurs>22: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t=Table(data,colWidths=[2*largeurcel,3*largeurcel,largeurcel,3*largeurcel, largeurcel],rowHeights=min((1+nbKolleurs),23)*[hauteurcel]) t.setStyle(LIST_STYLE) w,h=t.wrapOn(pdf,0,0) t.drawOn(pdf,(pdf.format[0]-w)/2,pdf.y-h-hauteurcel/2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage(soustitre = classe) LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),1,(0,0,0)) ,('BACKGROUND',(0,0),(-1,0),(.6,.6,.6)) ,('VALIGN',(0,0),(-1,-1),'MIDDLE') ,('ALIGN',(0,0),(-1,-1),'CENTRE') ,('FACE',(0,0),(-1,-1),"Helvetica-Bold") ,('SIZE',(0,0),(-1,-1),8)]) nbKolleurs-=22 data = [["Matière","Établissement","Grade","Colleur"] + (["mois"] if parmois else []) + ["heures"]]+[[""]*(5+parmois) for i in range(min(22,nbKolleurs))] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab-=22 ligneGrade-=22 ligneMat-=22 if parmois: ligneColleur-=22 ligneMois=1 else: ligneColleur=1 # fin classe if total: LIST_STYLE.add('SPAN',(0,ligneColleur),(3+parmois,ligneColleur)) LIST_STYLE.add('BACKGROUND',(0,ligneColleur),(-1,ligneColleur),(.7,.7,.7)) data[ligneColleur] = ["total {}".format(classe)]+[""]*(3+parmois)+["{:.02f}h".format(totalclasse/60).replace('.',',')] ligneEtab+=1 ligneGrade+=1 ligneMat+=1 ligneColleur+=1 t=Table(data,colWidths=[2*largeurcel,3*largeurcel,largeurcel,3*largeurcel,largeurcel],rowHeights=min((1+nbKolleurs),23)*[hauteurcel]) t.setStyle(LIST_STYLE) w,h=t.wrapOn(pdf,0,0) t.drawOn(pdf,(pdf.format[0]-w)/2,pdf.y-h-hauteurcel/2) pdf.finDePage() pdf.save() fichier = pdf.buffer.getvalue() pdf.buffer.close() response.write(fichier) return response
def squareSection( page, location, size, gridspace, linefreq, checkered, rainbow, gridline, linewidth, boxline, checkeredcolor, gridcolor, linecolor, boxcolor, bgndcolor, **excessParams ): """ Places a Cartesian graph in the specified location on the canvas. Keyword arguments: page -- a Canvas instance on which to draw location -- location of the graph as a list of (x, y) tuple size -- size of the graph as (width, height) tuple gridspace -- size of individual grid cells linefreq -- frequency of lines expressed as the number of rows per line checkered -- true for checkered grid rainbow -- true for rainbow grid gridline -- thickness of lines around cells linewidth -- width of each writing line boxline -- thickness of border around graph(s), 0 for no box checkeredcolor -- color of checkered boxes gridcolor -- color of grid lines around cells linecolor -- color of each line boxcolor -- color of box surrounding graph(s) bgndcolor -- color of background of each cell """ # dimensions and spacing (area_w, area_h) = size (loc_x, loc_y) = location (cells_x, cells_y) = (int(area_w / gridspace), int(area_h / gridspace)) grid_w = cells_x * gridspace + boxline grid_h = cells_y * gridspace + boxline xMargins = (area_w - grid_w) / 2 yMargins = (area_h - grid_h) / 2 if cells_x < 1 or cells_y < 1: raise ValueError('Specified dimensions do not fit on page.') # create plain table data = [['' for col in xrange(cells_x)] for row in xrange(cells_y)] table = Table(data, colWidths=gridspace, rowHeights=gridspace) # checkered grid or shaded background pattern = list() if checkered and rainbow: raise ValueError('Grid pattern cannot be both rainbow and checekred.') if checkered: for y in xrange(cells_y): for x in xrange(y % 2, cells_x, 2): c = (x, y) pattern.append(('BACKGROUND', c, c, grey(checkeredcolor))) elif rainbow: rainbow_pattern = rainbowGrid((cells_x, cells_y), darkness=5) for x in xrange(cells_x): for y in xrange(cells_y): c = (x, y) pattern.append(('BACKGROUND', c, c, rainbow_pattern[x][y])) elif bgndcolor != 0: pattern.append(('BACKGROUND', (0, 0), (-1, -1), grey(bgndcolor))) # apply table style style = TableStyle(pattern) style.add('INNERGRID', (0, 0), (-1, -1), gridline, grey(gridcolor)) if boxline != 0: style.add('BOX', (0, 0), (-1, -1), boxline, grey(boxcolor)) table.setStyle(style) # writing lines if linefreq != 0: style = TableStyle() for line in xrange(int(cells_y / linefreq) + 1): rowline = line * linefreq style.add('LINEABOVE', (0, rowline), (-1, rowline), linewidth, grey(linecolor)) table.setStyle(style) # draw graphs frame = Frame( loc_x + xMargins, loc_y + yMargins, grid_w, grid_h, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, ) frame.addFromList([table], page)
def drawCell(): """ Drawing a cell text """ # Finding background cellBackground = self.pageObject.get('PCOLOR') if cellBackground in self.colorList: try: hexCellColor = self.colorList[cellBackground] background = colors.HexColor(str(hexCellColor)) except: background = colors.HexColor('#ffffff') else: background = colors.HexColor('#ffffff') stile = TableStyle([('ROWBACKGROUNDS', (0,0), (0,0), (background, background))]) # Borders bottomLine = int(self.pageObject.get('BottomLine')) topLine = int(self.pageObject.get('TopLine')) leftLine = int(self.pageObject.get('LeftLine')) rightLine = int(self.pageObject.get('RightLine')) lineWidth = float(self.pageObject.get('PWIDTH')) borderColor = self.pageObject.get('PCOLOR2') alignment = " " # Finding value and cell's style if self.version: paras = self.pageObject.findall('para') itexts = self.pageObject.findall('ITEXT') ch = '' matrix = [] if len(itexts)>=1: if len(itexts)>1: for itext in itexts: chtmp = itext.get('CH') ch = ch +" "+ chtmp itext = itexts[0] else: itext = itexts[0] ch = itext.get('CH') if self.version: try: alignment = paras[0].get('ALIGN') except: alignment = "0" else: alignment = itext.get('CAB') if alignment == None: alignment = self.defaultAlignment if alignment == '0': alignment = 'LEFT' elif alignment == '1': alignment = 'CENTER' elif alignment == '2': alignment = 'RIGHT' else: alignment = "LEFT" stile.add('ALIGN', (0,0), (0,0), alignment) # Font Name if self.version: fontName = getPdfFontName(str(itext.get('FONT'))) else: fontName = getPdfFontName(str(itext.get('CFONT'))) stile.add('FONT', (0,0), (0,0), fontName) # Font size if self.version: fontSize = float(itext.get('FONTSIZE')) else: fontSize = float(itext.get('CSIZE')) stile.add('FONTSIZE', (0,0), (0,0), fontSize) # Hex color if self.version: textColor = itext.get('FCOLOR') else: textColor = itext.get('CCOLOR') if textColor in self.colorList: try: hexTextColor = self.colorList[textColor] foreground = colors.HexColor(str(hexTextColor)) except: foreground = colors.HexColor('#000000') else: foreground = colors.HexColor('#000000') stile.add('TEXTCOLOR', (0,0), (0,0), foreground) # Applying attributes if borderColor in self.colorList: try: hexBorderColor = self.colorList[borderColor] except: hexBorderColor = '#000000' else: hexBorderColor = '#000000' stile.add('VALIGN',(0,0),(-1,-1),'TOP') if (bottomLine == 1 and topLine == 1 and leftLine == 1 and rightLine == 1) or (lineWidth > 1): stile.add('BOX', (0,0), (-1,-1), lineWidth, hexBorderColor) else: if bottomLine == 1: stile.add('LINEBELOW', (0,0), (-1,-1), lineWidth, hexBorderColor) elif topLine == 1: stile.add('LINEABOVE', (0,0), (-1,-1), lineWidth, hexBorderColor) if leftLine == 1: stile.add('LINEBEFORE', (0,0), (-1,-1), lineWidth, hexBorderColor) if rightLine == 1: stile.add('LINEAFTER', (0,0), (-1,-1), lineWidth, hexBorderColor) # Creating and filling data = [] data.append(self.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize)) matrix.append(data) if len(matrix) > 0: table=Table(data=matrix, colWidths=width, rowHeights=height, style=stile) # Adding cell to the frame and save it lst = [] lst.append(table) f = Frame(x1=(xPos - self.pageProperties[self.pdfPage][9]), y1=(self.pageProperties[0][7] - yPos - height + self.pageProperties[self.pdfPage][10] - 12), width=width, height=(height + 12), showBoundary=0) f.addFromList(lst, self.canvas) self.canvas.saveState()
def drawTable(): """ Drawing a table """ matrix = [] vector = [] # Total of element's table actualGroup = self.group cells = int(self.tablesProperties[actualGroup]["cells"]) columns = int(self.tablesProperties[actualGroup]["columns"]) rows = int(self.tablesProperties[actualGroup]["rows"]) # Finding cell size cont = 0 widths = [] heights = [] innerIterator = self.iterator xpos = float(self.pageObjects[innerIterator].get("XPOS")) ypos = float(self.pageObjects[innerIterator].get("YPOS")) while actualGroup == self.group and innerIterator < len(self.pageObjects): cont += 1 actualGroup = self.pageObjects[innerIterator].get("GROUPS") if actualGroup == self.group: width = float(self.pageObjects[innerIterator].get("WIDTH")) widths.append(width) if cont == columns: height = float(self.pageObjects[innerIterator].get("HEIGHT")) heights.append(height) cont = 0 innerIterator += 1 # General table style (always the same!!!) stile = TableStyle([]) stile.add("VALIGN", (0, 0), (-1, -1), "TOP") # Applying stile, font and color for every cell contColumns = -1 contRows = 0 ch = "" cont = 0 vector = [] actualGroup = self.group innerIterator = self.iterator while actualGroup == self.group and innerIterator < len(self.pageObjects): actualGroup = self.pageObjects[innerIterator].get("GROUPS") actualPage = int(self.pageObjects[innerIterator].get("OwnPage")) if actualPage != self.pdfPage: innerIterator += 1 continue if actualGroup == self.group: # Conversion between index - row/column contColumns += 1 if contColumns == columns: contColumns = 0 contRows += 1 # Finding background cellBackground = self.pageObjects[innerIterator].get("PCOLOR") if cellBackground in self.colorList: try: hexColor = self.colorList[cellBackground] background = colors.HexColor(str(hexColor)) except: background = colors.HexColor("#ffffff") else: background = colors.HexColor("#ffffff") stile.add( "ROWBACKGROUNDS", (contColumns, contRows), (contColumns, contRows), (background, background) ) itexts = self.pageObjects[innerIterator].findall("ITEXT") put = False for itext in itexts: ch = itext.get("CH") # Horizontal alignment alignment = itext.get("CAB") if alignment == "0": alignment = "LEFT" elif alignment == "1": alignment = "CENTER" elif alignment == "2": alignment = "RIGHT" stile.add("ALIGN", (contColumns, contRows), (contColumns, contRows), alignment) # Font name fontName = getPdfFontName(str(itext.get("CFONT"))) stile.add("FONT", (contColumns, contRows), (contColumns, contRows), fontName) # Font size fontSize = float(itext.get("CSIZE")) stile.add("FONTSIZE", (contColumns, contRows), (contColumns, contRows), fontSize) # Hex color textColor = itext.get("CCOLOR") if textColor in self.colorList: try: hexColor = self.colorList[textColor] foreground = colors.HexColor(str(hexColor)) except: foreground = colors.HexColor("#000000") else: foreground = colors.HexColor("#000000") stile.add("TEXTCOLOR", (contColumns, contRows), (contColumns, contRows), foreground) # Borders actualPageObject = self.pageObjects[innerIterator] bottomLine = int(actualPageObject.get("BottomLine")) topLine = int(actualPageObject.get("TopLine")) leftLine = int(actualPageObject.get("LeftLine")) rightLine = int(actualPageObject.get("RightLine")) lineWidth = float(actualPageObject.get("PWIDTH")) borderColor = actualPageObject.get("PCOLOR2") if borderColor in self.colorList: try: hexBorderColor = self.colorList[borderColor] except: hexBorderColor = "#000000" else: hexBorderColor = "#000000" if bottomLine == 1 and topLine == 1 and leftLine == 1 and rightLine == 1: stile.add( "BOX", (contColumns, contRows), (contColumns, contRows), lineWidth, hexBorderColor ) else: if bottomLine == 1: stile.add( "LINEBELOW", (contColumns, contRows), (contColumns, contRows), lineWidth, hexBorderColor, ) elif topLine == 1: stile.add( "LINEABOVE", (contColumns, contRows), (contColumns, contRows), lineWidth, hexBorderColor, ) if leftLine == 1: stile.add( "LINEBEFORE", (contColumns, contRows), (contColumns, contRows), lineWidth, hexBorderColor, ) if rightLine == 1: stile.add( "LINEAFTER", (contColumns, contRows), (contColumns, contRows), lineWidth, hexBorderColor, ) vector.append(self.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize)) put = True if put == False: vector.append("") cont += 1 if cont == columns: matrix.append(vector) vector = [] cont = 0 innerIterator += 1 # Creating and filling table table = Table(matrix, style=stile, colWidths=widths[:columns], rowHeights=heights[:rows]) # Adding cell to the frame and save it lst = [] lst.append(table) # Effective table size sumRows = 0 sumColumns = 0 for i in range(0, rows): sumRows += heights[i] for i in range(0, columns): sumColumns += widths[i] f = Frame( x1=(xpos - self.pageProperties[self.pdfPage][9]), y1=(self.pageProperties[self.pdfPage][7] - ypos - sumRows + self.pageProperties[self.pdfPage][10] - 12), width=sumColumns, height=(sumRows + 12), showBoundary=0, ) f.addFromList(lst, self.canvas) self.canvas.saveState() self.iterator += cells - 1
def ramassagePdf(request, id_ramassage, parMois = 0): """Renvoie le fichier PDF du ramassage par année/effectif correspondant au ramassage dont l'id est id_ramassage""" parMois = int(parMois) // 2 ramassage=get_object_or_404(Ramassage,pk=id_ramassage) LISTE_MOIS=["","Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"] LISTE_MOIS_COURT=["jan","fev","mar","avr","mai","juin","juil","aou","sep","oct","nov","dec"] response = HttpResponse(content_type='application/pdf') if Ramassage.objects.filter(moisFin__lt=ramassage.moisFin).exists(): #s'il existe un ramassage antérieur debut = Ramassage.objects.filter(moisFin__lt=ramassage.moisFin).aggregate(Max('moisFin'))['moisFin__max']+timedelta(days=1) else: debut = Semaine.objects.aggregate(Min('lundi'))['lundi__min'] fin = ramassage.moisFin moisdebut = 12*debut.year+debut.month-1 listeDecompte, effectifs = Ramassage.objects.decompteRamassage(ramassage, csv = False, parClasse = False, parMois=parMois) nomfichier="ramassage{}_{}-{}_{}.pdf".format(debut.month,debut.year,fin.month,fin.year) response['Content-Disposition'] = "attachment; filename={}".format(nomfichier) pdf = easyPdf(titre="Ramassage des colles de {} {} à {} {}".format(LISTE_MOIS[debut.month],debut.year,LISTE_MOIS[fin.month],fin.year),marge_x=30,marge_y=30) largeurcel=(pdf.format[0]-2*pdf.marge_x)/(9+parMois+len(effectifs)) hauteurcel=30 nbKolleurs=sum([z for x,y,z in listeDecompte]) pdf.debutDePage() LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),1,(0,0,0)) ,('BACKGROUND',(0,0),(-1,0),(.6,.6,.6)) ,('VALIGN',(0,0),(-1,-1),'MIDDLE') ,('ALIGN',(0,0),(-1,-1),'CENTRE') ,('FACE',(0,0),(-1,-1),"Helvetica-Bold") ,('SIZE',(0,0),(-1,-1),8)]) data = [["Matière","Établissement","Grade","Colleur"] + (["Mois"] if parMois else []) + ["{}è. ann.\n{}".format(annee,effectif) for annee,effectif in effectifs]]+[[""]*(4+parMois+len(effectifs)) for i in range(min(23,nbKolleurs))] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneMat=ligneEtab=ligneGrade=ligneColleur=ligneMois=1 for matiere, listeEtabs, nbEtabs in listeDecompte: data[ligneMat][0]=matiere.title() if nbEtabs>1: LIST_STYLE.add('SPAN',(0,ligneMat),(0,min(ligneMat+nbEtabs-1,23))) ligneMat+=nbEtabs for etablissement, listeGrades, nbGrades in listeEtabs: data[ligneEtab][1]=etablissement.title() if nbGrades>1: LIST_STYLE.add('SPAN',(1,ligneEtab),(1,min(ligneEtab+nbGrades-1,23))) ligneEtab+=nbGrades for grade, listeColleurs, nbColleurs in listeGrades: data[ligneGrade][2]=grade if nbColleurs>1: LIST_STYLE.add('SPAN',(2,ligneGrade),(2,min(ligneGrade+nbColleurs-1,23))) ligneGrade+=nbColleurs if parMois: for colleur, listeMois, nbMois in listeColleurs: data[ligneColleur][3]=colleur if nbMois>1: LIST_STYLE.add('SPAN',(3,ligneColleur),(3,min(ligneColleur+nbMois-1,23))) ligneColleur+=nbMois for moi, decomptes in listeMois: if moi < moisdebut: LIST_STYLE.add('TEXTCOLOR',(4,ligneMois),(4+len(effectifs),ligneMois),(1,0,0)) data[ligneMois][4]=LISTE_MOIS_COURT[moi%12] for i in range(len(effectifs)): data[ligneMois][i+5]="{:.02f}h".format(decomptes[i]/60).replace('.',',') ligneMois+=1 if ligneMois==24 and nbKolleurs>23: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t=Table(data,colWidths=[2*largeurcel,3*largeurcel,largeurcel,3*largeurcel,largeurcel]+[largeurcel]*len(effectifs),rowHeights=min((1+nbKolleurs),24)*[hauteurcel]) t.setStyle(LIST_STYLE) w,h=t.wrapOn(pdf,0,0) t.drawOn(pdf,(pdf.format[0]-w)/2,pdf.y-h-hauteurcel/2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage() LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),1,(0,0,0)) ,('BACKGROUND',(0,0),(-1,0),(.6,.6,.6)) ,('VALIGN',(0,0),(-1,-1),'MIDDLE') ,('ALIGN',(0,0),(-1,-1),'CENTRE') ,('FACE',(0,0),(-1,-1),"Helvetica-Bold") ,('SIZE',(0,0),(-1,-1),8)]) nbKolleurs-=23 data = [["Matière","Établissement","Grade","Colleur","Mois"]+["{}è. ann.\n{}".format(annee,effectif) for annee,effectif in effectifs]]+[[""]*(5+len(effectifs)) for i in range(min(23,nbKolleurs))] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab-=23 ligneGrade-=23 ligneMat-=23 ligneColleur-=23 ligneMois=1 if ligneMat>1: data[1][0]=matiere.title() if ligneMat>2: LIST_STYLE.add('SPAN',(0,1),(0,min(ligneMat-1,23))) if ligneEtab>1: data[1][1]=etablissement.title() if ligneEtab>2: LIST_STYLE.add('SPAN',(1,1),(1,min(ligneEtab-1,23))) if ligneGrade>1: data[1][2]=grade if ligneGrade>2: LIST_STYLE.add('SPAN',(2,1),(2,min(ligneGrade-1,23))) if ligneColleur>1: data[1][3]= colleur if ligneColleur>2: LIST_STYLE.add('SPAN',(3,1),(3,min(ligneColleur-1,23))) else: for colleur, decomptes in listeColleurs: data[ligneColleur][3]=colleur for i in range(len(effectifs)): data[ligneColleur][i+4]="{:.02f}h".format(decomptes[i]/60).replace('.',',') ligneColleur+=1 if ligneColleur==24 and nbKolleurs>23: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t=Table(data,colWidths=[2*largeurcel,3*largeurcel,largeurcel,3*largeurcel]+[largeurcel]*len(effectifs),rowHeights=min((1+nbKolleurs),24)*[hauteurcel]) t.setStyle(LIST_STYLE) w,h=t.wrapOn(pdf,0,0) t.drawOn(pdf,(pdf.format[0]-w)/2,pdf.y-h-hauteurcel/2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage() LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),1,(0,0,0)) ,('BACKGROUND',(0,0),(-1,0),(.6,.6,.6)) ,('VALIGN',(0,0),(-1,-1),'MIDDLE') ,('ALIGN',(0,0),(-1,-1),'CENTRE') ,('FACE',(0,0),(-1,-1),"Helvetica-Bold") ,('SIZE',(0,0),(-1,-1),8)]) nbKolleurs-=23 data = [["Matière","Établissement","Grade","Colleur"]+["{}è. ann.\n{}".format(annee,effectif) for annee,effectif in effectifs]]+[[""]*(4+len(effectifs)) for i in range(min(23,nbKolleurs))] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab-=23 ligneGrade-=23 ligneMat-=23 ligneColleur=1 if ligneMat>1: data[1][0]=matiere.title() if ligneMat>2: LIST_STYLE.add('SPAN',(0,1),(0,min(ligneMat-1,23))) if ligneEtab>1: data[1][1]=etablissement.title() if ligneEtab>2: LIST_STYLE.add('SPAN',(1,1),(1,min(ligneEtab-1,23))) if ligneGrade>1: data[1][2]=grade if ligneGrade>2: LIST_STYLE.add('SPAN',(2,1),(2,min(ligneGrade-1,23))) t=Table(data,colWidths=[2*largeurcel,3*largeurcel,largeurcel,3*largeurcel]+[largeurcel]*(parMois+len(effectifs)),rowHeights=min((1+nbKolleurs),24)*[hauteurcel]) t.setStyle(LIST_STYLE) w,h=t.wrapOn(pdf,0,0) t.drawOn(pdf,(pdf.format[0]-w)/2,pdf.y-h-hauteurcel/2) pdf.finDePage() pdf.save() fichier = pdf.buffer.getvalue() pdf.buffer.close() response.write(fichier) return response
def toPDF(self): pdfSet = PDFSettings() pdfSet.pdfDir=self.pdfDir pdfSet.addStyles() cW = pdfSet.cW pdfSet.GCN = self.GCN pdfSet.TCN = self.TCN pdfSet.verNum = self.verNum pdfSet.subDate = self.subDate pdfSet.subTime = self.subTime pdfSet.inFileName = self.inFileName pdfSet.testProd = self.testProd #fileNameBase = pdfSet.pdfDir + os.sep + '277-' + self.TCN fileNameBase = pdfSet.pdfDir + os.sep + '277-' + self.subDateTime fileName = fileNameBase + '.pdf' doc = SimpleDocTemplate(fileName, pagesize=letter, leftMargin=pdfSet.marginSize, rightMargin=pdfSet.marginSize, topMargin=pdfSet.marginSize + pdfSet.lineHeight*2, bottomMargin=pdfSet.marginSize + pdfSet.lineHeight*2) doc.leftPadding = 0 Story = [] stylesheet=getSampleStyleSheet() style1 = stylesheet['Normal'] style1.fontName = pdfSet.regFont style1.fontSize = pdfSet.fontSize style1.borderPadding = 0 #codeStyle.leading = 8 style2 = copy.copy(style1) style2.firstLineIndent = -15 style2.leftIndent = 20 style3 = copy.copy(style1) style3.fontName = pdfSet.boldFont tmpPara = "Payor: %s [%s] - Received %s, processed %s" % (self.payor.Name, self.payor.ID, self.date837Rec, self.date837Rec) Story.append(Paragraph(tmpPara, style1)) Story.append(Spacer(1,pdfSet.lineHeight*.5)) tmpPara = "Submitter: %s [%s] %s - %s" % (self.submitter.Name, self.submitter.ID, self.submitter.amount, self.submitter.action) Story.append(Paragraph(tmpPara, style1)) if len(self.submitter.amtString) > 1: Story.append(Paragraph(self.submitter.amtString, style1)) tmpPara = self.submitter.qtyString + ' - Status code: ' + self.submitter.statusCode Story.append(Paragraph(tmpPara, style1)) Story.append(Spacer(1,pdfSet.lineHeight*.5)) for billProv in self.bP: #bpSection = [] tmpPara = "Billing Provider: %s [%s] %s - %s" % (billProv.Name, billProv.ID, billProv.amount, billProv.action) Story.append(Paragraph(tmpPara, style1)) if len(billProv.amtString) > 1: Story.append(Paragraph(billProv.amtString, style1)) tmpPara = billProv.qtyString + ' - Status code: ' + billProv.statusCode Story.append(Paragraph(tmpPara, style1)) #bpSec.append(Spacer(1,pdfSet.lineHeight*.5)) if len(billProv.claim) > 0: statWidths = [26*cW, 18*cW, 9*cW, 8*cW, 8*cW, 5*cW, 3*cW, 9*cW, 18*cW, 9*cW] statStyle = TableStyle([('VALIGN', (0,0), (-1,-1), 'TOP'), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ('FONT', (0,0), (-1,-1), pdfSet.regFont, pdfSet.fontSize), ('BOTTOMPADDING',(0,0),(-1,-1),pdfSet.pad), ('TOPPADDING', (0,0),(-1,-1),pdfSet.pad), ('RIGHTPADDING', (0,0),(-1,-1),pdfSet.pad), ('LEFTPADDING', (0,0),(-1,-1),pdfSet.pad), ('LINEBELOW', (0,1), (-1,1), 1, (0,0,0,1))]) statStyle.add('ALIGN', (4,0), (4,-1), 'DECIMAL') errStyle = copy.copy(statStyle) errStyle.add('FONT', (0,0), (-1,-1), pdfSet.regFont, pdfSet.fontSize) statLines = [(None, None, None, None, None, None, None, None, 'Status codes', None), ("Patient", "Claim Number", None, None, None, None, None, "Action", 'Cat. Code Source', None)] for clm in billProv.claim: for clmLine in clm.line: if clmLine.action == 'Accept': statLines.append([clmLine.Name, clmLine.ID, clmLine.date1, clmLine.date2, clmLine.amount, None, None, clmLine.action, clmLine.statusCode, None]) else: statLines.append([clmLine.Name, clmLine.ID, clmLine.date1, clmLine.date2, clmLine.amount, None, '**', clmLine.action, clmLine.statusCode, '**']) tbl = Table(statLines, colWidths=statWidths, rowHeights=None, style=statStyle) tbl.hAlign = 'LEFT' tbl.leftPadding = 0 Story.append(tbl) Story.append(Spacer(1,pdfSet.lineHeight*2)) #Story.append(KeepTogether(bpSection)) glossary = [] glossary.append(Paragraph("GLOSSARY: Code categories, status codes, and entities", style3)) for gloss in (self.catGlossary, self.codeGlossary, self.srcGlossary): if len(gloss) > 0: for code, message in gloss.iteritems(): tmpPara = "%s: %s " % (code, message) glossary.append(Paragraph(tmpPara, style2)) Story.append(KeepTogether(glossary)) attempt = 1 while attempt > 0: #avoid blowing up due to duplicate filename try: open(fileName, 'wb') doc.build(Story, onFirstPage=pdfSet.firstPage, onLaterPages=pdfSet.laterPages) attempt = 0 except IOError: doc.filename = fileName = '%s(%s).pdf' % (fileNameBase, attempt) attempt += 1 os.startfile(fileName)
def define_avg_time_table_style(): table_style = TableStyle() # All rows table_style.add('TOPPADDING', (0, 0), (-1, -1), 0) table_style.add('BOTTOMPADDING', (0, 0), (-1, -1), 0) table_style.add('VALIGN', (0, 0), (-1, -1), "MIDDLE") table_style.add('INNERGRID', (0, 1), (-1, -1), 0.2 * mm, colors.black) table_style.add('BOX', (0, 1), (-1, -1), 0.4 * mm, colors.black) # Header row table_style.add('INNERGRID', (0, 0), (-1, 0), 0.2 * mm, colors.black) table_style.add('BOX', (0, 0), (-1, 0), 0.4 * mm, colors.black) table_style.add('BACKGROUND', (0, 0), (-1, 0), colors.black) table_style.add('ALIGN', (0, 0), (-1, 0), "CENTER") return table_style
def create_dictionary(self): self.file = self.parcial_path + "/dictionary_" + self.table.name + ".pdf" doc = SimpleDocTemplate(self.file, pagesize=landscape(A4)) story = list() styles = getSampleStyleSheet() styles.add( ParagraphStyle( name='CustomTitle', fontName='Times-Bold', fontSize=14, alignment=TA_CENTER, textColor=colors.black, )) # Title title = "DICIONÁRIO DE DADOS" story.append(Paragraph(title, styles['CustomTitle'])) story.append(Spacer(1, 48)) # Basic Info story.append(Paragraph("<b>RECURSO: </b>", styles['Normal'])) story.append(Spacer(1, 4)) story.append(Paragraph(self.resource.name, styles['Normal'])) story.append(Spacer(1, 10)) story.append( Paragraph("<b>FREQUÊNCIA DE ATUALIZAÇÃO: </b>", styles['Normal'])) story.append(Spacer(1, 4)) if self.resource.schedule_type == Resource.TYPE_DAY: story.append(Paragraph('DIARIAMENTE', styles['Normal'])) elif self.resource.schedule_type == Resource.TYPE_WEEK: story.append(Paragraph('SEMANALMENTE', styles['Normal'])) elif self.resource.schedule_type == Resource.TYPE_MONTH: story.append(Paragraph('MENSALMENTE', styles['Normal'])) elif self.resource.schedule_type == Resource.TYPE_YEAR: story.append(Paragraph('ANUALMENTE', styles['Normal'])) story.append(Spacer(1, 10)) story.append(Paragraph('<b>DESCRIÇÃO:</b>', styles['Normal'])) story.append( Paragraph(self.data_dictionary.description, styles['Normal'])) story.append(Spacer(1, 6)) # TABLE # Table Title story.append(Spacer(1, 48)) # Table Data data = [ ['COLUNA', 'TIPO', 'TAMANHO', 'ACEITA NULO', 'DESCRIÇÃO'], ] for column in DBColumn.objects.filter( db_table=self.table).order_by('id'): aceita_nulo = 'NÃO' if column.not_null == 'YES': aceita_nulo = 'SIM' tamanho = '' if column.size > 0: tamanho = column.size data.append([ column.name, column.type.upper(), tamanho, aceita_nulo, column.dd_description ]) for temp_table in DBTable.objects.filter(db_table=self.table): for column in DBColumn.objects.filter( db_table=temp_table).order_by('id'): aceita_nulo = 'NÃO' if column.not_null == 'YES': aceita_nulo = 'SIM' tamanho = '' if column.size > 0: tamanho = column.size data.append([ temp_table.name + "_" + column.name, column.type.upper(), tamanho, aceita_nulo, column.dd_description ]) table = Table(data, colWidths=(60 * mm, 50 * mm, 25 * mm, 30 * mm, 80 * mm)) table_style = TableStyle() table_style.add('BOX', (0, 0), (-1, -1), 0.50, colors.black) table_style.add('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black) table_style.add('FONTNAME', (0, 0), (-1, 0), 'Times-Bold') table_style.add('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey) table_style.add('ALIGNMENT', (2, 1), (-1, -1), 'CENTER') table.setStyle(table_style) story.append(table) doc.build(story)
def realestateToPDF(context, request): # this translates AND encodes to utf-8 def _(msg, mapping=None): msg = safe_unicode(msg) return translate(msg, domain='collective.realestatebroker', mapping=mapping, context=request).encode('utf-8') def trans(msg): """Just translate, used for field names.""" msg = safe_unicode(msg) return translate(msg, domain='collective.realestatebroker', context=request) # create the document structure style = rebStyleSeet() colors = rebColors() album_view = context.restrictedTraverse('@@realestate_album') realestate_view = context.restrictedTraverse('@@realestate') floorplan_view = context.restrictedTraverse('@@realestate_floorplans') structure = [] # Front page utility = queryUtility(IFrontPage) if not utility: structure += frontpage(context, request, style) else: structure += utility(context, request, style) # Second page: desc, main text. description = context.Description() structure.append(Paragraph(description, style['description'])) text = hack_kupu_text(context.getText()) structure.append(Paragraph(text, style['normal'])) structure.append(PageBreak()) # Photos, sorted by page. photo_floors = album_view.photos_for_pdf() for floor in photo_floors: structure.append(Paragraph(trans(floor['floorname']), style['heading1'])) for photo in floor['photos']: structure += insert_image(photo) structure.append(PageBreak()) #structure.append(PageBreak()) # Floorplans floorplan_floors = floorplan_view.floorplans_for_pdf() for floor in floorplan_floors: name = _(u'Floor plan for ${floorname}', mapping={'floorname': floor['floorname']}) structure.append(Paragraph(name, style['heading1'])) for photo in floor['photos']: structure += insert_image(photo, full_width=True) structure.append(PageBreak()) # Characteristics structure.append(Paragraph(_(u'Characteristics'), style['heading1'])) data = [] index = 0 heading_rows = [] even_rows = [] data.append([Paragraph(_(u'Object data'), style['table_header']), '']) heading_rows.append(index) index += 1 for local_index, field in enumerate(realestate_view.base_fields()): label = trans(field.widget.Label(context)) value = field.getAccessor(context)() if isinstance(value, ListType) or isinstance(value, TupleType): value = u', '.join(value) if isinstance(value, BooleanType): if value: value = _(u'True') else: value = _(u'False') try: value = trans(value) except TypeError: pass value = unicode(value) data.append([Paragraph(label, style['table_text']), Paragraph(value, style['table_text'])]) if (local_index // 2.0 == local_index / 2.0): even_rows.append(index) index += 1 for section in realestate_view.characteristic_fields(): if not section['title']: continue data.append([Paragraph(trans(section['title']), style['table_header']), '']) heading_rows.append(index) index += 1 for local_index, field in enumerate(section['fields']): label = trans(field.widget.Label(context)) value = field.getAccessor(context)() site_encoding = getSiteEncoding(context) if isinstance(value, ListType) or isinstance(value, TupleType): value = [safe_unicode(item, site_encoding) for item in value] value = u', '.join(value) if isinstance(value, BooleanType): if value: value = _(u'True') else: value = _(u'False') try: value = trans(value) except TypeError: pass value = unicode(value) data.append([Paragraph(label, style['table_text']), Paragraph(value, style['table_text'])]) if (local_index // 2.0 == local_index / 2.0): even_rows.append(index) index += 1 table = Table(data=data) table_style = TableStyle([]) for row in heading_rows: table_style.add('BACKGROUND', (0, row), (1, row), colors['table_heading_background']) for row in even_rows: table_style.add('BACKGROUND', (0, row), (1, row), colors['table_even_background']) table_style.add('GRID', (0, 0), (1, -1), 1, colors['table_grid_color']) table_style.add('VALIGN', (0, 0), (-1, -1), 'TOP') table.setStyle(table_style) structure.append(table) structure.append(PageBreak()) # Location + map structure.append(Paragraph(_(u'Address data'), style['heading1'])) table_style = TableStyle([]) data = [] data.append([Paragraph(_(u'Address'), style['big']), Paragraph(context.Title(), style['big'])]) data.append([Paragraph(_(u'Zip code'), style['big']), Paragraph(context.getZipCode(), style['big'])]) data.append([Paragraph(_(u'City'), style['big']), Paragraph(context.getCity(), style['big'])]) table = Table(data=data) table_style.add('BOTTOMPADDING', (0, 0), (1, -1), 12) table_style.add('VALIGN', (0, 0), (-1, -1), 'TOP') table.setStyle(table_style) structure.append(table) # TODO: map (which isn't possible with google maps atm). structure.append(PageBreak()) # Back matter utility = queryUtility(IBackMatter) if utility: structure += utility(context, request, style) # Write it out. (Originally this code used a tempfile, but I guess that # that's something that's not handled right in this zope version. stream = StringIO() writeDocument(stream, structure) return stream.getvalue()
def ramassagePdf(request, id_ramassage): """Renvoie le fichier PDF du ramassage correspondant au ramassage dont l'id est id_ramassage""" ramassage = get_object_or_404(Ramassage, pk=id_ramassage) LISTE_MOIS = [ "", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre" ] response = HttpResponse(content_type='application/pdf') debut = ramassage.moisDebut fin = Ramassage.incremente_mois(ramassage.moisFin) - timedelta(days=1) listeDecompte, effectifs = Ramassage.objects.decompte(debut, fin) nomfichier = "ramassage{}_{}-{}_{}.pdf".format(debut.month, debut.year, fin.month, fin.year) response['Content-Disposition'] = "attachment; filename={}".format( nomfichier) pdf = easyPdf(titre="Ramassage des colles de {} {} à {} {}".format( LISTE_MOIS[debut.month], debut.year, LISTE_MOIS[fin.month], fin.year), marge_x=30, marge_y=30) largeurcel = (pdf.format[0] - 2 * pdf.marge_x) / (9 + len(effectifs)) hauteurcel = 30 nbKolleurs = sum([z for x, y, z in listeDecompte]) pdf.debutDePage() LIST_STYLE = TableStyle([('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)), ('BACKGROUND', (0, 0), (-1, 0), (.6, .6, .6)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 8)]) data = [["Matière", "Établissement", "Grade", "Colleur"] + [ "{}è. ann.\n{}".format(annee, effectif) for annee, effectif in effectifs ]] + [[""] * (4 + len(effectifs)) for i in range(min(23, nbKolleurs)) ] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneMat = ligneEtab = ligneGrade = ligneColleur = 1 for matiere, listeEtabs, nbEtabs in listeDecompte: data[ligneMat][0] = matiere.title() if nbEtabs > 1: LIST_STYLE.add('SPAN', (0, ligneMat), (0, min(ligneMat + nbEtabs - 1, 23))) ligneMat += nbEtabs for etablissement, listeGrades, nbGrades in listeEtabs: data[ligneEtab][ 1] = 'Inconnu' if not etablissement else etablissement.title() if nbGrades > 1: LIST_STYLE.add('SPAN', (1, ligneEtab), (1, min(ligneEtab + nbGrades - 1, 23))) ligneEtab += nbGrades for grade, listeColleurs, nbColleurs in listeGrades: data[ligneGrade][2] = grade if nbColleurs > 1: LIST_STYLE.add('SPAN', (2, ligneGrade), (2, min(ligneGrade + nbColleurs - 1, 23))) ligneGrade += nbColleurs for colleur, decomptes in listeColleurs: data[ligneColleur][3] = colleur for i in range(len(effectifs)): data[ligneColleur][i + 4] = "{},{:02d}h".format( decomptes[i] // 60, (1 + decomptes[i] % 60 * 5) // 3) ligneColleur += 1 if ligneColleur == 24 and nbKolleurs > 23: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t = Table(data, colWidths=[ 2 * largeurcel, 3 * largeurcel, largeurcel, 3 * largeurcel ] + [largeurcel] * len(effectifs), rowHeights=min( (1 + nbKolleurs), 24) * [hauteurcel]) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, (pdf.format[0] - w) / 2, pdf.y - h - hauteurcel / 2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage() LIST_STYLE = TableStyle([ ('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)), ('BACKGROUND', (0, 0), (-1, 0), (.6, .6, .6)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 8) ]) nbKolleurs -= 23 data = [ ["Matière", "Établissement", "Grade", "Colleur"] + [ "{}è. ann.\n{}".format(annee, effectif) for annee, effectif in effectifs ] ] + [ [""] * (4 + len(effectifs)) for i in range(min(23, nbKolleurs)) ] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab -= 23 ligneGrade -= 23 ligneMat -= 23 ligneColleur = 1 if ligneMat > 1: data[1][0] = matiere.title() if ligneMat > 2: LIST_STYLE.add('SPAN', (0, 1), (0, min(ligneMat - 1, 23))) if ligneEtab > 1: data[1][ 1] = 'Inconnu' if not etablissement else etablissement.title( ) if ligneEtab > 2: LIST_STYLE.add('SPAN', (1, 1), (1, min(ligneEtab, 23))) if ligneGrade > 1: data[1][2] = grade if ligneGrade > 2: LIST_STYLE.add( 'SPAN', (2, 1), (2, min(ligneGrade, 23))) t = Table( data, colWidths=[2 * largeurcel, 3 * largeurcel, largeurcel, 3 * largeurcel ] + [largeurcel] * len(effectifs), rowHeights=min((1 + nbKolleurs), 24) * [hauteurcel]) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, (pdf.format[0] - w) / 2, pdf.y - h - hauteurcel / 2) pdf.finDePage() pdf.save() fichier = pdf.buffer.getvalue() pdf.buffer.close() response.write(fichier) return response
def gather_elements(self, client, node, style): # Take the style from the parent "table" node # because sometimes it's not passed down. if node.parent['classes']: style = client.styles.combinedStyle(['table'] + node.parent['classes']) else: style = client.styles['table'] rows = [] colWidths = [] hasHead = False headRows = 0 for n in node.children: if isinstance(n, docutils.nodes.thead): hasHead = True for row in n.children: r = [] for cell in row.children: r.append(cell) rows.append(r) headRows = len(rows) elif isinstance(n, docutils.nodes.tbody): for row in n.children: r = [] for cell in row.children: r.append(cell) rows.append(r) elif isinstance(n, docutils.nodes.colspec): colWidths.append(int(n['colwidth'])) # colWidths are in no specific unit, really. Maybe ems. # Convert them to % colWidths = map(int, colWidths) tot = sum(colWidths) colWidths = ["%s%%" % ((100. * w) / tot) for w in colWidths] if 'colWidths' in style.__dict__: colWidths[:len(style.colWidths)] = style.colWidths spans = client.filltable(rows) data = [] cellStyles = [] rowids = range(0, len(rows)) for row, i in zip(rows, rowids): r = [] j = 0 for cell in row: if isinstance(cell, str): r.append("") else: if i < headRows: st = client.styles['table-heading'] else: st = client.styles['table-body'] ell = client.gather_elements(cell, style=st) r.append(ell) j += 1 data.append(r) st = TableStyle(spans) if 'commands' in style.__dict__: for cmd in style.commands: st.add(*cmd) else: # Only use the commands from "table" if the # specified class has no commands. for cmd in client.styles['table'].commands: st.add(*cmd) if hasHead: for cmd in client.styles.tstyleHead(headRows): st.add(*cmd) rtr = client.repeat_table_rows t = DelayedTable(data, colWidths, st, rtr) if style.alignment == TA_LEFT: t.hAlign = 'LEFT' elif style.alignment == TA_CENTER: t.hAlign = 'CENTER' elif style.alignment == TA_RIGHT: t.hAlign = 'RIGHT' return [t]
def generatePDF(self, model_data): """ Dieses Beispiel zeigt nicht annähernd die Möglichkeiten von ReportLab! Es demonstriert nur, wie einfach es sein kann. """ stylesheet = getSampleStyleSheet() # Formatstil für die Überschrift festlegen sth1 = stylesheet['Heading1'] # Formatstil für den Absatz festlegen stn = stylesheet['Normal'] stn.fontName = 'Helvetica' stn.fontSize = 10 stn.leading = 12 #print stn.spaceAfter #print stn.spaceBefore #print stn.leading print("TODO: Why is the text so close to the top of the cells?") # Automatische Silbentrennung für diesen Stil einschalten stn.language = 'DE' stn.hyphenation = True # Wir machen erstmal einen Fake, # nämlich den ASCII-Text zeilenweise. self.generateDUMP(model_data) pure_text = "".join(self.text) story = [] para = Paragraph( "Beispiel für einen Datenbankbericht".decode("iso-8859-1"), sth1) ''' story.append(para) para = Paragraph("""Dies ist ein längerer Absatz, der eigentlich nur den Zweck hat, die automatische Silbentrennung von WordAxe zu demonstrieren. Aus diesem Grund enthält dieser Absatz auch einige besonders schöne lange Wörter wie etwa "Donaudampfschifffahrtsgesellschaftskapitän" oder "Bundeskanzleramt" oder "Landesgesundheitsbehörden", sogar gleich mehrfach: Schiff Dampfschiff Dampfschifffahrt Donaudampfschiffahrt oder Donaudampfschiffahrtsgesellschaft Donaudampfschiffahrtsgesellschaftsvorsitzender (Ha! damit habt Ihr wohl nicht gerechnet, oder?) und nebenbei auch HTML-Formatierung wie <b>fett</b> oder <i>kursiv!</i> Mal sehen, ob das Euro-Zeichen geht - ich befürchte aber, dass das auf Anhieb nicht funktioniert. Hier kommt es: € - nee, das sehe ich schon im Quelltext nicht richtig. """.decode("iso-8859-1"), stn) story.append(para) for line in pure_text.splitlines(): para = Paragraph(line.decode("iso-8859-1"), stn) story.append(para) ''' # Jetzt mal anders: # Ausgabe als Master-Detail-Liste, wobei die Details # eine Spalte weiter eingerückt sind. if model_data: headers1 = [Paragraph(toUnicode(x), stn) for x in DEPT.headers()] headers2 = [None] + [ Paragraph(toUnicode(x), stn) for x in EMP.headers() ] nColumns = max(len(headers1), len(headers2)) fill1 = ([None] * (nColumns - len(headers1))) fill2 = ([None] * (nColumns - len(headers2))) headers1 += fill1 headers2 += fill2 tableData = [headers1, headers2] colWidths = [None] * nColumns colWidths[-1] = 40 * mm nRows = len(model_data) tableStyle = TableStyle([ ('BOX', (0, 0), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 1), colors.orange), ('BACKGROUND', (0, 1), (-1, 1), colors.yellow), ('INNERGRID', (0, 0), (-1, -1), 0.5, colors.black), ('LEFTPADDING', (0, 0), (-1, -1), 3), ('RIGHTPADDING', (0, 0), (-1, -1), 3), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ]) for dept in model_data: tableData.append(dept.genParagraphList(stn) + fill1) tableStyle.add('BACKGROUND', (0, len(tableData) - 1), (-1, len(tableData) - 1), colors.orange) for emp in dept.children["emp"]: tableData.append([""] + emp.genParagraphList(stn) + fill2) table = LongTable(tableData, style=tableStyle, colWidths=colWidths, repeatRows=2) story.append(table) self.story = story
def Pdf(classe, semin, semax): """Renvoie le fichier PDF du colloscope de la classe classe, entre les semaines semin et semax""" groupes = Groupe.objects.filter(groupeeleve__classe=classe).distinct() jours, creneaux, colles, semaines = Colle.objects.classe2colloscope( classe, semin, semax) jours = list(jours) matieres = Matiere.objects.filter( colle__creneau__classe=classe, colle__semaine__lundi__range=(semin.lundi, semax.lundi)).distinct() couleurs = dict() for matiere in matieres: rouge = int(matiere.couleur[1:3], 16) / 255 vert = int(matiere.couleur[3:5], 16) / 255 bleu = int(matiere.couleur[5:7], 16) / 255 couleurs[matiere.pk] = (rouge, vert, bleu) LISTE_JOURS = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"] response = HttpResponse(content_type='application/pdf') nomfichier = "Colloscope_{}_semaine_{}_{}.pdf".format( unidecode(classe.nom), semin.numero, semax.numero) response['Content-Disposition'] = "attachment; filename={}".format( nomfichier) pdf = easyPdf(orientation='landscape', titre="Colloscope {} semaines n°{} à {}".format( classe.nom, semin.numero, semax.numero), marge_x=30, marge_y=30) nbCreneaux = creneaux.count() nbPages = max((nbCreneaux - 1) // 20 + 1, 1) creneauxParPage = max(1, -((-nbCreneaux) // nbPages)) largeurcel = min( (pdf.format[0] - 2 * pdf.marge_x - 70) / max(creneauxParPage, 1), 60) hauteurcel = (pdf.format[1] - 70 - 2 * pdf.marge_y) / 18 nbSemaines = len(colles) semaines = list(semaines) for indsemaine in range(0, nbSemaines, 15): # on place au maximum 15 semaines par pages indjour = 0 reste = 0 dernierJour = 0 for indcreneau in range( 0, nbCreneaux, creneauxParPage ): # on place au maximum creneauxParPage créneaux par page nbjours = 0 nbCreneauxLoc = min(creneauxParPage, nbCreneaux - indcreneau) nbSemainesLoc = min(15, nbSemaines - indsemaine) pdf.debutDePage(soustitre="Calendrier des colles") LIST_STYLE = TableStyle([('GRID', (1, 0), (-1, -1), 1, (0, 0, 0)), ('GRID', (0, 1), (0, -1), 1, (0, 0, 0)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 9)]) data = [ [""] * (1 + nbCreneauxLoc) for i in range(3 + nbSemainesLoc) ] # on créé un tableau de la bonne taille, rempli de chaînes vides # on remplit les jours. if reste != 0: # S'il reste des créneaux d'un jour de la page précédente data[0][1] = LISTE_JOURS[ dernierJour] # on réécrit le nom du jour LIST_STYLE.add('SPAN', (1, 0), (reste, 0)) # on fusionne les bonnes cases nbjours = reste # on met à jour le nombre de créneaux déjà pris en compte reste = 0 # on remet le reste à 0 while nbjours < nbCreneauxLoc: dernierJour = jours[indjour]['jour'] data[0][nbjours + 1] = LISTE_JOURS[dernierJour] LIST_STYLE.add( 'SPAN', (nbjours + 1, 0), (min(nbjours + jours[indjour]['nb'], nbCreneauxLoc), 0)) nbjours += jours[indjour]['nb'] indjour += 1 reste = nbjours - nbCreneauxLoc # on remplit les heures, ainsi que les salles data[1][0] = "Heure" data[2][0] = "Salle" for cren in range(nbCreneauxLoc): heure = creneaux[indcreneau + cren].heure data[1][cren + 1] = "{}h{:02d}".format(heure // 4, 15 * (heure % 4)) data[2][cren + 1] = creneaux[indcreneau + cren].salle #on places les colles dans le tableau, ainsi que les bonnes couleurs for icren in range(indcreneau, indcreneau + nbCreneauxLoc): for isem in range(indsemaine, indsemaine + nbSemainesLoc): # On place les semaines dans la première colonne data[3 + isem - indsemaine][0] = "S" + str(semaines[isem]) colle = colles[isem][icren] if colle['id_col']: if colle['temps'] == 20: data[3 + isem - indsemaine][ 1 + icren - indcreneau] = "{}:{}".format( classe.dictColleurs( semin, semax)[colle['id_colleur']], colle['nomgroupe']) elif colle['temps'] == 30: data[3 + isem - indsemaine][ 1 + icren - indcreneau] = "{}:{}".format( classe.dictColleurs( semin, semax)[colle['id_colleur']], classe.dictEleves()[colle['id_eleve']]) elif colle['temps'] == 60: data[3 + isem - indsemaine][ 1 + icren - indcreneau] = "{}".format( classe.dictColleurs( semin, semax)[colle['id_colleur']]) LIST_STYLE.add( 'BACKGROUND', (1 + icren - indcreneau, 3 + isem - indsemaine), (1 + icren - indcreneau, 3 + isem - indsemaine), couleurs[colle['id_matiere']]) t = Table(data, colWidths=[70] + nbCreneauxLoc * [largeurcel], rowHeights=(3 + nbSemainesLoc) * [hauteurcel]) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, (pdf.format[0] - w) / 2, pdf.y - h - ((pdf.y - pdf.marge_y) - h) / 2) pdf.finDePage() fontsize = 10 pdf.setFont("Helvetica-Bold", fontsize) largeurcel = (pdf.format[0] - 2 * pdf.marge_x) / 6 hauteurcel = (pdf.format[1] - 2 * pdf.marge_y - 70) / 12 pdf.debutDePage(soustitre="Groupes de colle") groupes = list(groupes) nbGroupes = len(groupes) for indGroupe in range(0, nbGroupes, 6): nbGroupesLoc = min(6, nbGroupes - indGroupe) data = [[ "Groupe {}".format(groupes[indGroupe + i]) for i in range(nbGroupesLoc) ]] data += [[""] * nbGroupesLoc for i in range(3)] for iGroupe in range(indGroupe, indGroupe + nbGroupesLoc): ieleve = 0 for eleve in groupes[iGroupe].groupeeleve.all(): ieleve += 1 data[ieleve][iGroupe - indGroupe] = "{} {} ({})".format( eleve.user.first_name.title(), eleve.user.last_name.upper(), classe.dictEleves()[eleve.id]) LIST_STYLE = TableStyle([('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 8), ('BACKGROUND', (0, 0), (-1, 0), (.6, .6, .6)) ]) t = Table(data, colWidths=[largeurcel] * nbGroupesLoc, rowHeights=[hauteurcel] * 4) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, (pdf.format[0] - w) / 2, pdf.y - h - 10) pdf.y -= h + 10 pdf.finDePage() matieres = Matiere.objects.filter( matieresclasse=classe, colle__creneau__classe=classe, colle__semaine__lundi__range=(semin.lundi, semax.lundi)).distinct() largeurcel = min(150, (pdf.format[0] - 2 * pdf.marge_x) / max(matieres.count(), 1)) hauteurcel = 40 for matiere in matieres: nbcolleurs = Colle.objects.filter( creneau__classe=classe, matiere=matiere, semaine__lundi__range=( semin.lundi, semax.lundi)).values('colleur').distinct().count() hauteurcel = min(hauteurcel, (pdf.format[1] - 2 * pdf.marge_y - 70) / nbcolleurs) pdf.debutDePage(soustitre="Liste des colleurs") pdf.x = (pdf.format[0] - matieres.count() * largeurcel) / 2 pdf.y -= 10 fontsize = 9 pdf.setFont("Helvetica-Bold", fontsize) for matiere in matieres: data = [[ matiere.nom.title() + ("" if not matiere.lv else "(LV{})".format(matiere.lv)) ]] colleurs = Colle.objects.filter( creneau__classe=classe, matiere=matiere, semaine__lundi__range=( semin.lundi, semax.lundi)).values('colleur').distinct().order_by( 'colleur__user__last_name', 'colleur__user__first_name') for colleur_id in colleurs: colleur = get_object_or_404(Colleur, pk=colleur_id['colleur']) data += [[ "{}. {} ({})".format( colleur.user.first_name[0].title(), colleur.user.last_name.upper(), classe.dictColleurs(semin, semax)[colleur.pk]) ]] LIST_STYLE = TableStyle([('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 8), ('BACKGROUND', (0, 0), (0, -1), couleurs[matiere.pk])]) t = Table(data, rowHeights=hauteurcel, colWidths=largeurcel) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, pdf.x, pdf.y - h) pdf.x += w pdf.finDePage() pdf.save() fichier = pdf.buffer.getvalue() pdf.buffer.close() response.write(fichier) return response
def gather_elements(self, client, node, style): # Take the style from the parent "table" node # because sometimes it's not passed down. if node.parent['classes']: style = client.styles.combinedStyle(['table']+node.parent['classes']) else: style = client.styles['table'] rows = [] colWidths = [] hasHead = False headRows = 0 for n in node.children: if isinstance(n, docutils.nodes.thead): hasHead = True for row in n.children: r = [] for cell in row.children: r.append(cell) rows.append(r) headRows = len(rows) elif isinstance(n, docutils.nodes.tbody): for row in n.children: r = [] for cell in row.children: r.append(cell) rows.append(r) elif isinstance(n, docutils.nodes.colspec): colWidths.append(int(n['colwidth'])) # colWidths are in no specific unit, really. Maybe ems. # Convert them to % colWidths=map(int, colWidths) tot=sum(colWidths) colWidths=["%s%%"%((100.*w)/tot) for w in colWidths] if 'colWidths' in style.__dict__: colWidths[:len(style.colWidths)]=style.colWidths spans = client.filltable(rows) data = [] cellStyles = [] rowids = range(0, len(rows)) for row, i in zip(rows, rowids): r = [] j = 0 for cell in row: if isinstance(cell, str): r.append("") else: if i < headRows: st = client.styles['table-heading'] else: st = client.styles['table-body'] ell = client.gather_elements(cell, style=st) r.append(ell) j += 1 data.append(r) st = TableStyle(spans) if 'commands' in style.__dict__: for cmd in style.commands: st.add(*cmd) else: # Only use the commands from "table" if the # specified class has no commands. for cmd in client.styles['table'].commands: st.add(*cmd) if hasHead: for cmd in client.styles.tstyleHead(headRows): st.add(*cmd) rtr = client.repeat_table_rows t=DelayedTable(data, colWidths, st, rtr) if style.alignment == TA_LEFT: t.hAlign='LEFT' elif style.alignment == TA_CENTER: t.hAlign='CENTER' elif style.alignment == TA_RIGHT: t.hAlign='RIGHT' return [t]
canvas.line(70, 790, 530, 790) pdfmetrics.getRegisteredFontNames() datas2 = [] datas2.append(['First', 'Second', 'Third']) stylesoftable = TableStyle([('ALIGN', (0, 0), (2, -1), 'CENTRE'), ('FONT', (0, 0), (2, 0), 'Helvetica', 10), ('FONT', (0, 1), (-1, -1), 'Helvetica', 8), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]) stylesoftable.add('BACKGROUND', (0, 0), (2, 0), colors.lightcoral) for i in range(cellswithdata): OBJ = Raw() cells = firstsheet['A2':r] for A2, B2, C2 in cells: OBJ.rawone = A2.value OBJ.rawtwo = B2.value OBJ.rawthird = C2.value datas2.append([OBJ.rawone, OBJ.rawtwo, OBJ.rawthird]) datatable = Table(datas2, [5 * cm, 5 * cm, 5 * cm], repeatRows=1) datatable.hAlign = 'CENTER' datatable.setStyle(stylesoftable)
def _render_month(self, month): '''Render one page with a month.''' table_data = self._calendar.monthdayscalendar(self.year, month) table_data = [ [ day or None for day in week ] for week in table_data ] table = Table(table_data, colWidths=(self.cell_width,) * 7, rowHeights=(self.cell_height,) * len(table_data) ) style = TableStyle() for padding in ("TOP", "RIGHT", "BOTTOM", "LEFT"): style.add(padding + "PADDING", (0, 0), (-1, -1), self.cell_padding) for position in ("BEFORE", "AFTER", "ABOVE", "BELOW"): style.add("LINE" + position, (0, 0), (-1, -1), self.cell_spacing / 2, colors.white) font_name = font_loader.get_font_name(self.cell_font_name, self.cell_font_variant) style.add("FONT", (0, 0), (-1, -1), font_name, self.cell_font_size) style.add("ALIGN", (0, 0), (-1, -1), "RIGHT") style.add("VALIGN", (0, 0), (-1, -1), "MIDDLE") style.add("BACKGROUND", (0, 0), (-1, -1), self.week_bgcolor) style.add("TEXTCOLOR", (0, 0), (-1, -1), self.week_color) self._style_holidays_and_special_days(month, style) table.setStyle(style) table_width, table_height = table.wrapOn(self.canvas, 7*self.cell_width, 6*self.cell_height) table.drawOn(self.canvas, self.margins[3], self.margins[2]) # Render title title_position = (self.margins[3], self.margins[2] + table_height + self.title_margin) self.set_font(self.title_font_name, self.title_font_size, variant=self.title_font_variant) self.canvas.drawString(title_position[0], title_position[1], self.locale.month_title(self.year, month)) # Render picture self._render_picture(month, self.content_height - self.title_font_size - 2 * self.title_margin - table_height) self.canvas.showPage()
text_style.leading *= 1.3 def verse_to_table(verse): global text_style num, ref, text = verse return (ref, Paragraph(text, text_style)) def header(canvas, doc): global margin canvas.saveState() canvas.setFont('Helvetica-Bold',11) canvas.drawString(margin, pagesizes.letter[1] - margin*1.2, "%s: verses %d-%d words long, at least %d verses apart" % (TITLE, MIN_WORDS, MAX_WORDS, MIN_DISTANCE)) canvas.drawString(margin, margin, "Page %d" % (doc.page)) canvas.restoreState() # convert verses into pdf paragraphs selected = map(verse_to_table, selected) # build pdf table style = TableStyle() style.add('VALIGN', (0,0), (-1,-1), 'TOP') style.add('GRID', (0,0), (-1,-1), 1, colors.black) table = Table(selected, [width*0.2,width*0.8]) table.setStyle(style) # build pdf output doc = SimpleDocTemplate("out_quotingbee.pdf", pagesize=pagesizes.letter, topMargin=margin*1.5, leftMargin=margin, bottomMargin=margin*1.5, rightMargin=margin) doc.build([table], onFirstPage=header, onLaterPages=header)
def drawTable(self, group=None, monocell=None, reiter = None, tabpro=None): """ Drawing a table """ matrix = [] lst = [] matrix2 = [] vector = [] # Total of element's table n_cells = int(tabpro['n_cells']) columns = int(tabpro['columns']) rows = int(tabpro['rows']) celle = tabpro["cells"] widths = [float(x.get("WIDTH")) for x in celle] heights = [float(x.get("HEIGHT")) for x in celle] xpos = [float(x.get("XPOS")) for x in celle] ypos = [float(x.get("YPOS")) for x in celle] contColumns = 0 ch = '' col = 0 cycle = False vector = [] alignment= None itexts = [x.findall("ITEXT") for x in celle] paras = [x.findall("para") for x in celle] trail = [x.findall("trail") for x in celle] stile = TableStyle([]) stile.add('VALIGN',(0,0),(-1,-1),'TOP') if monocell==True: cells = 1 columns=1 rows = 1 #print "CEEEEEEEEEEEEEELS", cells for v in range(0,n_cells): if v == 0: contRows = 0 contColumns = 0 elif columns==1: contColumns = -1 contRows= int(v/columns) else: contRows= int(v/columns) contColumns = ((v)%columns) # print "VVVVVVVVVVVVV E CELLE", "celle", celle,"V:",v, "LEN DI CELLE",len(celle), "NCELLS", n_cells, group try: background = self.backgroundFunc(celle[v])# Finding background except Exception as e: Environment.pg2log.info("ERRORE NEL GRUPPO TABELLA"+ group + "ERRORE:" + str(e.args)) hexBorderColor = self.hexBorderColorFunc(celle[v].get('PCOLOR2')) stile.add('ROWBACKGROUNDS', (contColumns,contRows), (contColumns,contRows), (background, background)) cellpict = celle[v].get('PFILE') cellIMGHeight = celle[v].get('HEIGHT') cellIMGWidth = celle[v].get('WIDTH') bordoriga = False if (celle[v].get('BottomLine') == "1" and celle[v].get('TopLine') == "1" and\ celle[v].get('LeftLine') =="1" and celle[v].get('RightLine') == "1"): stile.add('BOX', (contColumns,contRows), (contColumns,contRows), float(celle[v].get('PWIDTH')), hexBorderColor) bordoriga = True else: if celle[v].get('BottomLine') == "1": stile.add('LINEBELOW', (contColumns,contRows), (contColumns,contRows), float(celle[v].get('PWIDTH')), hexBorderColor) bordoriga = True if celle[v].get('TopLine') == "1": stile.add('LINEABOVE', (contColumns,contRows), (contColumns,contRows), float(celle[v].get('PWIDTH')), hexBorderColor) bordoriga = True if celle[v].get('LeftLine') == "1": stile.add('LINEBEFORE', (contColumns,contRows), (contColumns,contRows), float(celle[v].get('PWIDTH')), hexBorderColor) bordoriga = True if celle[v].get('RightLine') == "1": stile.add('LINEAFTER', (contColumns,contRows), (contColumns,contRows), float(celle[v].get('PWIDTH')), hexBorderColor) bordoriga = True if not bordoriga and str(celle[v].get('PCOLOR2')) != "None": stile.add('BOX', (contColumns,contRows), (contColumns,contRows), float(celle[v].get('PWIDTH')), hexBorderColor) if not monocell: ch = self.chFunc(itexts[v])[0] itext = self.chFunc(itexts[v])[1] else: try: itext = itexts[0] ch = itexts[0].get('CH') except: itext = None ch = "" actualPageObject = tabpro # Borders pdfAlignment = self.alignmentFunc(paras,v, monocell, trail=trail, reiter=reiter) #alignment stile.add('ALIGN', (contColumns,contRows), (contColumns,contRows), pdfAlignment) if itext != None: fontSize = self.fontSizeFunc(itext,v=v, trail=trail)# Font size stile.add('FONTSIZE', (contColumns,contRows), (contColumns,contRows), fontSize) fontName = self.fontNameFunc(itext,trail=trail) # Font name stile.add('FONT', (contColumns,contRows), (contColumns,contRows), fontName) foreground = self.foregroundFunc(itext) #foreground stile.add('TEXTCOLOR', (contColumns,contRows), (contColumns,contRows), foreground) if "bcview" in ch: alignment="LEFT" vector.append(Sla2pdfUtils.createbarcode(ch)) else: vector.append(Sla2pdfUtils.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize)) elif cellpict: (imgPath, imgFile) = os.path.split(cellpict) path = Environment.imagesDir + imgFile widthIMG = (float(cellIMGHeight)-2)*100/(float(cellIMGWidth)-2) img = Image(path,width=widthIMG,height=float(cellIMGHeight)-2) vector.append(img) else: vector.append('') if monocell==True: cycle= True elif ((v+1)%columns) == 0: contRows = 0 cycle= True if cycle == True: matrix.append(vector) vector = [] cycle = False table=Table(matrix,style=stile, colWidths=widths[:columns], rowHeights=heights[:rows]) lst.append(table) # Effective table size sumRows = Sla2pdfUtils.sumRowsFunc(heights,rows) sumColumns = Sla2pdfUtils.sumColumnsFunc(widths,columns) f = Frame(x1=(xpos[0] - self.pageProperties[self.pdfPage][9]), y1=(self.pageProperties[self.pdfPage][7] - ypos[0] - sumRows + self.pageProperties[self.pdfPage][10] - 12), width=sumColumns, height=(sumRows+12), showBoundary=0) sumRows = sumColumns = 0 f.addFromList(lst, self.canvas) reiter = False
def get_questionnaire_pdf(filename, doc_id, start_index=1, print_answers=True): """ Method which writes to @filename a pdf representing the questionnaire of @doc_id By default the first system is numbered starting with 1, this can be overwritten with the @start_index parameter. Subsequent systems will have sequential numbers""" doc = get_doc_copy_with_references(doc_id, start_index=1) story = [Spacer(1,10*cm)] story.append( P(doc['questionnaire_intro'], ParagraphStyle( name='ItalicJustified', alignment=TA_JUSTIFY, fontName='Times-Italic'))) story.append(Spacer(1,3*cm)) company_data = [['0', P('Company and Offer',styleH1), ''], ['0.1', P('Company Name', styleN), ''], ['0.2', P('if alternative proposal(s) submitted: Bid (Conforming bid or alternative proposal)', styleN), ''] ] company_style = TableStyle([ ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey), ]) table = Table(company_data, colWidths=[ 1.5*cm, 11.5*cm, 6*cm], style=company_style) story.append(table) story.append(PageBreak()) data = [[ 'Ref', 'Header/Question', 'Type', 'Answer' ]] # this lis will contain the indices of the rows which should have a different # formatting (headers) headers_rows = [] headers_rows.append(len(data)-1) for sys in range(len(doc.get('systems', []))): system = doc['systems'][sys] data.append(['%s' % (start_index + sys), P(system['name'], styleH2), '', '']) headers_rows.append(len(data)-1) for sec in range(len(system.get('sections',[]))): section = system['sections'][sec] data.append([ '%s.%s' % (start_index + sys, sec + 1), P(section['header'], styleH3), '', '']) headers_rows.append(len(data)-1) for q in range(len(section.get('questions', []))): question = section['questions'][q] data.append( [ "%d.%d.%d" % (start_index + sys, sec + 1, q + 1), P(question['question'], styleN), _get_type(question), (str(question['answer'] or '') if print_answers else '') ]) table_styles = TableStyle([ ('GRID', (0,0), (-1,-1), 0.25, colors.black), ('VALIGN', (0,0), (-1, -1), 'MIDDLE'), ('ALIGN', (2,0), (3,-1), 'CENTER'), ]) for h in headers_rows: table_styles.add('BACKGROUND', (0,h), (-1,h), colors.lightgrey) table = Table(data , colWidths=[ 1.5*cm, 12.5*cm, 3*cm, 2*cm], style=table_styles) story.append(table) pdf = SimpleDocTemplate(filename) _on_first_page = partial(_first_page, doc_id=doc_id, title=doc['title'], type_="Technical Questionnaire") _on_later_pages = partial(_later_pages, doc_id=doc_id, type_="Technical Questionnaire") pdf.build(story, onFirstPage=_on_first_page, onLaterPages=_on_later_pages) return pdf
def draw_text(report, text, attributes): """ Draw text string on report_info. :param report: :param text: text to output to report_info :param attributes: attributes (e.g. 'font name', 'font size', 'color') to apply to text """ report['canvas'].saveState() text = format_text(text, attributes) styles = getSampleStyleSheet() text_alignment = {'Left': TA_LEFT, 'Center': TA_CENTER, 'Right': TA_RIGHT, 'Justified': TA_JUSTIFY} base_style = styles['Normal'] left_indent = attributes.get("leftIndent", base_style.leftIndent) right_indent = attributes.get("rightIndent", base_style.leftIndent) font_name = get_font(report, attributes, base_style) font_is_bold = convert2boolean(attributes.get('fontIsBold')) if font_is_bold: text = '<b>' + text + '</b>' font_is_italic = convert2boolean(attributes.get('fontIsItalic')) if font_is_italic: text = '<i>' + text + '</i>' font_is_underline = convert2boolean(attributes.get('fontIsUnderline')) if font_is_underline: text = '<u>' + text + '</u>' font_is_strike_through = convert2boolean(attributes.get('fontIsStrikeThrough')) if font_is_strike_through: text = '<strike>' + text + '</strike>' font_size = attributes.get('fontSize', 10) text_color = attributes.get('forecolor') if text_color is None: text_color = base_style.textColor else: text_color = colors.HexColor(text_color) ps = ParagraphStyle(name='cell', parent=styles['Normal'], fontName=font_name, fontSize=font_size, leading=font_size * 1.2, leftIndent=left_indent, rightIndent=right_indent, alignment=text_alignment[attributes.get('textAlignment', 'Left')], textColor=text_color ) # text = "<br/>".join(str(text).split('\n')) # replace '\n' with a <br/> to cause newline text = str(text).replace('\n', '<br/>') # story = [Paragraph(str(text), ps)] story = [Paragraph(text, ps)] story_in_frame = KeepInFrame(attributes['width'], attributes['height'], story, mode='shrink') # 'truncate, overflow, shrink data = [[story_in_frame]] t = Table(data, colWidths=attributes['width'], rowHeights=attributes['height']) table_style = TableStyle([ ('VALIGN', (0,0),(0,0), attributes.get('verticalAlignment', 'TOP').upper()), ('TEXTCOLOR', (0, 0), (0, 0), colors.black), ('LEFTPADDING', (0, 0), (0, 0), 0), ('RIGHTPADDING', (0, 0), (0, 0), 0), ('TOPPADDING', (0, 0), (0, 0), 0), ('BOTTOMPADDING', (0, 0), (0, 0), 0), ]) if attributes.get('mode') is not None: backcolor = attributes.get('backcolor') if backcolor is not None: table_style.add('BACKGROUND', (0, 0), (0, 0), colors.HexColor(backcolor)) t.setStyle(table_style) t.wrapOn(report['canvas'], attributes['width'], attributes['height']) t.drawOn(report['canvas'], attributes['x'], report['cur_y'] - attributes['y'] - attributes['height']) report['canvas'].restoreState()
def drawTable(): """ Drawing a table """ matrix = [] vector = [] # Total of element's table actualGroup = self.group cells = int(self.tablesProperties[actualGroup]['cells']) columns = int(self.tablesProperties[actualGroup]['columns']) rows = int(self.tablesProperties[actualGroup]['rows']) # Finding cell size cont = 0 widths = [] heights = [] innerIterator = self.iterator xpos = float(self.pageObjects[innerIterator].get('XPOS')) ypos = float(self.pageObjects[innerIterator].get('YPOS')) while actualGroup == self.group and innerIterator < len(self.pageObjects): cont += 1 actualGroup = self.pageObjects[innerIterator].get('GROUPS') if actualGroup == self.group: width = float(self.pageObjects[innerIterator].get('WIDTH')) widths.append(width) if cont == columns: height = float(self.pageObjects[innerIterator].get('HEIGHT')) heights.append(height) cont = 0 innerIterator += 1 # General table style (always the same!!!) stile = TableStyle([]) stile.add('VALIGN',(0,0),(-1,-1),'TOP') # Applying stile, font and color for every cell contColumns = -1 contRows = 0 ch = '' cont = 0 vector = [] actualGroup = self.group innerIterator = self.iterator alignment = " " while actualGroup == self.group and innerIterator < len(self.pageObjects): actualGroup = self.pageObjects[innerIterator].get('GROUPS') actualPage = int(self.pageObjects[innerIterator].get('OwnPage')) if actualPage != self.pdfPage: innerIterator += 1 continue if actualGroup == self.group: # Conversion between index - row/column contColumns += 1 if contColumns == columns: contColumns = 0 contRows += 1 # Finding background cellBackground = self.pageObjects[innerIterator].get('PCOLOR') if cellBackground in self.colorList: try: hexColor = self.colorList[cellBackground] background = colors.HexColor(str(hexColor)) except: background = colors.HexColor('#ffffff') else: background = colors.HexColor('#ffffff') stile.add('ROWBACKGROUNDS', (contColumns,contRows), (contColumns,contRows), (background, background)) itexts = self.pageObjects[innerIterator].findall('ITEXT') put = False if self.version: paras = self.pageObjects[innerIterator].findall('para') if len(itexts)>=1: if len(itexts)>1: for itext in itexts: chtmp = itext.get('CH') ch = ch +" "+ chtmp itext = itexts[0] else: itext = itexts[0] ch = itext.get('CH') if self.version: #try: alignment = paras[0].get('ALIGN') #except: #alignment = "0" else: alignment = itext.get('CAB') if alignment == None: alignment = self.defaultAlignment if alignment == '0': alignment = 'LEFT' elif alignment == '1': alignment = 'CENTER' elif alignment == '2': alignment = 'RIGHT' else: alignment = "LEFT" stile.add('ALIGN', (contColumns,contRows), (contColumns,contRows), alignment) # Font name if self.version: fontName = getPdfFontName(str(itext.get('FONT'))) else: fontName = getPdfFontName(str(itext.get('CFONT'))) stile.add('FONT', (contColumns,contRows), (contColumns,contRows), fontName) # Font size if self.version: try: print "TEEEEE", itext.get('FONTSIZE') fontSize = float(itext.get('FONTSIZE')) except: fontSize = float(10) else: fontSize = float(itext.get('CSIZE')) stile.add('FONTSIZE', (contColumns,contRows), (contColumns,contRows), fontSize) # Hex color textColor = itext.get('FCOLOR') if textColor in self.colorList: try: hexColor = self.colorList[textColor] foreground = colors.HexColor(str(hexColor)) except: foreground = colors.HexColor('#000000') else: foreground = colors.HexColor('#000000') stile.add('TEXTCOLOR', (contColumns,contRows), (contColumns,contRows), foreground) # Borders actualPageObject = self.pageObjects[innerIterator] bottomLine = int(actualPageObject.get('BottomLine')) topLine = int(actualPageObject.get('TopLine')) leftLine = int(actualPageObject.get('LeftLine')) rightLine = int(actualPageObject.get('RightLine')) lineWidth = float(actualPageObject.get('PWIDTH')) borderColor = actualPageObject.get('PCOLOR2') if borderColor in self.colorList: try: hexBorderColor = self.colorList[borderColor] except: hexBorderColor = '#000000' else: hexBorderColor = '#000000' if (bottomLine == 1 and topLine == 1 and leftLine == 1 and rightLine == 1): stile.add('BOX', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor) else: if bottomLine == 1: stile.add('LINEBELOW', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor) elif topLine == 1: stile.add('LINEABOVE', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor) if leftLine == 1: stile.add('LINEBEFORE', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor) if rightLine == 1: stile.add('LINEAFTER', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor) vector.append(self.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize)) put = True if put == False: vector.append('') cont += 1 if cont == columns: #print "VECTORRRR ", vector matrix.append(vector) vector = [] cont = 0 test = None innerIterator += 1 # Creating and filling table #print "matrix", matrix table=Table(matrix, style=stile, colWidths=widths[:columns], rowHeights=heights[:rows]) # Adding cell to the frame and save it lst = [] lst.append(table) # Effective table size sumRows = 0 sumColumns = 0 for i in range(0, rows): sumRows += heights[i] for i in range(0, columns): sumColumns += widths[i] f = Frame(x1=(xpos - self.pageProperties[self.pdfPage][9]), y1=(self.pageProperties[self.pdfPage][7] - ypos - sumRows + self.pageProperties[self.pdfPage][10] - 12), width=sumColumns, height=(sumRows+12), showBoundary=0) f.addFromList(lst, self.canvas) self.canvas.saveState() self.iterator += cells - 1
def some_view3(request, *args, **kwargs): from django.http import HttpResponse from reportlab.lib import colors from reportlab.lib.pagesizes import letter, inch from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Table, TableStyle, Frame, PageTemplate, BaseDocTemplate, FrameBreak, Spacer from reportlab.lib.styles import getSampleStyleSheet # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') #response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' #A4 width = 8.5 inches # define frames - for frames in page frameHeader = Frame(x1=0*inch, y1=9.6*inch, width=8.5*inch, height=1.2*inch) frameTable1 = Frame(x1=0.3*inch, y1=8.0*inch, width=4.25*inch, height=1.6*inch) frameTable2 = Frame(x1=4.25*inch, y1=8.0*inch, width=4.25*inch, height=1.6*inch) frameTable3 = Frame(x1=1.0625*inch, y1=7.0*inch, width=1.5*inch, height=1.0*inch) frameTable4 = Frame(x1=2.5625*inch, y1=7.0*inch, width=1.5*inch, height=1.0*inch) frameTable5 = Frame(x1=4.0625*inch, y1=7.0*inch, width=1.5*inch, height=1.0*inch) frameTable6 = Frame(x1=5.5625*inch, y1=7.0*inch, width=1.5*inch, height=1.0*inch) #Checkboxes frameTable7 = Frame(x1=1.0625*inch, y1=1.5*inch, width=1.5*inch, height=6.2*inch) frameTable8 = Frame(x1=2.5625*inch, y1=1.5*inch, width=5.5*inch, height=5.5*inch) #Signature frameTable9 = Frame(x1=0*inch, y1=0.5*inch, width=8.5*inch, height=1.0*inch) # define pageTemplates - for page in document mainPage = PageTemplate(frames=[frameHeader, frameTable1, frameTable2, frameTable3, frameTable4, frameTable5, frameTable6, frameTable7, frameTable8, frameTable9 ]) # define BasicDocTemplate - for document doc = BaseDocTemplate(response, pagesize=letter, pageTemplates=mainPage) # styles styleSheet = getSampleStyleSheet() styleH = styleSheet['Heading1'] # create a story # container for the 'Flowable' objects elements = [] # Add all the flowables to different frames #elements.append(heading) #elements.append(FrameBreak()) # move to next frame #TESTING FRAMES #Two Columns #frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1', showBoundary=1) #frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2', showBoundary=1) #doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1,frame2]), ]) #I = Image('replogo.gif') #I.drawHeight = 1.25*inch*I.drawHeight / I.drawWidth #I.drawWidth = 1.25*inch ############################################################### #Hamta modeller som kommer anvandas fran databasen serviceprotocol = Serviceprotocol.objects.get(pk=kwargs.get('pk', None)) #Serviceprotocol.objects.get(pk=kwargs.get('pk', None)) #print(Serviceprotocol) # for product in Product.objects.all(): # p = Paragraph("%s" % product.name, style) # Catalog.append(p) # s = Spacer(1, 0.25*inch) # Catalog.append(s) # doc.build(Catalog) ############################################################### ############################################################### #Rubrik h = Paragraph("""<para align=center spaceb=3><b>Serviceprotocol</b></para>""", styleH) elements.append(h) g = Spacer(1, 0.25*inch) elements.append(g) ############################################################### ############################################################### #DATUM data = [['Datum:', serviceprotocol.date]] a=Table(data,style=[ ('BOX',(0,0),(-1,-1),2,colors.black), ('ALIGN',(0,0),(0,0),'CENTER'), ('ALIGN',(0,0),(-1,-1),'LEFT'), ]) a._argW[-1]=1.1*inch elements.append(a) elements.append(FrameBreak()) ############################################################### ############################################################### #Modell, Ar, Km etc data = [['Modell:', serviceprotocol.model], ['År:', serviceprotocol.year], ['Km:', serviceprotocol.km], ['Tekniker:', serviceprotocol.employee], ['Regnr:', serviceprotocol.registration_nr]] b=Table(data,style=[ #(col, row) ('BOX',(0,0),(-1,-1),2,colors.black), ('LINEABOVE',(0,1),(1,1),1,colors.black), ('LINEABOVE',(0,2),(1,2),1,colors.black), ('LINEABOVE',(0,3),(1,3),1,colors.black), ('LINEABOVE',(0,4),(1,4),1,colors.black), ('ALIGN',(1,0),(1,4),'CENTER'), ('ALIGN',(0,0),(-1,-1),'LEFT'), ]) b._argW[1]=1.6*inch elements.append(b) elements.append(FrameBreak()) ############################################################### ############################################################### #Company information data = [["Nilsson's MC Shop AB"], ['Industrigatan 48'], ['58277 Linköping'], ['Tel 013-141458']] f=Table(data,style=[ #(col, row) ('ALIGN',(0,0),(0,3),'CENTER'), ]) #f._argW[0]=1.6*inch elements.append(f) elements.append(FrameBreak()) ############################################################### ############################################################### #CHECKBOXES service_fields = [ 'oil_check', 'motor_check', 'primary_check', 'gearbox_check', 'chain_check', 'cylinder_check', 'brakes_check', 'front_check', 'back_check', 'plug_check', 'rm_plug_check', 'grease_check', 'air_check', 'rm_air_check', 'filter_check', 'belt_check', 'tires_check', 'pressure_check', 'fuel_check', 'layer_check', 'rm_layer_check', 'support_check', 'blinkers_check', 'error_check', ] service_fields2 = [ 'Oljebyte', 'Motor', 'Primär', 'Vx.låda', 'Kontroll premiärkedja + ev. justering', 'Kontroll broms + kopplingscylindrar + slangar', 'Byte broms + koppl. Vätskor', 'Kontroll bromsklossar fram', 'Kontroll bromsklossar bak', 'Kontroll tändstift', 'Byte tändstift', 'Kontroll vajrar + smörjning', 'Kontroll luftrenare', 'Byte luftrenare', 'Rengöring luftfilter KN-typ', 'Kontroll belt - drivkedja + ev. justering - smörjning', 'Kontroll däck + fälgar + lagar', 'Lufttryck fram + bak', 'Kontroll bränsle + oljeslangar', 'Kontroll styrlager', 'Smörjning styrlager', 'Smörjning av stöd', 'Kontroll belysning + blinkers + nivå justering', 'Felkoder', ] service_fields3 = [ {'oil_check':'Oljebyte'}, {'motor_check':'Motor'}, {'primary_check':'Primär'}, {'gearbox_check':'Vx.låda'}, {'chain_check':'Kontroll premiärkedja + ev. justering'}, {'cylinder_check':'Kontroll broms + kopplingscylindrar + slangar'}, {'brakes_check':'Byte broms + koppl. Vätskor'}, {'front_check':'Kontroll bromsklossar fram'}, {'back_check':'Kontroll bromsklossar bak'}, {'plug_check':'Kontroll tändstift'}, {'rm_plug_check':'Byte tändstift'}, {'grease_check':'Kontroll vajrar + smörjning'}, {'air_check':'Kontroll luftrenare'}, {'rm_air_check':'Byte luftrenare'}, {'filter_check':'Rengöring luftfilter KN-typ'}, {'belt_check':'Kontroll belt - drivkedja + ev. justering - smörjning'}, {'tires_check':'Kontroll däck + fälgar + lagar'}, {'pressure_check':'Lufttryck fram + bak'}, {'fuel_check':'Kontroll bränsle + oljeslangar'}, {'layer_check':'Kontroll styrlager'}, {'rm_layer_check':'Smörjning styrlager'}, {'support_check':'Smörjning av stöd'}, {'blinkers_check':'Kontroll belysning + blinkers + nivå justering'}, {'error_check':'Felkoder'}, ] for field in service_fields3: for key, value in field.items(): data = [['', value]] c=Table(data, 1*[0.3*inch], 1*[0.3*inch]) LIST_STYLE = TableStyle([ ('BOX',(0,0),(0,0),2,colors.black), ('ALIGN',(0,0),(0,0),'LEFT'), ]) #Modefiera celler i efterhand. if getattr(serviceprotocol,key) == True: LIST_STYLE.add('BACKGROUND',(0,0),(0,0),colors.black) #Lagg till allt c.setStyle(LIST_STYLE) #Satt width pa column 1 till 1*inch c._argW[1]=1*inch #Lagg till i flow if key == 'oil_check' or key == 'motor_check' or key == 'primary_check' or key =='gearbox_check': elements.append(c) elements.append(FrameBreak()) else: elements.append(c) elements.append(FrameBreak()) ############################################################### ############################################################### #Additional, Comments p1 = Paragraph("%s" % serviceprotocol.additional, styleSheet["BodyText"]) p2 = Paragraph("%s" % serviceprotocol.comment, styleSheet["BodyText"]) # data = [['Övrigt enl. önskemål:', p1], # ['Anm:', p2]] # d=Table(data,style=[ #(col, row) # ('ALIGN',(0,0),(0,1),'RIGHT'), # ('VALIGN',(0,0),(0,1),'TOP'), # ('BOX',(0,0),(-1,-1),2,colors.black), # ('GRID',(0,0),(-1,-1),0.5,colors.green), # ]) # d._argW[0]=1.5*inch data = [['Övrigt enl. önskemål:'], [p1], ['Anm:'], [p2], ] d=Table(data,style=[ #(col, row) #('ALIGN',(0,0),(0,1),'RIGHT'), #('VALIGN',(0,0),(0,1),'TOP'), ('BOX',(0,0),(0,1),1.0,colors.black), ('BOX',(0,2),(0,3),1.0,colors.black), ]) d._argW[0]=3.8*inch elements.append(d) elements.append(FrameBreak()) ############################################################### ############################################################### #Signature data = [['Signatur tekniker:', '']] e=Table(data,colWidths=None, rowHeights=1*[0.4*inch],style=[ ('BOX',(0,0),(-1,-1),2,colors.black), ('ALIGN',(0,0),(-1,-1),'LEFT'), ]) e._argW[-1]=2.8*inch k = Spacer(1, 0.35*inch) elements.append(k) elements.append(e) ############################################################### # write the document to disk doc.build(elements) return response
def get_elements(self): elements = [] table_style_data = [('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBELOW', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (0, -1), 1, colors.black), ('BACKGROUND', (0, 0), (1, 0), colors.lightblue)] table_style = TableStyle(table_style_data) table_style.spaceAfter = 25 heading_style = TableStyle(table_style_data) heading_style.spaceAfter = 25 heading_style.add('SPAN', (0, 0), (1, 0)) heading_style.add('ALIGN', (0, 0), (1, 0), 'CENTER') localised_date_str = PDFTransformer.get_localised_date( self.response['submitted_at']) heading_data = [[Paragraph(self.survey['title'], style_h)]] heading_data.append( ['Form Type', self.response['collection']['instrument_id']]) heading_data.append( ['Respondent', self.response['metadata']['ru_ref']]) heading_data.append(['Submitted At', localised_date_str]) heading = Table(heading_data, style=heading_style, colWidths='*') elements.append(heading) for question_group in filter(lambda x: 'title' in x, self.survey['question_groups']): section_heading = True for question in filter(lambda x: 'text' in x, question_group['questions']): if question['question_id'] in self.response['data']: try: answer = str( self.response['data'][question['question_id']]) except KeyError: answer = '' # Output the section header if we haven't already # Checking here so that whole sections are suppressed # if they have no answers. if section_heading: elements.append(HRFlowable(width="100%")) elements.append( Paragraph(question_group['title'], style_sh)) section_heading = False # Question not output if answer is empty text = question.get("text") if not text[0].isdigit(): text = " ".join((question.get("number", ""), text)) elements.append(Paragraph(text, style_n)) elements.append(Paragraph(answer, style_answer)) return elements
def exportMotifs(self): # Iterate through each motif num_cols = 2 row_iterator = 0 styles = getSampleStyleSheet() titleStyle = styles['Title'] titleStyle.alignment = 2 titleStyle.fontSize = 20 title = Paragraph("Graphlets", titleStyle) tableData = [[title]] listStyle = TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green), ('TEXTCOLOR', (0, 0), (1, -1), colors.black)]) numberOfRows = len(self._data) # iterate over results in multiples of two for index in range(0, numberOfRows - 1, 2): # Two motifs per row # Input first motif firstMotifFilename = self.svgCache[str(self._data[index][0])] factor = .2 sx = sy = factor drawing1 = svg2rlg(firstMotifFilename) drawing1.width, drawing1.height = drawing1.minWidth( ) * sx, drawing1.height * sy drawing1.scale(sx, sy) # Input Last motif secondMotifFilename = self.svgCache[str(self._data[index + 1][0])] drawing2 = svg2rlg(secondMotifFilename) drawing2.width, drawing2.height = drawing2.minWidth( ) * sx, drawing2.height * sy drawing2.scale(sx, sy) # Append the data tableData.append(["", ""]) tableData.append([self._data[index][0], self._data[index + 1][0]]) tableData.append([drawing1, drawing2]) tableData.append([self._data[index][1], self._data[index + 1][1]]) tableData.append(["", ""]) self.progress.emit(index / numberOfRows * 100) if QThread.currentThread().isInterruptionRequested(): return # For the last row if add the last row if (numberOfRows % 2 != 0): lastElementIndex = numberOfRows - 1 lastmotifRow = self.svgCache[str(self._data[lastElementIndex][0])] drawing1 = svg2rlg(lastmotifRow) factor = .2 sx = sy = factor drawing1.width, drawing1.height = drawing1.minWidth( ) * sx, drawing1.height * sy drawing1.scale(sx, sy) tableData.append(["", ""]) tableData.append([self._data[lastElementIndex][0], ""]) tableData.append([drawing1, ""]) tableData.append([self._data[lastElementIndex][1], ""]) tableData.append(["", ""]) elements = [] t = Table(tableData) listStyle.add("ALIGN", (0, 0), (-1, -1), "CENTER") listStyle.add("VALIGN", (0, 0), (-1, -1), "MIDDLE") listStyle.add("", (0, 0), (-1, -1), "MIDDLE") #listStyle.add("BACKGROUND",(0,0),(-1,-1),colors.red) t.setStyle(listStyle.getCommands()) elements.append(t) elements.append(svg2rlg("./report/plot.svg")) # write the to disk self.pdfFile.build(elements) self.finished.emit(True)
def Set_Bills(self, Bill_List): self.Insert_First_Page_Header(Bill_List) Normal_Style=ParagraphStyle('normal') Right_Para_Style=ParagraphStyle( 'right-col-style', parent=ParagraphStyle('normal'), alignment=TA_CENTER, fontSize=self.Right_Side_Font_Size, leading=self.Right_Side_Font_Size, spaceBefore=0, spaceAfter=0, textColor=colors.white, fontName='Helvetica-Bold') Number_And_Title_Para_Style=Normal_Style=ParagraphStyle('num-title-style', parent=Normal_Style, alignment=TA_LEFT,leftIndent=6, \ textColor=colors.white, fontName='Helvetica-Bold',fontSize=12, leading=16, spaceBefore=0, spaceAfter=0) Committee_And_Recommend_Para_Style=ParagraphStyle('commit-recommend-style', parent=Normal_Style, alignment=TA_LEFT,leftIndent=6, \ textColor=colors.white, fontName='Helvetica-Bold', fontSize=11, leading=15) Liberty_Type_And_Summary_Para_Style=ParagraphStyle('liberty-type-style', parent=Normal_Style, alignment=TA_LEFT,leftIndent=6, \ textColor=colors.black, fontName='Helvetica-Bold', fontSize=11, leading=15) # # Convert the bill data into table format RL_Bill_Table=[] RL_Bill_Table_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) ]) # # Each time through this loop, we add all of the rows to the RL_Bill_Table Base_Row=0 for Bill in Bill_List: URL_Text="<a href=http://www.nhliberty.org/bills/view/2016/" + \ bill.Brief_Bill_Number(Bill.Number, Separator='') + ">" # # There may be specal cases where we have an entry that does not # have a bill number in which case we want to avoid dropping # in our normal text with a comma and just go blank # if len(Bill.Number.strip()) > 0: Number_And_Title_Para=Paragraph(URL_Text + Bill.Number + '</a>, ' + utils.Normalize_Text(Bill.Title), Number_And_Title_Para_Style) else: Number_And_Title_Para=Paragraph(utils.Normalize_Text(Bill.Title),\ Number_And_Title_Para_Style) Number_Only_Para = Paragraph(bill.Brief_Bill_Number(Bill.Number), \ Right_Para_Style) RL_Bill_Table.append([Number_And_Title_Para, Number_Only_Para]) Committee_And_Recommendation_Para=Paragraph(Bill.Committee + ': ' + Bill.Committee_Recommendation, Committee_And_Recommend_Para_Style) RL_Bill_Table.append([Committee_And_Recommendation_Para, '']) Liberty_Type_And_Summary_Para=Paragraph(Bill.Liberty_Type.upper()\ + ': ' + utils.Normalize_Text(Bill.NHLA_Summary), \ Liberty_Type_And_Summary_Para_Style) NHLA_Recommend_Para=Paragraph(Bill.NHLA_Recommendation, \ Right_Para_Style) RL_Bill_Table.append([Liberty_Type_And_Summary_Para, \ NHLA_Recommend_Para]) RL_Bill_Table.append([utils.To_Bullet_List(Bill.GS_Blurb), '']) RL_Bill_Table_Style.add('BACKGROUND',(0,Base_Row), (0,Base_Row),\ colors.black) RL_Bill_Table_Style.add('BACKGROUND',(0,Base_Row+1), (0,Base_Row+1),\ ["HORIZONTAL", colors.HexColor(0x606060), colors.black]) RL_Bill_Table_Style.add('BACKGROUND',(0,Base_Row+2), (0,Base_Row+3),\ colors.transparent) RL_Bill_Table_Style.add('VALIGN',(0,Base_Row),(0,Base_Row+3),"TOP") RL_Bill_Table_Style.add('VALIGN',(1, Base_Row), (1, Base_Row), "TOP") RL_Bill_Table_Style.add('VALIGN',(1, Base_Row+2), (1, Base_Row+3),\ "MIDDLE") RL_Bill_Table_Style.add('SPAN', (1,Base_Row), (1,Base_Row+1)) RL_Bill_Table_Style.add('SPAN', (1,Base_Row+2), (1,Base_Row+3)) RL_Bill_Table_Style.add('BACKGROUND', (1,Base_Row), (1,Base_Row+1), \ colors.black) RL_Bill_Table_Style.add('BACKGROUND', (1,Base_Row+2), (1,Base_Row+3),\ ["VERTICAL", colors.black, colors.HexColor(0x606060)]) RL_Bill_Table_Style.add('TOPPADDING',(1,Base_Row+2), (1,Base_Row+3),7) RL_Bill_Table_Style.add('BOTTOMPADDING',(1,Base_Row+2),\ (1,Base_Row+3),7) RL_Bill_Table_Style.add('BOTTOMPADDING',(0,Base_Row+3),\ (0,Base_Row+3),3) RL_Bill_Table_Style.add('NOSPLIT', (0,Base_Row),(1,Base_Row+3)) Base_Row=Base_Row+4 # # Reportlab does not take kindly to inserting a table with no rows so # if we've ended up with a zero length table, don't insert it # if len(RL_Bill_Table) > 0: t=BetterTable(RL_Bill_Table, [7.06*inch, 1.44*inch]) t.setStyle(RL_Bill_Table_Style) self.doc.elements.append(t)
def create_print_table(table_data): """Formats report data into table""" column_counter = 0 data_list = [] table_keys = [] for key in RECEIVEDDATA.keys(): TEMPDICT = {key: ATTRIBUTEDATA.find(key)} TABLEKEYSINDEX.update(TEMPDICT) SORTEDTABLESINDEX = sorted( (value, key) for (key, value) in TABLEKEYSINDEX.items()) for index in SORTEDTABLESINDEX: table_keys.append(index[1]) header_list = [] rows_count = [] header_style = ParagraphStyle("headerStyle", alignment=TA_CENTER, spaceAfter=4, borderPadding=(10, 10, 10), leftIndent=10, fontName='VeraBd', fontSize=7.5, wordWrap='CJK') key_style = ParagraphStyle(name='keyStyle', alignment=TA_LEFT, spaceAfter=4, fontName='Vera', fontSize=7.5, wordWrap='CJK') val_style = ParagraphStyle(name='valStyle', alignment=TA_RIGHT, spaceAfter=4, fontName='Vera', fontSize=7.5, wordWrap='CJK') for header in table_keys: header_list += [Paragraph(header, header_style), "", ""] rows_count.append(len(table_data[header])) header_list.pop() data_list.append(header_list) rows_number = max(rows_count) column_header_color = Color(0.8666666666666667, 0.8745098039215686, 0.8745098039215686, 1) table_style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (1, 0), 'CENTER'), ('ALIGN', (0, 0), (-1, 0), 'LEFT'), ('BACKGROUND', (0, 0), (1, 0), column_header_color), ('BACKGROUND', (3, 0), (4, 0), column_header_color), ('SPAN', (0, 0), (1, 0)), ('SPAN', (3, 0), (4, 0)), ]) row_color = Color(0.9529411764705882, 0.9529411764705882, 0.9529411764705882, 1) for i in xrange(rows_number): if i % 2 != 0: table_style.add('BACKGROUND', (0, (i + 1)), (1, (i + 1)), row_color) table_style.add('BACKGROUND', (3, (i + 1)), (4, (i + 1)), row_color) values_list = [] for header in table_keys: try: row_value = table_data[header][i] key = Paragraph(row_value.split(":")[0], key_style) val = Paragraph(row_value.split(":")[1], val_style) values_list += [key, val, ""] except IndexError: values_list += ["", "", ""] values_list.pop() data_list.append(values_list) data_table = Table(data_list, colWidths=(145, 100, 10, 145, 100), style=table_style) return data_table
def createDoc(rows, rptType): flightroute = dbMgr(config.flightRoute) doc = SimpleDocTemplate(rptType + baseReport, rightMargin=margin, leftMargin=margin, topMargin=margin, bottomMargin=margin, pagesize=landscape(letter)) # container for the 'Flowable' objects elements = [] elements.append(Paragraph(rptType + " Flights seen on:" + " " + rptDate, styleHeading)) # elements.append(PageBreak) # Set Column Headers even_rows = [] poi = [] chk = [] colWidths = [.75 * inch] + [.8 * inch] + [1 * inch] + [2.2 * inch] + [1.45 * inch] + [.65 * inch] + [ .65 * inch] + [.65 * inch] + [.65 * inch] + [.65 * inch] + [.65 * inch] rowHeights = [.16 * inch] * ((len(rows) * 2) + 2) index = 0 data = [["Start Time", "Mode S", "Call Sign", "Country", "Manufacturer", "First Sqwk", "First Alt", "First GS", "First VR", "First Track", "#MsgRcvd"], ['End Time', 'Registration', 'Route', 'Owner', 'Type', 'Last Sqwk', "Last Alt", "Last GS", "Last VR", "Last Track"]] for row in rows: # Change "N" to "United States" if row[4] == 'N': country = 'United States' else: country = row[4] # Check for missing start_time try: start_time = str(row[53][11:]) except TypeError: start_time = 'UNKNOWN' # Check for missing end_time try: end_time = str(row[54][11:]) except TypeError: end_time = 'UNKNOWN' try: mode_s = str(row[3]) except TypeError: mode_s = "UNKNOWN" try: registration = str(row[6]).strip() except TypeError: registration = '------' try: manufacturer = str(row[12]).strip() except TypeError: manufacturer = '------' try: mfr_type = str(row[14]).strip() except TypeError: mfr_type = '------' try: owner = str(row[21]).strip() except TypeError: owner = '-----' if str(row[81]).strip() == '': firstSquawk = '----' else: firstSquawk = str(row[81]) if str(row[82]).strip() == '': lastSquawk = '----' else: lastSquawk = str(row[82]) if str(row[75]).strip() == '': firstAlt = '------' else: firstAlt = str(row[75]) if str(row[76]).strip() == '': lastAlt = '------' else: lastAlt = str(row[76]) if str(row[55]).strip() == 'None': callsign = '------' route = '------' else: callsign = str(row[55]).strip() route = flightroute.query("select route from FlightRoute where FlightRoute.flight like '" + callsign + "'").fetchall() if len(route) > 0: route = str(route[0][0]) else: route = '------' try: firstGS = str(int(float(row[73]))) except TypeError: firstGS = '------' try: lastGS = str(int(float(row[74]))) except TypeError: lastGS = '------' msg_rcvd = calcMsgCount(row) try: firstVR = str(int(float(row[77]))) except TypeError: firstVR = "------" try: lastVR = str(int(float(row[78]))) except TypeError: lastVR = "------" try: firstTrk = str(int(float(row[79]))) except TypeError: firstTrk = '----' try: lastTrk = str(int(float(row[80]))) except TypeError: lastTrk = '----' data.append( [start_time, mode_s, callsign, country, manufacturer, firstSquawk, firstAlt, firstGS, firstVR, firstTrk, msg_rcvd]) data.append([end_time, registration, route, owner, mfr_type, lastSquawk, lastAlt, lastGS, lastVR, lastTrk]) index += 1 if index % 2 == 0: even_rows.append(index) if row[28] == 1: poi.append(index) if str(row[6]).strip() == 'None': chk.append(index) # Reminder: (column, row) starting at 0 # (0,0) is upper left, (-1,-1) is lower right (row,0),(row,-1) is entire row # t = Table(data, colWidths=colWidths, rowHeights=rowHeights, repeatRows=2) t = Table(data, colWidths=colWidths, rowHeights=rowHeights, repeatRows=2, hAlign='LEFT') t.hAlign = 'LEFT' t.vAlign = 'CENTER' # Define default table attributes tblStyle = TableStyle([]) tblStyle.add('FONTSIZE', (0, 0), (-1, -1), page_font_size) tblStyle.add('TEXTFONT', (0, 0), (-1, -1), page_font) tblStyle.add('TEXTCOLOR', (0, 0), (-1, -1), colors.black) tblStyle.add('TOPPADDING', (0, 0), (-1, -1), 6) tblStyle.add('BOTTOMPADDING', (0, 0), (-1, -1), 0) tblStyle.add('BOX', (0, 0), (-1, 1), .25, colors.black) tblStyle.add('BOX', (0, 0), (-1, -1), 2, colors.black) tblStyle.add('INNERGRID', (0, 0), (-1, 1), 0.15, colors.gray) tblStyle.add('BACKGROUND', (0, 0), (-1, 1), colors.lightblue) tblStyle.add('BACKGROUND', (0, 2), (-1, -1), colors.white) for row in even_rows: row1 = (row) * 2 row2 = row1 + 1 tblStyle.add('BACKGROUND', (0, row1), (-1, row2), colors.lightgreen) if rptType == 'all': for row in poi: row1 = row * 2 row2 = row1 + 1 tblStyle.add('BACKGROUND', (0, row1), (-1, row1), colors.red) tblStyle.add('BACKGROUND', (0, row2), (-1, row2), colors.red) tblStyle.add('TEXTCOLOR', (0, row1), (-1, row1), colors.white) tblStyle.add('TEXTCOLOR', (0, row2), (-1, row2), colors.white) for row in chk: row1 = row * 2 row2 = row1 + 1 tblStyle.add('BACKGROUND', (0, row1), (-1, row1), colors.yellow) tblStyle.add('BACKGROUND', (0, row2), (-1, row2), colors.yellow) tblStyle.add('TEXTCOLOR', (0, row1), (-1, row1), colors.black) tblStyle.add('TEXTCOLOR', (0, row2), (-1, row2), colors.black) t.setStyle(tblStyle) elements.append(t) # write the document to disk doc.build(elements)
def receive_journal(request): """Печать истории принятия материала за день""" user = request.user.doctorprofile # Профиль текущего пользователя from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus import Table, TableStyle from reportlab.lib import colors from reportlab.platypus import Paragraph from reportlab.lib.styles import getSampleStyleSheet styleSheet = getSampleStyleSheet() import os.path import collections import pytz import copy start = str(request.GET.get("start", "1")) group = str(request.GET.get("group", "-2")) return_type = str(request.GET.get("return", "pdf")) otd = str(request.GET.get("otd", "[]")) start = 1 if not start.isdigit() else int(start) group = -2 if group not in ["-2", "-1"] and ( not group.isdigit() or not directory.ResearchGroup.objects.filter( pk=int(group)).exists()) else int(group) otd = [int(x) for x in json.loads(otd)] PROJECT_ROOT = os.path.abspath( os.path.dirname(__file__)) # Директория Django pdfmetrics.registerFont( TTFont('OpenSans', PROJECT_ROOT + '/../static/fonts/OpenSans.ttf')) # Загрузка шрифта response = HttpResponse( content_type='application/pdf') # Формирование ответа response[ 'Content-Disposition'] = 'inline; filename="zhurnal_priema_materiala.pdf"' # Content-Disposition inline для показа PDF в браузере from io import BytesIO buffer = BytesIO() # Буфер from reportlab.pdfgen import canvas c = canvas.Canvas(buffer, pagesize=A4) # Холст tubes = TubesRegistration.objects.filter( issledovaniya__research__subgroup__podrazdeleniye=request.user. doctorprofile.podrazileniye, time_recive__gte=datetime.now().date(), doc_get__podrazileniye__pk__in=otd, doc_recive__isnull=False).order_by( 'issledovaniya__napravleniye__client__pk') local_tz = pytz.timezone(settings.TIME_ZONE) # Локальная временная зона labs = {} # Словарь с пробирками, сгруппироваными по лаборатории directions = set() vids = set() perpage = 47 n_dict = {} n = 1 for v in tubes: # Перебор пробирок idv = v.id if idv in vids: continue vids.add(idv) iss = Issledovaniya.objects.filter( tubes__id=v.id) # Получение исследований для пробирки if group == -1: iss = iss.filter(research__groups__isnull=True) elif group >= 0: iss = iss.filter(research__groups__pk=group) iss_list = collections.OrderedDict() # Список исследований k = "_" if v.doc_get: k = str(v.doc_get.podrazileniye.pk) + "@" + str( v.doc_get.podrazileniye) else: k = str(iss.first().napravleniye.doc.podrazileniye.pk) + "@" + str( iss.first().napravleniye.doc.podrazileniye) if k not in n_dict.keys(): n_dict[k] = 0 for val in iss.order_by( "research__sort_weight" ): # Цикл перевода полученных исследований в список iss_list[val.research.sort_weight] = val.research.title if len(iss_list) == 0: continue ''' if n < start: n += 1 continue''' directions.add(iss[0].napravleniye.pk) if return_type == "pdf": n_dict[k] += 1 if n_dict[k] >= start: if k not in labs.keys( ): # Добавление списка в словарь если по ключу k нету ничего в словаре labs labs[k] = [] if perpage - len(labs[k]) % perpage < len(iss_list): pre = copy.deepcopy(labs[k][len(labs[k]) - 1]) pre["researches"] = "" for x in range(0, perpage - len(labs[k]) % perpage): labs[k].append(pre) for value in iss_list: # Перебор списка исследований labs[k].append( { "type": v.type.tube.title, "researches": iss_list[value], "client-type": iss[0].napravleniye.client.type, "lab_title": iss[0].research.subgroup.title, "time": "" if not v.time_recive else v.time_recive. astimezone(local_tz).strftime("%H:%M:%S"), "dir_id": iss[0].napravleniye.pk, "podr": iss[0].napravleniye.doc.podrazileniye.title, "receive_n": str(n), "tube_id": str(v.id), "direction": str(iss[0].napravleniye.pk), "history_num": iss[0].napravleniye.history_num, "n": n_dict[k], "fio": iss[0].napravleniye.client.shortfio() } ) # Добавление в список исследований и пробирок по ключу k в словарь labs n += 1 directions = list(directions) if return_type == "directions": return HttpResponse(json.dumps(directions), content_type="application/json") labs = collections.OrderedDict(sorted(labs.items())) # Сортировка словаря c.setFont('OpenSans', 20) paddingx = 17 data_header = [ "№", "ФИО, № истории", "№ Напр", "№ емкости", "Тип емкости", "Наименования исследований" ] tw = w - paddingx * 3.5 tx = paddingx * 2 ty = 90 c.setFont('OpenSans', 9) styleSheet["BodyText"].fontName = "OpenSans" styleSheet["BodyText"].fontSize = 7 doc_num = 0 for key in labs: doc_num += 1 p = Paginator(labs[key], perpage) i = 0 if doc_num >= 2: c.showPage() nn = 0 gid = "-1" for pg_num in p.page_range: pg = p.page(pg_num) if len(pg) == 0: continue if pg_num >= 0: drawTituls(c, user, p.num_pages, pg_num, paddingx, pg[0], group=group, otd=key.split("@")[1], start=start) data = [] tmp = [] for v in data_header: tmp.append(Paragraph(str(v), styleSheet["BodyText"])) data.append(tmp) merge_list = {} num = 0 lastid = "-1" for obj in pg.object_list: tmp = [] if lastid != obj["tube_id"]: if gid != obj["tube_id"]: i += 1 lastid = gid = obj["tube_id"] shownum = True else: shownum = False if lastid not in merge_list.keys(): merge_list[lastid] = [] merge_list[lastid].append(num) if shownum: nn += 1 tmp.append( Paragraph(str(obj["n"]), styleSheet["BodyText"]) ) # "--" if obj["receive_n"] == "0" else obj["receive_n"], styleSheet["BodyText"])) fio = obj["fio"] if obj["history_num"] and len(obj["history_num"]) > 0: fio += ", " + obj["history_num"] tmp.append(Paragraph(fio, styleSheet["BodyText"])) tmp.append( Paragraph(obj["direction"], styleSheet["BodyText"])) tmp.append( Paragraph(obj["tube_id"], styleSheet["BodyText"])) tmp.append(Paragraph(obj["type"], styleSheet["BodyText"])) else: tmp.append("") tmp.append("") tmp.append("") tmp.append("") tmp.append("") research_tmp = obj["researches"] if len(research_tmp) > 44: research_tmp = research_tmp[0:-(len(research_tmp) - 44)] + "..." tmp.append(Paragraph(research_tmp, styleSheet["BodyText"])) data.append(tmp) num += 1 style = TableStyle([('TEXTCOLOR', (0, -1), (-1, -1), colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), ('LEFTPADDING', (0, 0), (-1, -1), 1), ('RIGHTPADDING', (0, 0), (-1, -1), 1), ('TOPPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 1)]) for span in merge_list: # Цикл объединения ячеек for pos in range(0, 6): style.add( 'INNERGRID', (pos, merge_list[span][0]), (pos, merge_list[span][0] + len(merge_list[span])), 0.28, colors.white) style.add( 'BOX', (pos, merge_list[span][0]), (pos, merge_list[span][0] + len(merge_list[span])), 0.2, colors.black) t = Table(data, colWidths=[ int(tw * 0.03), int(tw * 0.23), int(tw * 0.09), int(tw * 0.09), int(tw * 0.23), int(tw * 0.35) ], style=style) t.canv = c wt, ht = t.wrap(0, 0) t.drawOn(c, tx, h - ht - ty) if pg.has_next(): c.showPage() c.setTitle("Журнал приема материала") c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) group_str = "Все исследования" if group >= 0: group_str = directory.ResearchGroup.objects.get(pk=group).title elif group == -2: group_str = "Все исследования" else: group_str = "Без группы" slog.Log(key="", type=25, body=json.dumps({ "group": group_str, "start": start, "otds": [ "%s, %s" % (users.Podrazdeleniya.objects.get(pk=int(x)).title, x) for x in otd ] }), user=request.user.doctorprofile).save() return response
def doit(fname='worksheet.pdf'): doc = SimpleDocTemplate(fname, pagesize=landscape(letter)) doc.leftMargin = doc.rightMargin = \ doc.topMargin = doc.bottomMargin = 0.1 * inch # container for the 'Flowable' objects data = [] blanks = ['' for i in range(24 * 3)] for part in 'ABCD': row = [part, 'Word #'] for i in range(24): row.append(str(i + 1)) row.append('') row.append('') data.append(row) data.append(['', 'Word'] + blanks) data.append(['', 'Hex Digit'] + blanks) if part != 'A': if part == 'B': xor = 'A⊕B' elif part == 'C': xor = '(A⊕B)⊕C' else: xor = '...⊕' + part data.append([xor, ''] + blanks[:-2] + ['X', 'X']) conf = [ #('BACKGROUND',(1,1),(-2,-2),colors.green), #('TEXTCOLOR',(0,0),(0,-1),colors.red), ('VALIGN', (0, 0), (0, -1), 'MIDDLE'), #('ALIGN', (0,0),(0,-1), 'RIGHT'), ('ALIGN', (0, 0), (0, 1), 'CENTER'), ('ALIGN', (1, 0), (2, -1), 'RIGHT'), ('ALIGN', (2, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (0, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (-1, -1), 2), ('RIGHTPADDING', (0, 0), (-1, -1), 2), #('TOPPADDING', (0,0),(-1,-1), 0), #('BOTTOMPADDING', (0,0),(-1,-1), 4.25), ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), ('LINEBEFORE', (2, 0), (2, -1), 1.0, colors.grey), ] for y in [0, 3, 3 + 4, 3 + 4 + 4]: conf.extend([ ('SPAN', (0, y), (0, y + 2)), ('BACKGROUND', (0, y), (0, y + 2), colors.lightgrey), ('LINEABOVE', (0, y), (-1, y), 1.0, colors.grey), ]) if y: conf.extend([ ('SPAN', (0, y + 3), (1, y + 3)), ('ALIGN', (0, y + 3), (1, y + 3), 'RIGHT'), ('LINEABOVE', (0, y + 3), (-1, y + 3), 1.0, colors.grey), ]) for x in range(24): pos = 2 + (x * 3) conf.extend([ ('SPAN', (pos, y), (pos + 2, y)), ('SPAN', (pos, y + 1), (pos + 2, y + 1)), ]) for x in range(3, 24 * 3, 6): conf.extend([ ('BACKGROUND', (2 + x, 0), (2 + x + 2, -1), colors.lightgrey), ]) W1 = 10 W2 = W1 + 2 t = Table(data, repeatRows=0, colWidths=[W2, None] + [W1 for i in range(24 * 3)]) t.setStyle(TableStyle(conf)) seed_samples = [[ cell(w) for w in sorted( list(range(0, 0x800, 0x100)) + [0, 1, 2, 3, 0x7fd, 0x7fe, 0x7ff]) ]] t2 = Table(seed_samples, colWidths=50) t2.setStyle( TableStyle([ ('LEFTPADDING', (0, 0), (-1, -1), 2), ('RIGHTPADDING', (0, 0), (-1, -1), 2), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 4.25), ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), ]), ) hex_table = [['⊕'] + ['%X' % i for i in range(16)]] for y in range(16): hex_table.append(['%X' % y] + ['%X' % (x ^ y) for x in range(16)]) t3 = Table(hex_table, colWidths=None) t3s = TableStyle([ ('ALIGN', (1, 1), (-1, -1), 'CENTER'), ('ALIGN', (1, 1), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), ('FONT', (0, 0), (-1, -1), 'Courier-Bold', 6), ('FONT', (1, 1), (-1, -1), 'Courier', 6), ]) for x in range(0, 16, 2): t3s.add('BACKGROUND', (2 + x, 0), (2 + x, -1), colors.lightgrey) t3.setStyle(t3s) # page top-to-bottom elements = [] elements.append( Paragraph( 'Seed XOR Worksheet', ParagraphStyle('tlab2', alignment=TA_LEFT, fontSize=16, spaceAfter=20, spaceBefore=20))) elements.append(t) elements.append(Spacer(0, 20)) elements.append(t3) if 1: elements.append( Paragraph( 'IMPORTANT: After use, burn with fire!', ParagraphStyle('tlab', alignment=TA_LEFT, fontSize=8, spaceAfter=2, spaceBefore=4))) if 0: elements.append(Spacer(0, 10)) elements.append(t2) doc.build(elements)
# for i in range(count): # t1 = Paragraph("<font name='chsFont'>{}</font>".format(textlist[i][0]),styleN) # t2 = Paragraph("<font name='chsFont'>{}</font>".format(textlist[i][1]),styleN) # t3 = Paragraph("<font name='chsFont'>{}</font>".format(textlist[i][2]),styleN) # t4 = Paragraph("<font name='chsFont'>{}</font>".format(textlist[i][3]),styleN) # data.append([t1,t2,t3,t4]) t3 = Paragraph("<font name='chsFont'>{}</font>".format(textlist[1][2]), styleN) t4 = Paragraph("<font name='chsFont'>{}</font>".format(textlist[0][3]), styleN) data.append(['', '', t3, t4]) tableThatSplitsOverPages = Table(data, [1 * cm, 4 * cm], repeatRows=1) tableThatSplitsOverPages.hAlign = 'LEFT' tblStyle = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBELOW', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (0, -1), 1, colors.black)]) tblStyle.add('BACKGROUND', (0, 0), (1, 0), colors.white) tblStyle.add('BACKGROUND', (0, 1), (-1, -1), colors.white) tableThatSplitsOverPages.setStyle(tblStyle) elements.append(tableThatSplitsOverPages) doc.build(elements) print('PDF was Generated')
def drawTable(self, group=None, monocell=None, reiter = None): """ Drawing a table """ matrix = [] lst = [] matrix2 = [] vector = [] # Total of element's table cells = int(self.tablesPropertie['cells']) columns = int(self.tablesPropertie['columns']) rows = int(self.tablesPropertie['rows']) widths = self.tablesPropertie['widths'] heights = self.tablesPropertie['heights'] xpos = self.tablesPropertie['xpos'] ypos = self.tablesPropertie['ypos'] # print "DATI", cells, columns, rows, group, heights, widths contColumns = 0 ch = '' col = 0 cycle = False vector = [] alignment= None itexts = self.tablesPropertie['itextsobj'] paras = self.tablesPropertie['parasobj'] stile = TableStyle([]) stile.add('VALIGN',(0,0),(-1,-1),'TOP') tblprop = self.tablesPropertie['cellProperties'] if monocell==True: cells = 1 columns=1 rows = 1 for v in xrange(0,cells): if v == 0: contRows = 0 contColumns = 0 elif columns==1: contColumns = -1 contRows= int(v/columns) else: contRows= int(v/columns) contColumns = ((v)%columns) background = self.backgroundFunc(tblprop[v])# Finding background hexBorderColor = self.hexBorderColorFunc(tblprop[v]['borderColor']) stile.add('ROWBACKGROUNDS', (contColumns,contRows), (contColumns,contRows), (background, background)) cellpr = tblprop[v] cellpict = cellpr['cellPicture'] cellIMGHeight = cellpr['cellHeight'] cellIMGWidth = cellpr['cellWidth'] if (cellpr['bottomLine'] == 1 and cellpr['topLine'] == 1 and\ cellpr['leftLine'] == 1 and cellpr['rightLine'] == 1): stile.add('BOX', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) else: if cellpr['bottomLine'] == 1: stile.add('LINEBELOW', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) elif cellpr['topLine'] == 1: stile.add('LINEABOVE', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if cellpr['leftLine'] == 1: stile.add('LINEBEFORE', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if cellpr['rightLine'] == 1: stile.add('LINEAFTER', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if not monocell: ch = self.chFunc(itexts[v])[0] itext = self.chFunc(itexts[v])[1] else: try: itext = itexts[0] ch = itexts[0].get('CH') except: itext = None ch = "" # self.chFunc(itexts[0])[1] actualPageObject = self.tablesPropertie# Borders uff = self.tablesPropertie['iterproper'] if uff != [] and v > columns: pdfAlignment = self.alignmentFunc(self.tablesPropertie['iterproper'][contColumns],v, reiter=True) else: pdfAlignment = self.alignmentFunc(paras, v, monocell) #alignment stile.add('ALIGN', (contColumns,contRows), (contColumns,contRows), pdfAlignment) if itext != None: fontName = self.fontNameFunc(itext) # Font name stile.add('FONT', (contColumns,contRows), (contColumns,contRows), fontName) fontSize = self.fontSizeFunc(itext)# Font size stile.add('FONTSIZE', (contColumns,contRows), (contColumns,contRows), fontSize) foreground = self.foregroundFunc(itext) #foreground stile.add('TEXTCOLOR', (contColumns,contRows), (contColumns,contRows), foreground) if "bcview" in ch: alignment="LEFT" vector.append(Sla2pdfUtils.createbarcode(ch)) else: vector.append(Sla2pdfUtils.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize)) elif cellpict: (imgPath, imgFile) = os.path.split(cellpict) path = Environment.imagesDir + imgFile widthIMG = (float(cellIMGHeight)-2)*100/(float(cellIMGWidth)-2) img = Image(path,width=widthIMG,height=float(cellIMGHeight)-2) vector.append(img) else: vector.append('') if monocell==True: cycle= True elif ((v+1)%columns) == 0: contRows = 0 cycle= True if cycle == True: matrix.append(vector) vector = [] cycle = False # if columns > 1 and not reiter: # #wid = [] # hei = [] # for h in range(0,len(heights),rows): # hei.append(heights[h]) # heights = hei table=Table(matrix,style=stile, colWidths=widths[:columns], rowHeights=heights[:rows]) lst.append(table) # Effective table size sumRows = Sla2pdfUtils.sumRowsFunc(heights,rows) sumColumns = Sla2pdfUtils.sumColumnsFunc(widths,columns) f = Frame(x1=(xpos[0] - self.pageProperties[self.pdfPage][9]), y1=(self.pageProperties[self.pdfPage][7] - ypos[0] - sumRows + self.pageProperties[self.pdfPage][10] - 12), width=sumColumns, height=(sumRows+12), showBoundary=0) sumRows = sumColumns = 0 f.addFromList(lst, self.canvas) reiter = False
def generate_summary_table(huc12): """Make a table summarizing our results, please.""" data = [] data.append([ "Year", "Precip", "Runoff", "Loss", "Delivery", '2+" Precip', "Events", ]) data.append([ "", "[inch]", "[inch]", "[tons/acre]", "[tons/acre]", "[days]", "[days]", ]) pgconn = get_dbconn("idep") huc12col = "huc_12" if len(huc12) == 8: huc12col = "substr(huc_12, 1, 8)" df = read_sql( """ WITH data as ( SELECT extract(year from valid)::int as year, huc_12, (sum(qc_precip) / 25.4)::numeric as sum_qc_precip, (sum(avg_runoff) / 25.4)::numeric as sum_avg_runoff, (sum(avg_loss) * 4.463)::numeric as sum_avg_loss, (sum(avg_delivery) * 4.463)::numeric as sum_avg_delivery, sum(case when qc_precip >= 50.8 then 1 else 0 end) as pdays, sum(case when avg_loss > 0 then 1 else 0 end) as events from results_by_huc12 WHERE scenario = 0 and """ + huc12col + """ = %s and valid >= '2008-01-01' GROUP by year, huc_12) SELECT year, round(avg(sum_qc_precip), 2), round(avg(sum_avg_runoff), 2), round(avg(sum_avg_loss), 2), round(avg(sum_avg_delivery), 2), round(avg(pdays)::numeric, 1), round(avg(events)::numeric, 1) from data GROUP by year ORDER by year """, pgconn, params=(huc12, ), index_col="year", ) for year, row in df.iterrows(): vals = [year] vals.extend(["%.2f" % (f, ) for f in list(row)[:-2]]) vals.extend(["%.0f" % (f, ) for f in list(row)[-2:]]) data.append(vals) data[-1][0] = "%s*" % (data[-1][0], ) totals = df.iloc[:-1].mean() vals = ["Average"] vals.extend(["%.2f" % (f, ) for f in list(totals)]) data.append(vals) style = TableStyle([ ("LINEBELOW", (1, 1), (-1, 1), 0.5, "#000000"), ("LINEAFTER", (0, 2), (0, -2), 0.5, "#000000"), ("LINEABOVE", (1, -1), (-1, -1), 0.5, "#000000"), ("ALIGN", (0, 0), (-1, -1), "RIGHT"), ]) for rownum in range(3, len(data) + 1, 2): style.add("LINEBELOW", (0, rownum), (-1, rownum), 0.25, "#EEEEEE") return Table(data, style=style)
def create_print_table(table_data): """Formats report data into table""" num_columns = len(RECEIVEDDATA.keys()) if num_columns != 1 and num_columns != 2: arcpy.AddError("Only one or two columns are supported") return None data_list = [] table_keys = [] for key in RECEIVEDDATA.keys(): TEMPDICT = {key : ATTRIBUTEDATA.find(key)} TABLEKEYSINDEX.update(TEMPDICT) SORTEDTABLESINDEX = sorted((value, key) for (key, value) in TABLEKEYSINDEX.items()) for index in SORTEDTABLESINDEX: table_keys.append(index[1]) header_list = [] rows_count = [] header_style = ParagraphStyle("headerStyle", alignment=TA_CENTER, spaceAfter=4, borderPadding=(10, 10, 10), leftIndent=10, fontName='VeraBd', fontSize=7.5, wordWrap='CJK') key_style = ParagraphStyle(name='keyStyle', alignment=TA_LEFT, spaceAfter=4, fontName='Vera', fontSize=7.5, wordWrap='CJK') val_style = ParagraphStyle(name='valStyle', alignment=TA_RIGHT, spaceAfter=4, fontName='Vera', fontSize=7.5, wordWrap='CJK') for header in table_keys: header_list += [Paragraph(header, header_style), "", ""] rows_count.append(len(table_data[header])) header_list.pop() data_list.append(header_list) rows_number = max(rows_count) column_header_color = Color(0.8666666666666667, 0.8745098039215686, 0.8745098039215686, 1) if num_columns == 1: table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (1, 0), 'CENTER'), ('ALIGN', (0, 0), (-1, 0), 'LEFT'), ('BACKGROUND', (0, 0), (1, 0), column_header_color), ('SPAN', (0, 0), (1, 0)), ]) else: table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (1, 0), 'CENTER'), ('ALIGN', (0, 0), (-1, 0), 'LEFT'), ('BACKGROUND', (0, 0), (1, 0), column_header_color), ('BACKGROUND', (3, 0), (4, 0), column_header_color), ('SPAN', (0, 0), (1, 0)), ('SPAN', (3, 0), (4, 0)), ]) row_color = Color(0.9529411764705882, 0.9529411764705882, 0.9529411764705882, 1) for i in xrange(rows_number): if i % 2 != 0: table_style.add('BACKGROUND', (0, (i+1)), (1, (i+1)), row_color) if num_columns == 2: table_style.add('BACKGROUND', (3, (i+1)), (4, (i+1)), row_color) values_list = [] for header in table_keys: try: row_value = table_data[header][i] key = Paragraph(row_value.split(":")[0], key_style) val = Paragraph(row_value.split(":")[1], val_style) values_list += [key, val,""] except IndexError: values_list += ["", "",""] values_list.pop() data_list.append(values_list) if num_columns == 1: data_table = Table(data_list, colWidths=(145, 100), style=table_style) else: data_table = Table(data_list, colWidths=(145, 100, 10, 145, 100), style=table_style) return data_table
def define_totals_table_style(): table_style = TableStyle() # All rows table_style.add('TOPPADDING', (0, 0), (-1, -1), 0) table_style.add('BOTTOMPADDING', (0, 0), (-1, -1), 0) table_style.add('VALIGN', (0, 0), (-1, -1), "MIDDLE") table_style.add('INNERGRID', (0, 1), (-1, -1), 0.2 * mm, colors.black) table_style.add('BOX', (0, 1), (-1, -1), 0.4 * mm, colors.black) table_style.add('BOX', (0, 1), (-1, -2), 0.4 * mm, colors.black) # Header column table_style.add('INNERGRID', (0, 0), (-1, 0), 0.2 * mm, colors.black) table_style.add('BOX', (0, 0), (-1, 0), 0.4 * mm, colors.black) table_style.add('BACKGROUND', (0, 0), (1, 0), colors.black) table_style.add('SPAN', (0, 0), (1, 0)) return table_style
# Prepare the TableStyle. myTableStyle = TableStyle([('LINEABOVE', (0,0), (-1,0), 2, colors.green), ('LINEBELOW', (0,0), (-1,0), 2, colors.green), ('LINEBELOW', (0,1), (-1,-1), 0.25, colors.black), ('LINEBELOW', (0,-1), (-1,-1), 2, colors.green), ('ALIGN', (1,1), (-1,-1), 'RIGHT')] ) # add some conditional formatting to the table style for i, data in enumerate(table_data): if not i: continue # skip header row for col in range(1,3): mb = int(data[col]) # megabytes uploaded or downloaded # color each cell from white at 0MB to a maximum of full red at 1000MB myTableStyle.add('BACKGROUND', (col, i), (col, i), lerp(colors.white, colors.red, 0, 1000, min(mb, 1000))) # The table flowables. A couple of points to note: # - repeatRows=1 means that 1 row (the header) will repeat at the top of each # page that the table flows on to. # - colWidths needs to be defined manually if you want the table to span the # entire width of the frame. myTable = Table(table_data, repeatRows=1, colWidths=[170/3.*mm]*3, style=myTableStyle) story.append(myTable) story.append(Spacer(1, 15*mm)) doc.build(story)
class InvoiceDocument: """This class represents a pdf invoice. All units are in mm pdffilePath is the output pdf file invoiceData = [invoiceHeader, lesson1List, ..., lessonNList] invoiceHeader = [invoice_date, invoice_to, invoice_for, invoice_ref, n, amount] lesson1List = [date, tuition_ref, hours, rate, amount, reason1, money1, ..., reasonN, moneyN, "discount", money] """ def __init__(self, pdffilePath, invoiceData): self.pageHeight = A4[1] / mm # in mm, all units in mm self.pageWidth = A4[0] / mm self.lMargin = 20.0 self.rMargin = 20.0 self.tMargin = 30.0 self.bMargin = 30.0 #print("page size of A4 in mm: ", self.pageWidth, self.pageHeight) self.canvas = Canvas(pdffilePath, pagesize=A4) self.canvas.setTitle("Invoice for Maths tuition") self.title = "Invoice for Maths tuition" self.fontPathBase = "./fonts/%s.ttf" #print("Font: ", self.fontPathBase % "DejaVuSerif") pdfmetrics.registerFont( TTFont('DejaVu', self.fontPathBase % "DejaVuSerif")) pdfmetrics.registerFont( TTFont('DejaVu-Bold', self.fontPathBase % "DejaVuSerif-Bold")) pdfmetrics.registerFont( TTFont('DejaVu-Italics', self.fontPathBase % "DejaVuSerif-Italic")) self.tutorData = [ "Hannes Buchholzer", "3 April Close, Horsham, RH12 2LL", "07516-100218", "*****@*****.**" ] self.invoiceHeader = invoiceData.pop(0) self.invoiceData = invoiceData # translate coordinates x,y in mm from top left # into pixels from bottom right def coord(self, x, y, fromRight=False, fromBottom=False): cx = (self.pageWidth - x) * mm if fromRight else x * mm cy = y * mm if fromBottom else (self.pageHeight - y) * mm return (cx, cy) # translate a mm value into pixels. Works also for a list of mm values def trans(self, x): if isinstance(x, list): cx = list(range(len(x))) for i in range(len(x)): cx[i] = float(x[i]) * mm else: cx = float(x) * mm return cx # convert Money to String # x should be a money amount as integer and float # the output is a string with £ sign def cM2S(self, x): x = float(x) if x < 0.0: pre = "-" x = -x else: pre = "" s = pre + "£{0:4.2f}".format(x) #print("convertMoney2String: ", x, " ", s) return s # convert date to String # x should be a list of 3 integers # day, month, year def cD2S(self, x): if x[2] < 100: x[2] += 2000 s = "{0:>02n}/{1:>02n}/{2:4n}".format(*x) #print("convertDate2String: ", x, " ", s) return s # draw it centered y mm from top def draw_heading(self, y): # canvas.saveState() self.canvas.setFont('DejaVu', 20) (cx, cy) = self.coord(self.pageWidth / 2.0, y) self.canvas.drawCentredString(cx, cy, self.title) # canvas.restoreState() # draw the tutor's details; here x, y is the bottom left # corner of the first line in mm def draw_tutor(self, x, y): # canvas.saveState() cx, cy = self.coord(x, y) self.canvas.setFont('DejaVu-Bold', 13) self.canvas.drawString(cx, cy, self.tutorData[0]) self.canvas.setFont('DejaVu', 10) cy -= 15 self.canvas.drawString(cx, cy, "address:") self.canvas.drawString(cx + 19 * mm, cy, self.tutorData[1]) cy -= 13 self.canvas.drawString(cx, cy, "phone:") self.canvas.drawString(cx + 19 * mm, cy, self.tutorData[2]) cy -= 13 self.canvas.drawString(cx, cy, "email:") self.canvas.drawString(cx + 19 * mm, cy, self.tutorData[3]) # canvas.restoreState() # draw the date; again x, y are in mm # y is the distance from the top # x is the distance from the right def draw_invoice_date(self, x, y): # canvas.saveState() cx, cy = self.coord(x, y, fromRight=True) self.canvas.setFont('DejaVu-Bold', 10) self.canvas.drawRightString(cx, cy, "invoice date:") self.canvas.setFont('DejaVu', 10) cy -= 12 # go 12 pixels lower self.canvas.drawRightString(cx, cy, self.invoiceHeader[0]) # canvas.restoreState() # draw the date; y is in mm # y is the distance from the top def draw_invoice_data(self, y): middlex = 80 # canvas.saveState() cx, cy = self.coord(self.lMargin, y) self.canvas.setFont('DejaVu-Bold', 11) self.canvas.drawString(cx, cy, "invoice to:") cx, cy = self.coord(middlex, y) self.canvas.drawString(cx, cy, "invoice for:") cx, cy = self.coord(self.pageWidth - 20, y) self.canvas.drawRightString(cx, cy, "invoice reference nr:") self.canvas.setFont('DejaVu', 10) cy -= 12 # go 12 pixels lower cx = self.lMargin * mm self.canvas.drawString(cx, cy, self.invoiceHeader[1]) cx = middlex * mm self.canvas.drawString(cx, cy, self.invoiceHeader[2]) cx = (self.pageWidth - 20) * mm self.canvas.drawRightString(cx, cy, self.invoiceHeader[3]) # canvas.restoreState() # draw table # y is the distance in mm from top def draw_table(self, y): vspace = 4 y += 8 self.headStyle = TableStyle([('FONT', (0, 0), (-1, 0), 'DejaVu-Bold', 10), ('GRID', (0, 0), (-1, 0), 2, black)]) self.bodyStyle = TableStyle([('FONT', (0, 0), (-1, -1), 'DejaVu', 10), ('BOX', (0, 0), (-1, -1), 2, black), ('LINEBEFORE', (1, 0), (1, -1), 2, black), ('LINEBEFORE', (2, 0), (2, -1), 2, black), ('LINEBEFORE', (3, 0), (3, -1), 2, black), ('LINEBEFORE', (4, 0), (4, -1), 2, black), ('LINEBEFORE', (5, 0), (5, -1), 2, black), ('ALIGN', (3, 0), (5, -1), 'RIGHT')]) self.footStyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'DejaVu-Bold', 10), ('BOX', (0, 0), (-1, -1), 2, black), ('ALIGN', (0, 0), (0, 0), 'CENTER'), ('ALIGN', (1, 0), (1, 0), 'RIGHT'), ('LINEBEFORE', (1, 0), (1, -1), 2, black) ]) dataBody = [] num = 0 for lesson in self.invoiceData: #print("Line: ", lesson) num += 1 line = lesson[0:2] line.append("teaching") line.append("{0:3.2f}".format(lesson[2])) line.append(self.cM2S(lesson[3])) line.append(self.cM2S(lesson[4])) dataBody.append(line) lRest = lesson[5:] while lRest: num += 1 extra_reason = lRest.pop(0) extra_cost = self.cM2S(lRest.pop(0)) line2 = [None, None, extra_reason, None, None, extra_cost] dataBody.append(line2) self.bodyStyle.add('LINEABOVE', (0, num), (-1, num), 2, black) dataHead = [[ "date", "tuition reference", "description", "hours", "rate", "amount" ]] dataFoot = [["total", self.cM2S(self.invoiceHeader[-1])]] colWiMMB = [25, 48, 42, 16, 18, 20] colWiMMF = [sum(colWiMMB[0:-1]), colWiMMB[-1]] colWidthB = self.trans(colWiMMB) colWidthF = self.trans(colWiMMF) #print(colWiMMB, colWiMMF) self.tableHead = Table(dataHead, colWidths=colWidthB, style=self.headStyle) self.tableBody = Table(dataBody, colWidths=colWidthB, style=self.bodyStyle, repeatRows=0) self.tableFoot = Table(dataFoot, colWidths=colWidthF, style=self.footStyle) sw, sh = self.tableHead.wrapOn(self.canvas, *self.trans([180, 10])) tw, th = self.tableBody.wrapOn(self.canvas, *self.trans([180, 120])) uw, uh = self.tableFoot.wrapOn(self.canvas, *self.trans([180, 10])) xx, yy = self.coord(self.lMargin, y) ay = yy - sh by = ay - th - vspace cy = by - uh - vspace theight = (sh + th + uh + 2 * vspace) / mm self.tableHead.drawOn(self.canvas, xx, ay) self.tableBody.drawOn(self.canvas, xx, by) self.tableFoot.drawOn(self.canvas, xx, cy) return theight # draw the date; y is in mm # y is the distance from the top def draw_invoice_foot(self, y): # canvas.saveState() cx, cy = self.coord(self.pageWidth / 2.0, y + 6) self.canvas.setFont('DejaVu', 10) # theight is becoming the total height of # the footer theight = 10 self.canvas.drawCentredString( cx, cy, "Please pay by bank transfer to following account within 7 calendar days of invoice date:" ) cy -= 13 theight += 13 self.canvas.drawCentredString( cx, cy, "Account Title: Hannes Buchholzer, Sort Code: 20-42-58, Account Number: 23821595." ) cy -= 13 theight += 13 self.canvas.setFont('DejaVu-Italics', 10) self.canvas.drawCentredString( cx, cy, "Please set the reference as the invoice reference number :") cy -= 20 theight += 20 self.canvas.setFont('DejaVu', 12) cx = self.trans(self.pageWidth / 2.0) self.canvas.drawCentredString(cx, cy, self.invoiceHeader[3]) cy -= 20 theight += 20 self.canvas.setFont('DejaVu', 10) self.canvas.drawCentredString( cx, cy, "Thank you for choosing me as your Tutor!") theight = theight / mm # convert into mm return theight def compileInvoice(self): self.draw_heading(30) self.draw_tutor(20, 50) self.draw_invoice_date(20, 50) self.draw_invoice_data(90) height1 = self.draw_table(110) yfoot = 120 + height1 + 20 if yfoot <= 250.0: height2 = self.draw_invoice_foot(yfoot) else: self.canvas.showPage() height2 = self.draw_invoice_foot(35) self.canvas.save()