def createBeritaAcaraPage(contain, styles, tahunAkademik, hariSekarang, tglSekarang, namaDosen, prodi, kelas, jumlahMhs, jumlahHadir, jumlahTdkHadir, listMasukan, namaDeputi, namaKaprodi, qrDeputi, qrKaprodi, qrDosen): text = '<font size="14"><b>BERITA ACARA PERWALIAN</b></font>' contain.append(Paragraph(text, styles["Center"])) contain.append(Spacer(1, .5*cm)) text = f'<font size="14"><b>TAHUN AKADEMIK {tahunAkademik}</b></font>' contain.append(Paragraph(text, styles["Center"])) contain.append(Spacer(1, 1.5*cm)) text = f'<font size="12">Pada hari ini {hariSekarang} tanggal {tglSekarang}, telah dilaksanakan Perwalian Tahun Akademik {tahunAkademik} dengan data sebagai berikut:</font>' contain.append(Paragraph(text, styles["Justify"])) contain.append(Spacer(1, .5*cm)) data = [['Nama Dosen Wali', ':', namaDosen], ['Jurusan / Kelas', ':', f'{prodi} / {kelas}'], ['Jumlah Mahasiswa', ':', jumlahMhs], ['Jumlah yang hadir', ':', jumlahHadir], ['Jumlah yang tidak hadir', ':', jumlahTdkHadir], ] table = Table(data, [5*cm, .5*cm, 10.5*cm], len(data)*[.6*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ])) contain.append(table) contain.append(Spacer(1, .7*cm)) text = '<font size="12">Catatan masukan dari mahasiswa :</font>' contain.append(Paragraph(text, styles["Justify"])) contain.append(Spacer(1, .1*cm)) table = Table(listMasukan, [.8*cm, 15.2*cm], len(listMasukan)*[.6*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ])) contain.append(table) contain.append(Spacer(1, .7*cm)) data = [ [Paragraph('<font size="12"><b>Dosen Wali,</b></font>', styles["Center"]), Paragraph('<font size="12"><b>Ketua Prodi,</b></font>', styles["Center"]), Paragraph('<font size="12"><b>Deputi Akademik,</b></font>', styles["Center"])], [Image(qrDeputi, 4*cm, 4*cm), Image(qrKaprodi, 4*cm, 4*cm), Image(qrDosen, 4*cm, 4*cm)], [Paragraph(f'<font size="12"><u>{namaDosen}</u></font>', styles["Center"]), Paragraph(f'<font size="12"><u>{namaKaprodi}</u></font>', styles["Center"]), Paragraph(f'<font size="12"><u>{namaDeputi}</u></font>', styles["Center"])], ] table = Table(data, [6.8*cm, 6.8*cm, 6.8*cm], [.6*cm, 4.5*cm, 1*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('ALIGN',(0,1),(-1,-1),'CENTER'), ])) contain.append(table) contain.append(PageBreak())
def get_table_style(self): style = TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ]) return style
def gen_footer_col2(self): w = self.usable_width / 2 h = self.usable_height s = self footer_totals_data = [["Subtotal", "000"]] def get_data(): return [[ "Subtotal", s._format_moneda(s.subtotales[s.drawn_items - 1]) ]] tbl = RestrictTable(footer_totals_data, w, h, get_data, [w - 70, 70]) tablestyle = TableStyle([('ALIGN', (-1, 0), (-1, -1), 'RIGHT'), ('BOTTOMPADDING', (0, 0), (-1, -1), 2), ('TOPPADDING', (0, -1), (-1, -1), 8), ('TEXTCOLOR', (0, 0), (-1, -1), (.3, .3, .3)), ('FONTNAME', (0, -1), (-1, -1), _baseFontNameB), ('FONTSIZE', (0, 0), (-1, -1), 8)]) tbl.setStyle(tablestyle) return [VSpace(), tbl, VSpace()]
def addTable(data, width=None, height=None, topHeader=False, leftHeader=False, add_style=None): # Create table object t = Table(data, colWidths=width, rowHeights=height, hAlign=TA_CENTER) # List default styles style = [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('FACE', (0, 0), (-1, -1), 'Courier')] # Add optional styles for headers at the top or left of the table if leftHeader: style.append(('BACKGROUND', (0, 0), (0, -1), colors.ReportLabFidBlue)) style.append(('TEXTCOLOR', (0, 0), (0, -1), colors.white)) style.append(('FACE', (0, 0), (0, -1), 'Courier-Bold')) if topHeader: style.append(('BACKGROUND', (0, 0), (-1, 0), colors.ReportLabFidBlue)) style.append(('TEXTCOLOR', (0, 0), (-1, 0), colors.white)) style.append(('FACE', (0, 0), (-1, 0), 'Courier-Bold')) # This is for any additional styles we may want to add. Feed them in as an array and this will add them to the table style when drawn. if add_style != None: for s in add_style: style.append(s) t.setStyle(TableStyle(style)) # Add the table doc.append(t)
def endFunctions(self, names): h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code styleSheet = getSampleStyleSheet() bt1 = styleSheet['BodyText'] story = self.story if not names: return tsa = tableStyleAttributes = [] # Make table with class and method rows # and add it to the story. p = Paragraph('<b>%s</b>' % self.classCompartment, bt) p.style.alignment = TA_CENTER rows = [(p, )] lenRows = len(rows) tsa.append(('BOX', (0, 0), (-1, lenRows - 1), 0.25, colors.black)) for name, doc, sig in self.methodCompartment: nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1) rows.append((nameAndSig, )) # No doc strings, now... # docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1) # rows.append((docStr,)) tsa.append(('BOX', (0, lenRows), (-1, -1), 0.25, colors.black)) t = Table(rows, (12 * cm, )) tableStyle = TableStyle(tableStyleAttributes) t.setStyle(tableStyle) self.story.append(t) self.story.append(Spacer(1 * cm, 1 * cm))
def striped_table(listA,listB): alt_join = stripe_lists(listA, listB) table_data = [] for row in alt_join: new_row = [] for item in row: content = Paragraph(item, table_cell_style) new_row.append(content) table_data.append(new_row) t=Table(table_data, colWidths=(PDF_WIDTH-2*margin)/num_cols) for each in range(len(alt_join)): if each % 2 == 0: bg_color = HEADER_COLOR txt_color = HEADER_TEXT_COLOR else: bg_color = BODY_COLOR txt_color = BODY_TEXT_COLOR t.setStyle(TableStyle([ ('BACKGROUND',(0,each),(num_cols,each),bg_color), ('TEXTCOLOR',(0,0),(num_cols,0),txt_color), ('ALIGN',(0,0),(-1,-1),'CENTER'), ('BOX',(0,0),(-1,-1),0.25, black), ('INNERGRID',(0,0),(-1,-1),0.25,black), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('LEFTPADDING',(0,0),(-1,-1),2), ('RIGHTPADDING',(0,0),(-1,-1),2), ('BOTTOMPADDING',(0,0),(-1,-1),2), ('TOPPADDING',(0,0),(-1,-1),2) ])) return t
def endClass(self, name, doc, bases): h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code styleSheet = getSampleStyleSheet() bt1 = styleSheet['BodyText'] story = self.story # Use only the first line of the class' doc string -- # no matter how long! (Do the same later for methods) classDoc = reduceDocStringLength(doc) tsa = tableStyleAttributes = [] # Make table with class and method rows # and add it to the story. p = Paragraph('<b>%s</b>' % self.classCompartment, bt) p.style.alignment = TA_CENTER rows = [(p, )] # No doc strings, now... # rows = rows + [(Paragraph('<i>%s</i>' % classDoc, bt1),)] lenRows = len(rows) tsa.append(('BOX', (0, 0), (-1, lenRows - 1), 0.25, colors.black)) for name, doc, sig in self.methodCompartment: nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1) rows.append((nameAndSig, )) # No doc strings, now... # docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1) # rows.append((docStr,)) tsa.append(('BOX', (0, lenRows), (-1, -1), 0.25, colors.black)) t = Table(rows, (12 * cm, )) tableStyle = TableStyle(tableStyleAttributes) t.setStyle(tableStyle) self.story.append(t) self.story.append(Spacer(1 * cm, 1 * cm))
def getAttributeTable(self): """ """ rowColor = getTabBackgroundColor() rowColorLight = getTabBackgroundColorLight() ik_tbl_style = TableStyle([\ ('LEFTPADDING', (0,0), (-1,-1), 0), ('RIGHTPADDING', (0,0), (-1,-1), 0), ('BOTTOMPADDING', (0,0), (-1,-1), 0), ('TOPPADDING', (0,0), (-1,-1), 3), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ('ROWBACKGROUNDS',(0,0),(-1,-1),[rowColorLight, rowColor]), ]) colWidths = [50 * mm, 85 * mm] data = [] data.extend(self.prependAttributeTable()) data.extend(self.makeAttributeTable()) data.extend(self.appendAttributeTable()) if len(data) > 0: t0 = Table(data, hAlign='RIGHT', style=ik_tbl_style, colWidths=colWidths) else: t0 = None return t0
def getAttributeTable(self): """ """ ik_tbl_style = TableStyle([\ ('LEFTPADDING', (0,0), (-1,-1), 0), ('RIGHTPADDING', (0,0), (-1,-1), 0), ('BOTTOMPADDING', (0,0), (-1,-1), 0), ('TOPPADDING', (0,0), (-1,-1), 0), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ]) colWidths = [50 * mm, 85 * mm] data = [] fields = self.getReportFields() for f_name, f_obj in fields.items(): f_val = getattr(self.context, f_name) if f_val is not None: rptPara = RptPara(unicode(f_val), doc=self.document) data.append([f_obj.field.title, rptPara]) if len(data) > 0: t0 = Table(data, hAlign = 'RIGHT', style=ik_tbl_style, colWidths=colWidths) else: t0 = None return t0
def vert_table(listA, listB, cols): listC = [] for i in range(len(listA)): row = [] row.append(listA[i]) row.append(listB[i]) listC.append(row) table_data = [] for row in listC: new_row = [] for item in row: content = Paragraph(item, table_cell_style) new_row.append(content) table_data.append(new_row) t=Table(table_data, colWidths=(PDF_WIDTH-2*margin)/cols) t.setStyle(TableStyle([ ('BACKGROUND',(0,0),(0,4),HEADER_COLOR), ('TEXTCOLOR',(0,0),(2,0),black), ('ALIGN',(0,0),(-1,-1),'CENTER'), ('BOX',(0,0),(-1,-1),0.25, black), ('INNERGRID',(0,0),(-1,-1),0.25,black), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('LEFTPADDING',(0,0),(-1,-1),2), ('RIGHTPADDING',(0,0),(-1,-1),2), ('BOTTOMPADDING',(0,0),(-1,-1),2), ('TOPPADDING',(0,0),(-1,-1),2) ])) return t
def through_table(data): styles = getSampleStyleSheet() table_cell_style = ParagraphStyle('yourtitle', alignment=1) table_data = [] for row in data: new_row = [] for item in row: content = Paragraph(item, table_cell_style) new_row.append(content) table_data.append(new_row) t=Table(table_data, colWidths=(PDF_WIDTH-2*margin)/5) t.setStyle(TableStyle([ ('BACKGROUND',(0,0),(0,-1),HEADER_COLOR), ('BACKGROUND',(0,0),(-1,0),HEADER_COLOR), ('TEXTCOLOR',(0,0),(2,0),black), ('ALIGN',(0,0),(-1,-1),'CENTER'), ('BOX',(0,0),(-1,-1),0.25, black), ('INNERGRID',(0,0),(-1,-1),0.25,black), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('LEFTPADDING',(0,0),(-1,-1),2), ('RIGHTPADDING',(0,0),(-1,-1),2), ('BOTTOMPADDING',(0,0),(-1,-1),2), ('TOPPADDING',(0,0),(-1,-1),2) ])) return t
def GenerarReporteEjecutivo(diccionario): data_table = diccionario pdf = 'Reporte Financiero.pdf' doc = SimpleDocTemplate(pdf, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) contenido = [] logo = './img/Entel.jpg' imagen = Image(logo, width=180, height=180, hAlign='CENTER') contenido.append(imagen) Titulo = 'Reporte Ejecutivo:' Estilos = getSampleStyleSheet() Estilos.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) contenido.append(Paragraph(Titulo, Estilos["Normal"])) contenido.append(Spacer(width=1, height=30)) tabla = Table(data_table) estilohead = TableStyle([('BACKGROUND', (0, 0), (3, 0), colors.orangered), ('TEXTCOLOR', (0, 0), (-1, 0), colors.blue), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('GRID', (0, 1), (-1, -1), 2, colors.blue), ('BOX', (0, 0), (-1, -1), 2, colors.blue)]) tabla.setStyle(estilohead) contenido.append(tabla) doc.build(contenido)
def generar_productos(request): print ("Genero el PDF") response = HttpResponse(content_type='application/pdf') pdf_name = "productos.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=10, leftMargin=10, topMargin=60, bottomMargin=18, ) productos = [] styles = getSampleStyleSheet() header = Paragraph("Listado de Productos", styles['Heading2']) productos.append(header) headings = ('Nombre', 'Descripcion', 'precio', 'stock') allproductos = [(p.nombre, p.descripcion, p.precio, p.stock) for p in producto.objects.all()] print (allproductos) t = Table([headings] + allproductos) t.setStyle(TableStyle( [ ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] )) productos.append(t) doc.build(productos) response.write(buff.getvalue()) buff.close() return response
def end(self, c): tdata = c.tableData data = tdata.get_data() # Add missing columns so that each row has the same count of columns # This prevents errors in Reportlab table try: maxcols = max([len(row) for row in data] or [0]) except ValueError: log.warn(c.warning("<table> rows seem to be inconsistent")) maxcols = [0] for i, row in enumerate(data): data[i] += [''] * (maxcols - len(row)) filter_len = filter(lambda col: col is None, tdata.colw) try: filter_len = len(filter_len) except Exception: filter_len = sum(1 for _ in filter_len) cols_with_no_width = filter_len if cols_with_no_width: # any col width not defined bad_cols = filter(lambda tup: tup[1] is None, enumerate(tdata.colw)) fair_division = str( 100 / float(cols_with_no_width)) + '%' # get fair % for i, _ in bad_cols: tdata.colw[i] = fair_division # fix empty with fair % try: if tdata.data: # log.debug("Table styles %r", tdata.styles) t = PmlTable( data, colWidths=tdata.colw, rowHeights=tdata.rowh, # totalWidth = tdata.width, splitByRow=1, # repeatCols = 1, repeatRows=tdata.repeat, hAlign=tdata.align, vAlign='TOP', style=TableStyle(tdata.styles)) t.totalWidth = _width(tdata.width) t.spaceBefore = c.frag.spaceBefore t.spaceAfter = c.frag.spaceAfter # XXX Maybe we need to copy some more properties? t.keepWithNext = c.frag.keepWithNext # t.hAlign = tdata.align c.add_story(t) else: log.warn(c.warning("<table> is empty")) except: log.warn(c.warning("<table>"), exc_info=1) # Cleanup and re-swap table data c.clear_fragment() c.tableData, self.tableData = self.tableData, None
def print_statistics(self): buffer = self.buffer doc = SimpleDocTemplate(buffer, rightMargin=inch / 4, leftMargin=inch / 4, topMargin=inch / 2, bottomMargin=inch / 4, pagesize=self.pageSize) # Our container for 'Flowable' objects elements = [] # A large collection of style sheets pre-made for us styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER)) # Draw things on the PDF. Here's where the PDF generation happens. elements.append( Paragraph(self.statistics["field_text"], styles['Heading1'])) if self.statistics["field_type"] == 'NumberField': pieChart = PieChart(self.statistics["quintilesY"], self.statistics["quintilesX"]) else: pieChart = PieChart(self.statistics["total_per_option"], self.statistics["options"]) elements.append(pieChart) # Draw table rows = [["Field type", self.statistics["field_type"]], ["Answered fields", self.statistics["total_filled"]], ["Empty fields", self.statistics["total_not_filled"]], ["Required", self.statistics["required"]]] if self.statistics["field_type"] == 'NumberField': rows.append(["Mean", self.statistics["mean"]]) rows.append(["Total Mean", self.statistics["total_mean"]]) rows.append( ["Standard Deviation", self.statistics["standard_deviation"]]) rows.append([ "Total Standard Deviation", self.statistics["total_standard_deviation"] ]) table = Table(rows) table.setStyle( TableStyle([('GRID', (0, 0), (-1, -1), 0.25, colors.black)])) elements.append(table) doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer) # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() return pdf
def genera_lettera(citazione): path_file = '%s/lettere/lett_%s%s.pdf' % (settings.DOCDIR, citazione['id_frase'], citazione['canzone']) row = len(citazione['testo'].split(''' ''')) print(citazione['canzone']) size = 6 if row <80 else 4 size = 0 if row < 35: size = 10 elif row < 55: size = 8 elif row < 60: size = 6 else: size = 4 size = int(6 + (100/row)) size = size if row < 80 else 6 size = 10 if row < 38 else size #citazione['autore'] = ' righe %s %%s' % row % size tabella_testo = [ [ par_nero("""{canzone}<br/><br/>""".format(**citazione), font=12, align=TA_CENTER, fontName='papyrus') ], [ #par_nero("{testo}".format(**citazione), font=size, lead=size, align=TA_CENTER, fontName='Times-BoldItalic') par_nero("{testo}".format(**citazione), font=size, lead=size, align=TA_CENTER, fontName='papyrus') ], [ #par_nero("{autore}".format(**citazione), font=8, align=TA_RIGHT) par_nero("{autore}".format(**citazione), font=8, align=TA_RIGHT, fontName='papyrus') ] ] style_row = TableStyle([]) #style_row.add('LINEABOVE', (0, 0), (-1, -1), 0.25, colors.grey) #style_row.add('LINEBELOW', (0, 0), (-1, -1), 0.25, colors.grey) #style_row.add('LINEAFTER', (0, 0), (-1, -1), 0.25, colors.grey) #style_row.add('LINEBEFORE', (0, 0), (-1, -1), 0.25, colors.grey) table = Table(tabella_testo, colWidths=12 * units.cm, style=style_row) doc = SimpleDocTemplate(path_file, pagesize=(13*units.cm, 21*units.cm)) margin_top = 0.5 if row > 60 else (90/row) doc.topMargin = units.cm * margin_top doc.bottomMargin = 0.5 *units.cm doc.build([table])
def end(self, c): tdata = c.tableData data = tdata.get_data() # Add missing columns so that each row has the same count of columns # This prevents errors in Reportlab table try: maxcols = max([len(row) for row in data] or [0]) except ValueError: log.warn(c.warning("<table> rows seem to be inconsistent")) maxcols = [0] for i, row in enumerate(data): data[i] += [''] * (maxcols - len(row)) cols_with_no_width = [ tup for tup in enumerate(tdata.colw) if tup[1] is None or tup[1] == 0.0 ] if cols_with_no_width: # any col width not defined log.debug(list(enumerate(tdata.colw))) fair_division = str(100 / float(len(cols_with_no_width))) + '%' log.debug("Fair division: {}".format(fair_division)) for i, _ in cols_with_no_width: log.debug("Setting {} to {}".format(i, fair_division)) tdata.colw[i] = fair_division log.debug("Col widths: {}".format(list(tdata.colw))) if tdata.data: # log.debug("Table styles %r", tdata.styles) t = PmlTable( data, colWidths=tdata.colw, rowHeights=tdata.rowh, # totalWidth = tdata.width, splitByRow=1, # repeatCols = 1, repeatRows=tdata.repeat, hAlign=tdata.align, vAlign='TOP', style=TableStyle(tdata.styles)) t.totalWidth = _width(tdata.width) t.spaceBefore = c.frag.spaceBefore t.spaceAfter = c.frag.spaceAfter # XXX Maybe we need to copy some more properties? t.keepWithNext = c.frag.keepWithNext # t.hAlign = tdata.align c.addStory(t) else: log.warn(c.warning("<table> is empty")) # Cleanup and re-swap table data c.clearFrag() c.tableData, self.tableData = self.tableData, None
def EgresoPDF(request): response = HttpResponse(content_type='application/pdf') buffer = BytesIO() pdf = canvas.Canvas(buffer) doc = SimpleDocTemplate( buffer, pagesizes=letter, rightMargin=30, leftMargin=30, topMargin=176.9, bottomMargin=50, paginate_by=0, ) ta_r = ParagraphStyle( 'parrafos', alignment=TA_RIGHT, fontSize=13, fontName="Helvetica-Bold", ) persona = [] styles = getSampleStyleSheet() # TABLA NUMERO 1 count = 0 data = [] filtro = Egreso.objects.all().order_by('-fecha', '-id') if (request.GET['tipo']): tipo = request.GET['tipo'] c = filtro.filter(concepto=tipo) else: c = filtro if c: for i in c: count = count + 1 data.append([ count, i.fecha, str(i.monto) + ' bs.', i.descripcion, i.concepto ]) else: return redirect('diezmo:egresos') x = Table(data, colWidths=[35, 85, 80, 200, 80]) x.setStyle( TableStyle([ ('GRID', (0, 0), (12, -1), 1, colors.black), ('ALIGN', (0, 0), (3, -1), 'CENTER'), ('FONTSIZE', (0, 0), (4, -1), 8), ])) persona.append(x) doc.build(persona, onFirstPage=HeaderFooterEgreso, onLaterPages=HeaderFooterEgreso, canvasmaker=NumberedCanvas) response.write(buffer.getvalue()) buffer.close() return response
def makePagePenguji(contain, styles, judul, namaMhs, npmMhs, program, tglSidang, penPendamping, nikPenPendamping, penUtama, nikPenUtama, koor, nikKoor, listTTD): text = f'<font size="16"><b>LEMBAR PENGESAHAN</b></font>' contain.append(Paragraph(text, styles["Center"])) contain.append(Spacer(1, 1*cm)) text = f'<font size="14"><b>{judul}</b></font>' contain.append(Paragraph(text, styles["CenterSpacing"])) contain.append(Spacer(1, .7*cm)) data = [[namaMhs, npmMhs], ] table = Table(data, [8.5*cm, 4*cm], len(data)*[.8*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('ALIGN', (0,0), (0,0), 'CENTER'), ('ALIGN', (-1,-1), (-1,-1), 'LEFT'), ])) contain.append(table) contain.append(Spacer(1, .4*cm)) path = './revisisidang/qrcodepengesahan/' data = [[Paragraph(f'<font size="12">Laporan Program {program} ini telah diperiksa, disetujui dan disidangkan<br/>Di Bandung, {tglSidang}<br/>Oleh :</font>', styles["CenterSpacing"])], ['Penguji Pendamping', '', 'Penguji Utama'], [Image(f'{path}{listTTD[3]}.png', 4 * cm, 4 * cm), '', Image(f'{path}{listTTD[2]}.png', 4 * cm, 4 * cm)], [Paragraph(f'<font size="12"><u>{penUtama}</u><br/>NIK. {nikPenUtama}</font>', styles["CenterSpacing"]), '',Paragraph(f'<font size="12"><u>{penPendamping}</u><br/>NIK. {nikPenPendamping}</font>', styles["CenterSpacing"])], [Paragraph(f'<font size="12">Menyetujui,<br/>Koordinator {program}</font>', styles["CenterSpacing"])], [Image(f'{path}{listTTD[4]}.png', 4 * cm, 4 * cm)], [Paragraph(f'<font size="12"><u>{koor}</u><br/>NIK. {nikKoor}</font>', styles["CenterSpacing"])], ] table = Table(data, [6.7*cm, .2*cm, 6.7*cm], [2*cm,.6*cm,4.1*cm,2*cm,1.2*cm,4.1*cm,1.4*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('VALIGN',(0,0),(-1,-1),'TOP'), ('SPAN', (0, 0), (2, 0)), ('SPAN', (0, 4), (2,4)), ('SPAN', (0, 5), (2,5)), ('SPAN', (0, 6), (2,6)), # ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), # ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) contain.append(table)
def createAbsensiPage(contain, styles, namaDosen, prodi, kelas, listMahasiswa, namaDeputi, namaKaprodi, qrDeputi, qrKaprodi, qrDosen): text = '<font size="14"><b>ABSENSI PERWALIAN</b></font>' contain.append(Paragraph(text, styles["Center"])) contain.append(Spacer(1, 1.5*cm)) data = [['NAMA DOSEN', ':', namaDosen], ['PROGRAM STUDI', ':', prodi], ['KELAS', ':', kelas], ] table = Table(data, [5*cm, .5*cm, 10.5*cm], len(data)*[.6*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ])) contain.append(table) contain.append(Spacer(1, .7*cm)) data = [[Paragraph('<font size="12"><b>No</b></font>', styles["Center"]), Paragraph('<font size="12"><b>Nama Mahasiswa</b></font>', styles["Center"]), Paragraph('<font size="12"><b>NPM</b></font>', styles["Center"]), Paragraph('<font size="12"><b>No Handphone<br/>E-mail</b></font>', styles["Center"]), Paragraph('<font size="12"><b>Tanda<br/>Tangan</b></font>', styles["Center"])]] data.extend(listMahasiswa) table = Table(data, [1*cm, 6*cm, 2*cm, 4.5*cm, 2*cm], len(data)*[1.5*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('ALIGN',(0,1),(-1,-1),'CENTER'), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 1, colors.black), ('BOX', (0,0), (-1,-1), 1, colors.black), ])) contain.append(table) contain.append(Spacer(1, .7*cm)) data = [ [Paragraph('<font size="12"><b>Dosen Wali,</b></font>', styles["Center"]), Paragraph('<font size="12"><b>Ketua Prodi,</b></font>', styles["Center"]), Paragraph('<font size="12"><b>Deputi Akademik,</b></font>', styles["Center"])], [Image(qrDeputi, 4*cm, 4*cm), Image(qrKaprodi, 4*cm, 4*cm), Image(qrDosen, 4*cm, 4*cm)], [Paragraph(f'<font size="12"><u>{namaDosen}</u></font>', styles["Center"]), Paragraph(f'<font size="12"><u>{namaKaprodi}</u></font>', styles["Center"]), Paragraph(f'<font size="12"><u>{namaDeputi}</u></font>', styles["Center"])], ] table = Table(data, [6.8*cm, 6.8*cm, 6.8*cm], [.6*cm, 4.5*cm, 1*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('ALIGN',(0,1),(-1,-1),'CENTER'), ])) contain.append(table)
def cabecera(self, request, fecha, pdf): usuario = request.user.get_full_name() #Utilizamos el archivo logo_django.png que está guardado en la carpeta media/imagenes archivo_imagen = settings.MEDIA_ROOT + 'Logo.png' #Definimos el tamaño de la imagen a cargar y las coordenadas correspondientes pdf.drawImage(archivo_imagen, 30, 700, 120, 90, preserveAspectRatio=True ) pdf.setFont("Helvetica", 9) # pdf.drawString(550, 770, u"%s" %time.strftime("%x")) pdf.drawString(500, 760, u"Fecha: %s/%s/%s" %(fecha.day, fecha.month, fecha.year) ) pdf.drawString(500, 750, u"Hora: %s:%s" %(fecha.hour, fecha.minute) ) #Creamos una tupla de encabezados para neustra tabla encabezados = ['Estado de Cuenta'.upper()] #Creamos una lista de tuplas que van a contener a las personas detalles = [ ('%s, Edificio %s, Apartamento %s' %(usuario, p.edificio, p.no_apartamento)) for p in Residente.objects.filter(id=request.user.id) ] #Establecemos el tamaño de cada una de las columnas de la tabla detalle_orden = Table([encabezados] + [detalles], rowHeights=50, colWidths=[575] ) #Aplicamos estilos a las celdas de la tabla detalle_orden.setStyle( TableStyle( [ #La primera fila(encabezados) va a estar centrada ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (0, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, -1), 12), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (0, 0), 'CENTER'), ('FONTSIZE', (0, 0), (-1, 0), 16), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ] ) ) #Establecemos el tamaño de la hoja que ocupará la tabla detalle_orden.wrapOn(pdf, 1000, 800) #Definimos la coordenada donde se dibujará la tabla detalle_orden.drawOn(pdf, 15, 660)
def get_pdf_file(data_to_download): """Get PDF File.""" players = Player.objects.all().order_by('ranking') player_list = [] for each_player in players: player_list.append([each_player.ranking, each_player.first_name, each_player.last_name, each_player.email, each_player.contact_number]) doc = io.BytesIO() pdf = SimpleDocTemplate(doc, pagesize=A4) # Header Table with the logos franklin_logo = os.path.join(settings.MEDIA_ROOT, 'images/franklin_logo.png') squash_auckland_logo = os.path.join(settings.MEDIA_ROOT, 'images/squash_auckland.png') franklin_logo_image = Image(franklin_logo) franklin_logo_image.drawWidth = 100 franklin_logo_image.drawHeight = 55 squash_auckland_logo_image = Image(squash_auckland_logo) squash_auckland_logo_image.drawWidth = 100 squash_auckland_logo_image.drawHeight = 30 document_title = "Franklin Squash Club Ladder" header_table = Table([[franklin_logo_image, document_title, squash_auckland_logo_image]]) # Header Table Style header_table_style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (1, 0), (1, 0), colors.HexColor('#CD6620')), ('FONTSIZE', (1, 0), (1, 0), 20), ('FONTNAME', (1, 0), (1, 0), 'Times-BoldItalic') ]) header_table.setStyle(header_table_style) spacer = Spacer(1, 10) # List with all of the players. if data_to_download == 'player_list': data = Table(get_player_list()) else: data = None page_elements = [header_table, spacer, data] pdf.build(page_elements) doc.seek(0) return doc
def _create_table(self, d, row_num, col_widths): HEADER_BACKGROUND_COLOR = colors.HexColor('#48ACC6') EVEN_BACKGROUND_COLOR = colors.HexColor('#DAEEF3') ODD_BACKGROUND_COLOR = colors.white table = Table(d, colWidths=col_widths) table.setStyle( TableStyle([ # 背景色 # 先頭行(ヘッダ) # 2ECCFA ('BACKGROUND', (0, 0), (-1, 0), HEADER_BACKGROUND_COLOR), # 表で使うフォントとそのサイズを設定 ('FONT', (0, 0), (-1, -1), self.FONT_MEIRYO, 9), # 先頭行だけbold ('FONT', (0, 0), (-1, 0), self.FONT_MEIRYO_BOLD, 9), # 先頭行は白 ('TEXTCOLOR', (0, 0), (-1, 0), colors.white), # 罫線 ('BOX', (0, 0), (-1, -1), 0.10, HEADER_BACKGROUND_COLOR), ('INNERGRID', (0, 0), (-1, -1), 0.10, HEADER_BACKGROUND_COLOR), # セルの縦文字位置を、TOPにする ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) # stripe for i in range(row_num): if (i % 2) == 0: table.setStyle( TableStyle([ ('BACKGROUND', (0, i + 1), (-1, i + 1), EVEN_BACKGROUND_COLOR), ('TEXTCOLOR', (0, i + 1), (-1, i + 1), colors.black), ])) else: table.setStyle( TableStyle([ ('BACKGROUND', (0, i + 1), (-1, i + 1), ODD_BACKGROUND_COLOR), ('TEXTCOLOR', (0, i + 1), (-1, i + 1), colors.black), ])) return table
def create_right_align_header(date, x_position=230, additional_data=None): date = add_new_line_to_string_at_index(date, 10) right_table_data = [ [ Paragraph("Datum", style=size_nine_helvetica_leading_10), Paragraph(date, style=size_nine_helvetica_leading_10), ], ] if additional_data is not None: right_table_data.extend(additional_data) right_table = Table(data=right_table_data, colWidths=[80, 100]) right_table.setStyle( TableStyle([ ('LEFTPADDING', (0, 0), (-1, -1), 0), ('VALIGN', (0, 0), (-1, -1), "TOP"), ('TOPPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 1), ])) data = [ ["", right_table], ] table = Table(data, splitByRow=True, colWidths=[x_position, 100], spaceAfter=30, spaceBefore=50) table.setStyle( TableStyle([ ('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 15), ('VALIGN', (0, 0), (-1, -1), "TOP"), ])) return [table]
def pdf_testPlatypus(self, fpath, txt, pkg=None, tbl=None, **kwargs): self.app.setThermo('build_pdf', 0, 'Preparo elaborazione', 10, command='init') PAGE_HEIGHT = A4[1]; PAGE_WIDTH = A4[0] styles = getSampleStyleSheet() def myLaterPages(canvas, doc): canvas.saveState() canvas.setFont('Times-Roman', 9) canvas.drawString(cm, 2 * cm, "Page %d" % (doc.page)) canvas.restoreState() doc = SimpleDocTemplate(fpath) Story = [Spacer(1, 4 * cm)] style = styles["Normal"] colWidths = (3 * cm, 1 * cm, 1 * cm, 4 * cm, 5 * cm) tstyle = TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), #('FONTSIZE', (0,0), (-1,-1), 7) ]) packages = [o for p, o in self.db.packages.items() if not pkg or p == pkg] self.app.setThermo('build_pdf', maximum_1=len(packages) + 1) for i, pobj in enumerate(packages): tables = [o for t, o in pobj.tables.items() if not tbl or t == tbl] self.app.setThermo('build_pdf', i, pobj.name, progress_2=0, message_2='', maximum_2=len(tables)) for k, tobj in enumerate(tables): if self.app.setThermo('build_pdf', progress_2=k, message_2=tobj.fullname) == 'stop': self.app.setThermo('build_pdf', command='stopped') return p = Paragraph(tobj.fullname, style) Story.append(p) Story.append(Spacer(1, 1 * cm)) data = [['Name', 'Type', 'Size', 'Name Long', 'Relations']] for cobj in tobj.columns.values(): rel = '' if cobj.relatedColumn(): rel = cobj.relatedColumn().fullname elif cobj.name == tobj.pkey and tobj.relatingColumns: rel = Paragraph('<br/>'.join(tobj.relatingColumns), style) data.append([cobj.name, cobj.attributes.get('dtype', ''), cobj.attributes.get('size', ''), self._(cobj.attributes.get('name_long', '')), rel]) t = Table(data, colWidths=colWidths) t.setStyle(tstyle) Story.append(t) Story.append(Spacer(1, 1 * cm)) self.app.setThermo('build_pdf', i + 1, "Impaginazione PDF", progress_2=0, message_2='', maximum_2=0) doc.build(Story, onFirstPage=myLaterPages, onLaterPages=myLaterPages) self.app.setThermo('build_pdf', command='end')
def AddStoryElement(self, element): if element.tag == "para": styleName = element.get("style", "default") style = self.paragraphStyles[styleName] element.attrib.clear() text = cElementTree.tostring(element) rotated = self._ConvertNumber(element, "rotate", 0) cls = RotatedParagraph if rotated else Paragraph para = cls(text, style) self.story.append(para) elif element.tag == "nextPage": self.story.append(PageBreak()) elif element.tag == "nextFrame": self.story.append(FrameBreak()) elif element.tag == "spacer": length = self._ConvertNumber(element, "length", 0) self.story.append(Spacer(length, length)) elif element.tag == "setNextTemplate": name = element.attrib["name"] self.story.append(NextPageTemplate(name)) elif element.tag == "blockTable": styleName = element.get("style", "default") style = self.tableStyles[styleName] if self.tableCommands: style = TableStyle(self.tableCommands, style) repeatRows = self._ConvertNumber(element, "repeatRows", 0) hAlign = element.get("hAlign", "CENTER") vAlign = element.get("vAlign", "MIDDLE") columnWidths = self._ConvertNumberList(element, "colWidths", []) pageRows = self._ConvertNumber(element, "pageRows") if not pageRows: self.story.append( LongTable(self.tableRows, columnWidths, self.tableRowHeights, style=style, hAlign=hAlign, vAlign=vAlign, repeatRows=repeatRows)) else: headerRows = self.tableRows[:repeatRows] headerRowHeights = self.tableRowHeights[:repeatRows] rows = self.tableRows[repeatRows:] rowHeights = self.tableRowHeights[repeatRows:] while rows: table = LongTable(headerRows + rows[:pageRows], columnWidths, headerRowHeights + rowHeights[:pageRows], style=style, hAlign=hAlign, vAlign=vAlign) self.story.append(table) rows = rows[pageRows:] rowHeights = rowHeights[pageRows:]
def set_common_per_page(self, canvas, doc): PAGE_WIDTH, PAGE_HEIGHT = pagesizes.A4 PDF_HEADER_FONT_SIZE = 8 canvas.saveState() # header string = self.set_header_string() canvas.setFont(self.FONT_MEIRYO, PDF_HEADER_FONT_SIZE) canvas.drawCentredString((PAGE_WIDTH / 2.0), (PAGE_HEIGHT - 20), string) # footer string = self.set_footer_string() canvas.setFont(self.FONT_MEIRYO, PDF_HEADER_FONT_SIZE) canvas.drawCentredString((PAGE_WIDTH / 2.0), 20, string) # 左上: アイコン image_path = django_settings.PDF_IMAGE_DIR + 'apple-icon-180x180.png' canvas.drawImage(image_path, 10*mm, 285*mm, width=10*mm, height=10*mm, preserveAspectRatio=True, mask=[0, 0, 0, 0, 0, 0]) # 右上: TLP表記 string = 'TLP: %s' % (self.feed.tlp.upper()) # Tableにて実装 data = [[string], ] table = Table(data) if self.feed.tlp.upper() == 'RED': color = '#FF0033' elif self.feed.tlp.upper() == 'AMBER': color = '#FFC000' elif self.feed.tlp.upper() == 'GREEN': color = '#33FF00' else: color = '#FFFFFF' table.setStyle(TableStyle([ # 背景色は黒 ('BACKGROUND', (0, 0), (-1, -1), colors.black), # テキスト色はTLPによって異なる ('TEXTCOLOR', (0, 0), (-1, -1), color), # 表で使うフォントとそのサイズを設定 ('FONT', (0, 0), (-1, -1), self.FONT_MEIRYO, 9), # ('FONT', (0, 0), (-1, -1), 'CJK', 9), # 四角に罫線を引いて、0.5の太さで、色は黒 ('BOX', (0, 0), (-1, -1), 1, colors.black), # 四角の内側に格子状の罫線を引いて、0.25の太さで、色は赤 ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), # セルの縦文字位置を、TOPにする ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) # 配置位置 table.wrapOn(canvas, 180*mm, 287*mm) table.drawOn(canvas, 180*mm, 287*mm) canvas.restoreState()
def wrap(self, availWidth, availHeight): "All table properties should be known by now." widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0, 'Placeholder for table of contents', 0)] else: _tempEntries = self._lastEntries i = 0 lastMargin = 0 tableData = [] tableStyle = [ ('VALIGN', (0, 0), (- 1, - 1), 'TOP'), ('LEFTPADDING', (0, 0), (- 1, - 1), 0), ('RIGHTPADDING', (0, 0), (- 1, - 1), 0), ('TOPPADDING', (0, 0), (- 1, - 1), 0), ('BOTTOMPADDING', (0, 0), (- 1, - 1), 0), ] for entry in _tempEntries: level, text, pageNum = entry[:3] leftColStyle = self.levelStyles[level] if i: # Not for first element tableStyle.append(( 'TOPPADDING', (0, i), (- 1, i), max(lastMargin, leftColStyle.spaceBefore))) # print leftColStyle.leftIndent lastMargin = leftColStyle.spaceAfter #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % level, parent=leftColStyle, leftIndent=0, alignment=TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(str(pageNum), rightColStyle) tableData.append([leftPara, rightPara]) i += 1 self._table = Table( tableData, colWidths=widths, style=TableStyle(tableStyle)) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return (self.width, self.height)
def add_grid_to_ticket(self, elements: list, numbers: list) -> list: t = Table( data=numbers, colWidths=len(numbers[0]) * [0.4 * inch], rowHeights=len(numbers) * [0.4 * inch], ) t.setStyle( TableStyle([ ("GRID", (0, 0), (-1, -1), 0.5, colors.black), ("ALIGN", (0, 1), (-1, -1), "CENTER"), ])) elements.append(t) return elements
def do_table_wrap(self, availWidth, availHeight): styles = getSampleStyleSheet() sN = styles['Normal'] sN.alignment = TA_CENTER data = [["" for x in range(12)] for y in range(3)] data[0][1] = Paragraph( "<br/><br/><strong>%s</strong>" % self.master.pathologist.fullname, sN) data[1][1] = Paragraph( self.master.pathologist.get_designation_display(), sN) data[2][1] = Paragraph( "PRC LIC #: %s" % self.master.pathologist.license, sN) data[0][7] = Paragraph( "<br/><br/><br/><strong>%s</strong>" % self.master.medical_technologist.fullname, sN) data[1][7] = Paragraph( self.master.medical_technologist.get_designation_display(), sN) data[2][7] = Paragraph( "PRC LIC #: %s" % self.master.medical_technologist.license, sN) w = availWidth - self.margin * 2 spacer = int(w * 0.05) remWidth = (w - (spacer * 4)) / 8 colWidths = [spacer] + \ [remWidth] * 4 + \ [spacer] * 2 + \ [remWidth] * 4 + \ [spacer] self.table = Table(data, colWidths=colWidths) self.table.setStyle( TableStyle([ # config padding ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), # lines ('LINEBELOW', (1, 0), (4, 0), 1, black), ('LINEBELOW', (7, 0), (10, 0), 1, black), # ('GRID', (0, 0), (-1, -1), 1, black), # Column 1 ('SPAN', (1, 0), (4, 0)), ('SPAN', (1, 1), (4, 1)), ('SPAN', (1, 2), (4, 2)), # Column 2 ('SPAN', (7, 0), (10, 0)), ('SPAN', (7, 1), (10, 1)), ('SPAN', (7, 2), (10, 2)), ])) self.table.canv = self.canv return self.table.wrap(availWidth, availHeight)
def _get_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))
def _get_style(self, rows): ''' set TableStyle add styles for row/col blocks style.add('SPAN', (col_s, row_s), (col_e, row_e)) also set row heights ''' _get_idxs = lambda x: self._get_idxs(rows, x) _get_se = lambda x: (x[0][0], x[-1][0]) # (col, row) style = TableStyle() title_row = 0 sample_row = 1 sample_row2 = 2 name_row = 3 unit_row = 4 style.add('GRID', (0, 0), (-1, -1), 0.25, colors.red) style.add('ALIGN', (0, unit_row), (-1, -1), 'LEFT') style.add('LEFTPADDING', (0, unit_row), (-1, -1), 1) # set style for title row if self.add_title: style.add('SPAN', (0, title_row), (-1, title_row)) style.add('LINEBELOW', (0, 0), (-1, 0), 1.5, colors.black) # set style for sample row for s, e in self._sample_summary_row1.spans: style.add('SPAN', (s, sample_row), (e, sample_row)) style.add('LINEBELOW', (s, sample_row), (e, sample_row), 1.5, colors.black) for s, e in self._sample_summary_row2.spans: style.add('SPAN', (s, sample_row2), (e, sample_row2)) # set style for name header style.add('LINEABOVE', (0, name_row), (-1, name_row), 1.5, colors.black) # set style for unit header style.add('LINEBELOW', (0, unit_row), (-1, unit_row), 1.5, colors.black) # set style for summary rows # summary_idxs = [(i, v) for i, v in enumerate(rows) # if isinstance(v, SummaryRow)] summary_idxs = _get_idxs(SummaryRow) for idx, summary in summary_idxs: style.add('LINEABOVE', (0, idx), (-1, idx), 1.5, colors.black) for si, se in summary.spans: style.add('SPAN', (si, idx), (se, idx)) analysis_idxs = _get_idxs(AnalysisRow) sidx, eidx = _get_se(analysis_idxs) # sidx, eidx = analysis_idxs[0][0], analysis_idxs[-1][0] style.add('VALIGN', (0, sidx), (-1, eidx), 'MIDDLE') style.add('ALIGN', (0, sidx), (-1, eidx), 'CENTER') for idx, _analysis in analysis_idxs: if idx % 2 == 0: style.add('BACKGROUND', (0, idx), (-1, idx), colors.lightgrey, ) # set for footnot rows footnote_idxs = _get_idxs(FootNoteRow) sidx, eidx = _get_se(footnote_idxs) style.add('VALIGN', (0, sidx), (-1, eidx), 'MIDDLE') for idx, _v in footnote_idxs: style.add('SPAN', (0, idx), (-1, idx)) # style.add('VALIGN', (1, idx), (-1, idx), 'MIDDLE') footer_idxs = _get_idxs(FooterRow) sidx, eidx = _get_se(footer_idxs) style.add('VALIGN', (0, sidx), (-1, eidx), 'MIDDLE') for idx, v in footer_idxs: for si, se in v.spans: style.add('SPAN', (si, idx), (se, idx)) return style
def build_pdf(self, response): cleaned_data = self.filterset.form.cleaned_data agrupamento = cleaned_data['agrupamento'] elements = [] #print('data ini', datetime.now()) data = self.get_data() #print('data fim', datetime.now()) style = TableStyle([ ('FONTSIZE', (0, 0), (-1, -1), 8), ('LEADING', (0, 0), (-1, -1), 7), ('GRID', (0, 0), (-1, -1), 0.1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('LEFTPADDING', (0, 0), (-1, -1), 3), ('RIGHTPADDING', (0, 0), (-1, -1), 3), ]) style.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE') #print('enumerate ini', datetime.now()) for i, value in enumerate(data): if len(value) <= 1: style.add('SPAN', (0, i), (-1, i)) if len(value) == 0: style.add('INNERGRID', (0, i), (-1, i), 0, colors.black), style.add('GRID', (0, i), (-1, i), -1, colors.white) style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black) if len(value) == 1: style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black) #print('enumerate fim', datetime.now()) # if not agrupamento or agrupamento == 'sem_agrupamento': # style.add('ALIGN', (0, 0), (0, -1), 'CENTER') #print('table ini', datetime.now()) rowHeights = 20 t = LongTable(data, rowHeights=rowHeights, splitByRow=True) t.setStyle(style) if len(t._argW) == 5: t._argW[0] = 1.8 * cm t._argW[1] = 6 * cm t._argW[2] = 6.5 * cm t._argW[3] = 9.5 * cm t._argW[4] = 2.4 * cm elif len(t._argW) == 4: t._argW[0] = 2 * cm t._argW[1] = 10 * cm t._argW[2] = 11.5 * cm t._argW[3] = 3 * cm for i, value in enumerate(data): if len(value) == 0: t._argH[i] = 7 continue for cell in value: if isinstance(cell, list): t._argH[i] = (rowHeights) * ( len(cell) - (0 if len(cell) > 1 else 0)) break elements.append(t) #print('table fim', datetime.now()) #print('build ini', datetime.now()) doc = SimpleDocTemplate( response, pagesize=landscape(A4), rightMargin=1.25 * cm, leftMargin=1.25 * cm, topMargin=1.1 * cm, bottomMargin=0.8 * cm) doc.build(elements)
def pdf(request, guid): import settings import reportlab.pdfgen.canvas from reportlab.lib import pagesizes, units, colors, utils from reportlab.platypus import Paragraph, Image from reportlab.platypus.tables import Table, TableStyle from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet from django.contrib.humanize.templatetags.humanize import intcomma company = fact.models.Slot.company() invoice = get_object_or_404(fact.models.Invoice, pk=guid) if not invoice.date_posted or not invoice.date_due: return redirect(reverse('fact.views.detailed', kwargs={'guid':guid})) response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=' + _('invoice') + '-' + invoice.id + '.pdf' p = reportlab.pdfgen.canvas.Canvas(response, pagesize=pagesizes.A4) width, height = pagesizes.A4 font = 'Helvetica' # Load options and payment text options = fact.models.Option.opt_list(request.LANGUAGE_CODE) for key, value in options.iteritems(): options['payment_text'] = options['payment_text'].replace('%' + key + '%', value) options['payment_text'] = options['payment_text'].replace('\n', '<br/>') # Right-hand stuff x = units.cm * 14; p.setFont(font + '-Bold', 18) p.drawString(x, height-(units.cm*4.5), _('Invoice %s') % invoice.id) p.setFont(font, 10) p.drawString(x, height-(units.cm*5.5), _('Invoice date: %s') % invoice.date_invoice.strftime('%d.%m.%Y')) p.drawString(x, height-(units.cm*6), _('Due date: %s') % invoice.date_due.strftime('%d.%m.%Y')) # Logo img = utils.ImageReader(settings.FACT_LOGO) iw, ih = img.getSize() aspect = ih / float(iw) img = Image(settings.FACT_LOGO, width=units.cm*4, height=units.cm*4*aspect) img.drawOn(p, x+(units.cm*1), height-(units.cm*2.25)) # Left-hand header stuff x = units.cm * 2; p.setFont(font + '-Oblique', 8) p.drawString(x, height-(units.cm*1.25), company['name']) address = company['address'].split("\n") base = 1.65 for a in address: p.drawString(x, height-(units.cm*base), a) base += 0.4 # Recipient name and address y = units.cm*4.5 base = 0.5 customer = invoice.customer p.setFont(font, 10) p.drawString(x, height-y, customer.addr_name); y += units.cm*base p.drawString(x, height-y, customer.addr_addr1); y += units.cm*base p.drawString(x, height-y, customer.addr_addr2); y += units.cm*base p.drawString(x, height-y, customer.addr_addr3); y += units.cm*base p.drawString(x, height-y, customer.addr_addr4); y += units.cm*base y += units.cm*2 # Main p.setFont(font + '-Bold', 14) p.drawString(x, height-y, _('Specification')) y += units.cm*1 p.setFont(font, 10) fmt = '{0:.2f}' # Get our invoice entries, headers, etc style = TableStyle() invoice_entries = [] headers = [_('Description'), _('Amount'), _('Type'), _('Unit price'), _('VAT'), _('Net')] style.add('FONT', (0,0), (-1,0), font + '-Bold') style.add('LINEBELOW', (0,0), (-1,0), 1, colors.black) for entry in invoice.entries: invoice_entries.append([ entry.description, intcomma(fmt.format(entry.quantity)), _(entry.action), intcomma(fmt.format(entry.unitprice)), intcomma(fmt.format(entry.tax_percent)) + '%', intcomma(fmt.format(entry.net)) ]) style.add('LINEBELOW', (0, len(invoice_entries)), (-1, len(invoice_entries)), 1, colors.black) sums = [] sums.append([_('Net'), '', '', '', '', intcomma(fmt.format(invoice.net))]) sums.append([_('VAT'), '', '', '', '', intcomma(fmt.format(invoice.tax))]) if invoice.payments.count() > 0: sums.append([_('Subtotal'), '', '', '', '', intcomma(fmt.format(invoice.gross))]) style.add('LINEBELOW', (0, len(invoice_entries)+3), (-1, len(invoice_entries)+3), 1, colors.black) for payment in invoice.payments.all(): sums.append([_('Paid %s') + payment.post_date.strftime('%d.%m.%Y'), '', '', '', '', intcomma(fmt.format(payment.amount))]) ln = len(invoice_entries) + len(sums) style.add('LINEBELOW', (0, ln), (-1, ln), 1, colors.black) else: style.add('LINEBELOW', (0, len(invoice_entries)+2), (-1, len(invoice_entries)+2), 1, colors.black) sums.append([_('Amount due'), '', '', '', '', intcomma(fmt.format(invoice.due))]) ln = len(invoice_entries) + len(sums) style.add('BACKGROUND', (0, ln), (-1, ln), colors.wheat) style.add('FONT', (0, ln), (-1, ln), font + '-Bold') style.add('LINEBELOW', (0, ln), (-1, ln), 2, colors.black) # Draw the table t = Table([headers] + invoice_entries + sums, ([units.cm*6.5, units.cm*1.75, units.cm*2, units.cm*2.5, units.cm*2, units.cm*2.25]) ) t.setStyle(style) w, h = t.wrapOn(p, units.cm*19, units.cm*8) y += h t.drawOn(p, x, height-y) # Bank account number stylesheet = getSampleStyleSheet() if invoice.notes: txt = invoice.notes + '<br/><br/>' else: txt = '' txt += options['payment_text'] pr = Paragraph(txt, stylesheet['BodyText']) w, h = pr.wrapOn(p, units.cm*17, units.cm*6) y += pr.height + (units.cm*1) pr.drawOn(p, x, height-y) # Footer stuff p.setFont(font + '-BoldOblique', 8) p.drawString(x, units.cm*2.8, company['name']) p.setFont(font + '-Oblique', 8) p.drawString(x, units.cm*2.4, address[0]) p.drawString(x, units.cm*2, address[1]) p.drawString(units.cm*8, units.cm*2.4, 'Web: ' + company['url']) p.drawString(units.cm*8, units.cm*2, 'E-post: ' + company['email']) p.drawString(units.cm*14, units.cm*2.4, 'Telefon: ' + company['phone']) p.drawString(units.cm*14, units.cm*2, 'Org.nr: ' + company['id']) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response