def append_to_pdf(self, story): data = [['#', _('Title'), _('Last Name'), _('First Name'), _('Structure level'), _('Group'), _('Committee')]] if config['participant_sort_users_by_first_name']: sort = 'first_name' else: sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): counter += 1 groups = '' for group in user.groups.all(): if group.pk != 2: groups += "%s<br/>" % unicode(_(group.name)) data.append([ counter, Paragraph(user.title, stylesheet['Tablecell']), Paragraph(user.last_name, stylesheet['Tablecell']), Paragraph(user.first_name, stylesheet['Tablecell']), Paragraph(user.structure_level, stylesheet['Tablecell']), Paragraph(groups, stylesheet['Tablecell']), Paragraph(user.committee, stylesheet['Tablecell'])]) t = LongTable(data, style=[ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm story.append(t)
def ncc_report(story, checks_list): loggerObj.LogMessage("info",file_name + " :: ncc_report() Enter") property_lenght = len(checks_list) checks_property_data = [['Properties Tested', 'Status']] for checks in checks_list: status = checks.get('Status') msg = checks.get('Name') checks_property_data.append([Paragraph(msg, NormalMessageStyle), Paragraph(status, getFontColor(status))]) checks_property_table = LongTable(checks_property_data, colWidths=[6 * inch, 0.75 * inch]) # style sheet for table checks_property_table.setStyle(TableStyle([('BACKGROUND', (0, 0), (1, 0), colors.fidlightblue), ('ALIGN', (0, 0), (1, property_lenght), 'LEFT'), ('INNERGRID', (0, 0), (2, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (1, property_lenght), 0.25, colors.black), ('TEXTFONT', (0, 0), (1, 0), 'Times-Roman'), ('FONTSIZE', (0, 0), (1, 0), 10)])) # story.append(checks_para_table) story.append(Spacer(1, 0.05 * inch)) story.append(checks_property_table) story.append(Spacer(1, 0.3 * inch)) loggerObj.LogMessage("info",file_name + " :: vc_report() Exit")
def users_to_pdf(pdf): """ Create a list of all users as PDF """ data = [['#', _('Title'), _('Last Name'), _('First Name'), _('Structure level'), _('Group')]] if config['users_sort_users_by_first_name']: sort = 'first_name' else: sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): counter += 1 groups = '' for group in user.groups.all(): if group.pk != 2: groups += "%s<br/>" % _(group.name) data.append([ counter, Paragraph(user.title, stylesheet['Tablecell']), Paragraph(user.last_name, stylesheet['Tablecell']), Paragraph(user.first_name, stylesheet['Tablecell']), Paragraph(user.structure_level, stylesheet['Tablecell']), Paragraph(groups, stylesheet['Tablecell'])]) t = LongTable(data, style=[ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm pdf.append(t) return pdf
def append_to_pdf(self, story): data = [[ '#', _('Last Name'), _('First Name'), _('Group'), _('Type'), _('Committee') ]] if config['participant_sort_users_by_first_name']: sort = 'first_name' else: sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): counter += 1 data.append([ counter, Paragraph(user.last_name, stylesheet['Tablecell']), Paragraph(user.first_name, stylesheet['Tablecell']), Paragraph(user.structure_level, stylesheet['Tablecell']), Paragraph(user.get_type_display(), stylesheet['Tablecell']), Paragraph(user.committee, stylesheet['Tablecell']) ]) t = LongTable(data, style=[('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm story.append(t)
def call_table(working_dir): query = DataExtrator(working_dir) data_tmp = list(query.get_call_hisotry()) data = [['Row ID', 'Contact Name', 'Number', 'Date', 'Type', 'Duration\n in seconds']] for i in data_tmp: tmp = [] for j in i: tmp.append(str(j)) data.append(tmp) tableStyle = [ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BACKGROUND', (0, 0), (5, 0), colors.lightgreen) ] styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.wordWrap = 'CJK' data2 = [[Paragraph(cell, styleN) for cell in row] for row in data] colwidths = [2*cm, 3*cm, 3*cm, 4*cm, 3*cm, 2.2*cm] call_table = LongTable(data2, colWidths=colwidths, repeatRows=1) call_table.setStyle(TableStyle(tableStyle)) return call_table
def sms_table(working_dir): query = DataExtrator(working_dir) data_tmp = list(query.get_sms_list()) data = [['Message ID', 'Thread ID', 'Receipent', 'Date', 'Body', 'Sent/revceived']] for i in data_tmp: tmp = [] for j in i: tmp.append(str(j)) data.append(tmp) tableStyle = [ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BACKGROUND', (0, 0), (5, 0), colors.lightgreen) ] styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.wordWrap = 'CJK' data2 = [[Paragraph(cell, styleN) for cell in row] for row in data] colwidths = [2*cm, 2*cm, 3*cm, 4*cm, 6*cm, 2*cm] t = LongTable(data2, colWidths=colwidths, repeatRows=1) t.setStyle(TableStyle(tableStyle)) return t
def add_status_colour(table: LongTable, table_data: List[Tuple], status_index: int) -> None: """ Add colour co-ordinated status tags """ for x in range(1, len(table_data) - 2): if table_data[x][status_index] == "N": bc = colors.orangered elif table_data[x][status_index] == "P": bc = colors.cornflowerblue elif table_data[x][status_index] == "F": bc = colors.lightgreen elif table_data[x][status_index] == "G": bc = colors.darkgreen elif table_data[x][status_index] == "PG": bc = colors.purple else: bc = colors.burlywood ts = TableStyle([('BACKGROUND', [status_index, x], [status_index, x], bc), ('TEXTCOLOR', [status_index, x], [status_index, x], colors.black)]) table.setStyle(ts)
def create(self, destination): doc = SimpleDocTemplate(destination, pagesize=A4) story = [] styles = self.para_style() comm_style = styles['CommunityName'] h5 = self.style['Heading5'] story.append(Paragraph("Community Accrual Report", styles['ReportName'])) container_data = [[Paragraph(self.community1, comm_style), Paragraph(self.community2, comm_style)], [Paragraph(self.date_range, h5), Paragraph(self.date_range, h5)]] report_style = self.inner_style() tables_data = [] for community_data in [self.data1, self.data2]: table_data, added_styles = self.community_table_data(community_data) tables_data.append(table_data) tables = [] report_style.extend(added_styles) for report_data in tables_data: table = LongTable(report_data, repeatRows=1) table.setStyle(report_style) tables.append(table) container_data.append(tables) container_table = Table(container_data, 2 * [3.6 * inch]) container_table.setStyle(TableStyle([ ('LINEABOVE', (0, 0), (-1, 0), 0.5, colors.HexColor('#ed4694')), ])) story.append(container_table) doc.build(story)
def append_to_pdf(self, story): data = [['#', _('Last Name'), _('First Name'), _('Group'), _('Type'), _('Committee')]] if config['participant_sort_users_by_first_name']: sort = 'first_name' else: sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): counter += 1 data.append([ counter, Paragraph(user.last_name, stylesheet['Tablecell']), Paragraph(user.first_name, stylesheet['Tablecell']), Paragraph(user.structure_level, stylesheet['Tablecell']), Paragraph(user.get_type_display(), stylesheet['Tablecell']), Paragraph(user.committee, stylesheet['Tablecell'])]) t = LongTable(data, style=[ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm story.append(t)
def make_rl_story( me, style_commands, table_data, col_widths =None, row_heights =None, hAlign='CENTER'): if not table_data: return [] # unless you rely on how reportlab would handle it table = LongTable( table_data, repeatRows=1, colWidths=col_widths, rowHeights=row_heights) table.hAlign = hAlign style = TableStyle( style_commands) res = [] if 0*'DEBUG STYLE': for cmd in style_commands: print cmd if me.overwrite_fonts_in_style: font_name='ArialMT' register_font(font_name) style.add( 'FONTNAME', (0,0), (-1,-1), font_name, 14) if 0*'DEBUG CELLS': style.add( 'INNERGRID', (0,0), (-1,-1), 0.25, 'BLACK') style.add( 'BOX', (0,0), (-1,-1), 0.25, 'BLACK') style.add( 'TOPPADDING', (0,0), (-1,-1), 0) style.add( 'LEFTPADDING', (0,0), (-1,-1), 0) style.add( 'RIGHTPADDING', (0,0), (-1,-1), 0) style.add( 'BOTTOMPADDING', (0,0), (-1,-1), 0) from reportlab.platypus.flowables import Spacer #res.insert( 0, Spacer( width=0, height=3)) table.setStyle( style) res.append( table) return res
def build_tabla_contenido(data): """ Construye la tabla del contenido del facturaVenta. Los datos deben venir en listas. Cada línea de la tabla, una tupla o lista con el código, descripción, cantidad, precio unitario (con dto. si lo lleva e IVA). El precio y cantidad deben ser flotantes para poder calcular el subtotal. """ estilo_cabecera_tabla = ParagraphStyle("Cabecera tabla", parent=estilos["Heading3"]) estilo_cabecera_tabla.fontName = "Times-Bold" estilo_cabecera_tabla.alignment = enums.TA_CENTER estilo_numeros_tabla = ParagraphStyle("Números tabla", parent=estilos["Normal"]) estilo_numeros_tabla.alignment = enums.TA_RIGHT datos = [(Paragraph(escribe("Código"), estilo_cabecera_tabla), Paragraph(escribe("Descripción"), estilo_cabecera_tabla), Paragraph("Cantidad", estilo_cabecera_tabla), Paragraph("Precio/U", estilo_cabecera_tabla), Paragraph("Total c/IVA", estilo_cabecera_tabla)) ] for d in data: fila = (escribe(d[0]), Paragraph(escribe(d[1]),estilos["Normal"]), Paragraph(escribe(utils.float2str(d[2])),estilo_numeros_tabla), Paragraph(escribe(utils.float2str(d[3])),estilo_numeros_tabla), Paragraph(escribe(utils.float2str(d[2] * d[3])), estilo_numeros_tabla) ) datos.append(fila) tabla = LongTable(datos, colWidths = (PAGE_WIDTH * 0.13, PAGE_WIDTH * 0.43, PAGE_WIDTH * 0.10, PAGE_WIDTH * 0.10, PAGE_WIDTH * 0.14), repeatRows = 1) tabla.setStyle(TableStyle([ ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey), ("LINEBEFORE", (0, 0), (-1, 0), 0.25, colors.black), ("LINEBELOW", (0, 0), (-1, 0), 1.0, colors.black), ("LINEBELOW", (0, "splitlast"), (-1, "splitlast"), 1.0, colors.black), #("BOX", (0, 0), (-1, -1), 1.0, colors.black), ("LINEABOVE", (0, 0), (-1, 0), 1.0, colors.black), ("LINEBEFORE", (0, 0), (0, -1), 1.0, colors.black), ("LINEAFTER", (-1, 0), (-1, -1), 1.0, colors.black), #("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ("VALIGN", (0, 0), (-1, 0), "CENTER"), ("VALIGN", (0, 0), (0, -1), "TOP"), ("ALIGN", (0, 0), (-1, 0), "CENTER"), ("ALIGN", (-3, 1), (-1, -1), "RIGHT"), #("ALIGN", (0, 1), (0, -1), "DECIMAL"), <- No puedo cambiar # el pivotChar de "." a ",". No me vale. ("ALIGN", (-1, 1), (-1, -1), "CENTER"), ("ALIGN", (0, 1), (0, -1), "CENTER"), #("RIGHTPADDING", (0, 1), (0, -1), 0.75 * cm), ])) return tabla
def make_last_row_bold(table: LongTable, len_data: int): """ Very simple to understand dude.... """ table_style = TableStyle([('FONTNAME', (0, len_data - 1), (-1, len_data - 1), 'Courier-Bold'), ('BACKGROUND', (0, len_data - 1), (-1, len_data - 1), colors.sandybrown)]) table.setStyle(table_style)
def add_table_border(table: LongTable) -> None: """ Add border to a given table """ # use ('BOX', (0, 0), (-1, -1), 2, colors.black) to make a box around the cells # use ('LINEBEFORE', (2, 1), (2, -1), 2, colors.red) to make a vertical line before cell # in the same way LINEABOVE, LINEBELOW, LINEAFTER can be used ts = TableStyle([('GRID', (0, 0), (-1, -1), 2, colors.black)]) table.setStyle(ts)
def add_footer(table: LongTable, len_data: int): """ Adding Footers to the table """ table_style = TableStyle([('FONTNAME', (0, len_data - 2), (-1, len_data - 1), 'Courier-Bold'), ('BACKGROUND', (0, len_data - 2), (-1, len_data - 1), colors.sandybrown)]) table.setStyle(table_style)
def change_cell_color(table: LongTable, x: int, y: int, color: str) -> None: """ Change the color of the cell in long table """ if color == "green": color = colors.lightgreen elif color == "red": color = colors.orangered ts = TableStyle([('BACKGROUND', [x, y], [x, y], color)]) table.setStyle(ts)
def view_report(story, checks_list): loggerObj.LogMessage("info",file_name + " :: view_report() Enter") count = 0 for checks in checks_list: count += 1 categoryList="" story.append(Spacer(1, 0.01 * inch)) categoryListLen = len(checks.get('Category')) for category in checks.get('Category'): categoryList += category if(categoryListLen > 1): categoryList += "," categoryListLen = categoryListLen - 1 else : continue checks_data = [[str(count) + ". Check: " + checks.get('Name'), " Category: "+ categoryList]] checks_para_table = Table(checks_data, hAlign='LEFT') checks_para_table.setStyle(TableStyle([('ALIGN', (0, 0), (1, 0), 'LEFT'), ('FONTSIZE', (0, 0), (1, 0), 10.50)])) checks_property_data = [['Actual Result', 'Expected Result','Check Status','Severity']] property_lenght = len(checks.get('Properties')) for properties in checks.get('Properties'): if properties is not None: xprop_actual,xprop_result, xprop_exp = properties.get('Message').split(":=") actual_result = xprop_result.split("(Expected")[0] expected_result = xprop_exp[:-1] check_status = properties.get('Status') severity_info = get_view_severity(checks.get('Name')) checks_property_data.append([Paragraph(actual_result.replace(';','<br/>'), NormalMessageStyle), Paragraph(expected_result.replace(';','<br/>'), NormalMessageStyle), Paragraph(check_status,getFontColor(check_status)), Paragraph(severity_info, NormalMessageStyle)]) checks_property_table = LongTable(checks_property_data, colWidths=[2.5*inch,2.75*inch,1*inch,0.75*inch]) checks_property_table.setStyle(TableStyle([('BACKGROUND', (0, 0), (3, 0), colors.fidlightblue), ('ALIGN', (0, 0), (3, property_lenght), 'LEFT'), ('INNERGRID', (0, 0), (3, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (1, property_lenght), 0.25, colors.black), ('TEXTFONT', (0, 0), (3, 0), 'Times-Roman'), ('FONTSIZE', (0, 0), (3, 0), 10)])) story.append(checks_para_table) story.append(Spacer(1, 0.05 * inch)) story.append(checks_property_table) story.append(Spacer(1, 0.3 * inch)) loggerObj.LogMessage("info",file_name + " :: view_report() Exit")
def add_alt_color(table: LongTable, len_data: int) -> None: """ Give alternate colour to consecutive rows """ # Alternate Colors for x in range(1, len_data): if x % 2 == 0: bc = colors.burlywood else: bc = colors.beige ts = TableStyle([('BACKGROUND', [0, x], [-1, x], bc)]) table.setStyle(ts)
def add_padded_header_footer_columns(table: LongTable, len_data: int) -> None: """ Have bigger padded column Headers """ table_style = TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.wheat), ('TEXTCOLOR', (0, 0), (-1, 0), colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Courier-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 10), ('BOTTOMPADDING', (0, 0), (-1, 0), 10), ('BACKGROUND', (0, 1), (-1, 0), colors.beige)]) table.setStyle(table_style)
def childreport(request, children, style_sheet=None): """ Takes a list of children and prints them out 4 at a time """ doct = doctemplate.SimpleDocTemplate(os.path.join(settings.TMP_DIR, 'child_report.pdf'), pagesize=A4) style = GRID_STYLE style.add(*('VALIGN', (0, 0), (-1, -1), 'MIDDLE')) style.add(*('LEFTPADDING', (0, 0), (-1, -1), 15)) style.add(*('RIGHTPADDING', (0, 0), (-1, -1), 15)) children = [ii for ii in children] num_pages = ceil(len(children) / 4.0) data = [] page_flowables = [] for ii in range(len(children)): data.append(child_report_data(children[ii], style_sheet=style_sheet)) col_table = lambda x: LongTable(x, colWidths=[100, 150], style=style) for ii in range(int(num_pages)): try: col11 = col_table(data[4 * ii]) except IndexError: col11 = Spacer(2, 2) try: col12 = col_table(data[4 * ii + 1]) except IndexError: col12 = Spacer(2, 2) try: col21 = col_table(data[4 * ii + 2]) except IndexError: col21 = Spacer(2, 2) try: col22 = col_table(data[4 * ii + 3]) except IndexError: col22 = Spacer(2, 2) page_table = LongTable([ [col11, Spacer(2, 0), col12], [col21, Spacer(2, 0), col22], ]) page_flowables.append(page_table) doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Child report"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=child_report.pdf" return response
def test(): doc = BaseDocTemplate("question.pdf", pagesize=A4, rightMargin=72, leftMargin=72, topMargin=50, bottomMargin=80, showBoundary=False) elements = [] data = [ ['A', 'B', 'C', '天津市西青区南开和平红桥北辰天津站摩天轮', 'D', 'OBJECTID', 'DYBH'], ['00', '0dddddddddddddddddddddddddddddddddddd1', '02', 'fff', '04'], ['10', '11', '12', 'dfg', '14'], [ '20', '21', '22', 'ddddddddddddddddddddddddddddddddddddddddddddddddddddddd23', '24' ], ] tableStyle = [ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ] styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.wordWrap = 'CJK' data2 = [[Paragraph(cell, styleN) for cell in row] for row in data] frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal') reprFrame(frame) colwidths = [frame._width / 5. for i in range(7)] t = LongTable(data2, colWidths=colwidths) t.setStyle(TableStyle(tableStyle)) elements.append(t) template = PageTemplate(id='longtable', frames=frame) doc.addPageTemplates([template]) doc.build(elements)
def words_marking_by_chat(working_dir): query = DataExtrator(working_dir) analyzer = MessagesAnalyzer() analyzer.calculate_words(query.get_sms_list()) styles = getSampleStyleSheet() words_by_threads = analyzer.words_by_thread elements = [] words_by_threads_title = Paragraph('Words marking grouped by receipent', styles["Heading1"]) elements.append(words_by_threads_title) for thread in words_by_threads.keys(): chat_title = Paragraph('Conversation with - ' + thread, styles["Heading3"]) elements.append(chat_title) data_tmp = words_by_threads[thread] data_tmp = sorted(data_tmp.items(), key=lambda x: x[1], reverse=True) data = [['Word', 'Times repeated']] for i in data_tmp: tmp = [] for j in i: tmp.append(str(j)) data.append(tmp) tableStyle = [ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BACKGROUND', (0, 0), (5, 0), colors.lightgreen) ] styleN = styles['Normal'] styleN.wordWrap = 'CJK' data2 = [[Paragraph(cell, styleN) for cell in row] for row in data] colwidths = [3*cm, 1.85*cm] tableWordsByThread = LongTable(data2, colWidths=colwidths, repeatRows=1) tableWordsByThread.setStyle(TableStyle(tableStyle)) elements.append(tableWordsByThread) return elements
def emp_report_mini(): Upload.emp_report_status.config(text='Running') try: data1 = pd.read_excel('Database/tmp_Report.xlsx') data2 = pd.read_excel('Database/Report.xlsx') cols = data1.columns data1 = data1.values.tolist() data2 = data2.values.tolist() data = [] for i in range(len(data1)): data.append(cols) data.append(data1[i]) data.append(data2[i]) data.append([]) output = OUTPUT_PATH + 'Emp_Report.pdf' elements = [] doc = SimpleDocTemplate(output, pagesize=landscape(A4)) t = LongTable(data, repeatRows=1) elements.append(t) doc.build(elements) except: Upload.emp_report_status.config(text='Error') sleep(1) Upload.emp_report_status.config(text='K')
def printstats(request, style_sheet=None): """ Prints a list of sponsors and children """ doct = doctemplate.SimpleDocTemplate(os.path.join(settings.TMP_DIR, 'proj_stats.pdf'), pagesize=A4) normal_para = lambda x: Paragraph(unicode(x), style=style_sheet["Normal"]) data = [ map(normal_para, [_("Sponsor Number"), _("Sponsor"), _("Child Number"), _("Child")]) ] sponsorships = Sponsorship.objects.filter( iscurrent=True).order_by('sponsor') for sponsorship in sponsorships: row = map(normal_para, (sponsorship.sponsor.code, u"%s %s" % (sponsorship.sponsor.fname, sponsorship.sponsor.lname), sponsorship.child.code, sponsorship.child.name)) data.append(row) table = LongTable(data, style=GRID_STYLE) page_flowables = [table] doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Statistics"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=stats.pdf" return response
def addTable(self,ndata,nkeys=None): data = [] if not nkeys: keys = self.hlib.getKeys(ndata) data.append(keys) else: keys = nkeys data.append(nkeys) for x in ndata: lister = [] for b in range(len(keys)): if keys[b] not in x: outb = None else: outb = x[keys[b]] t = Paragraph(str(outb),self.styles["Normal"]) lister.append(t) data.append(lister) tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('BOX',(0,0),(-1,-1),1,black), ('INNERGRID',(0,0),(-1,-1),1,black), ('BACKGROUND',(0,0),(-1,0),lightblue)]) t = LongTable(data,repeatRows=1) t.setStyle(tblStyle) self.story.append(t) self.story.append(CondPageBreak(6))
def create_table(table_data: List[Tuple]) -> LongTable: """ Returns a table of the input data. """ table = LongTable(table_data, spaceAfter=5, spaceBefore=5) return table
def pdf(): doc = BaseDocTemplate("Murojaatnomalar.pdf", pagesize=A4, rightMargin=12, leftMargin=5, topMargin=8, bottomMargin=15, showBoundary=False) elements = [] with sqlite3.connect('Murojaat.sqlite3') as conn: conn.row_factory = lambda cursor, row: [row[0], row[1]] c = conn.cursor() data = c.execute("select name,murojaat from murojaatlar").fetchall() data = [["Ism-Familya", "Murojaatnoma"]] + data tableStyle = [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (0, -1), "LEFT"), ('FONTSIZE', (0, 0), (-1, -1), 14), ('ALIGN', (0, 7), (0, 7), "RIGHT"), ('VALIGN', (0, 0), (-1, -1), 'TOP')] styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.wordWrap = 'CJK' data2 = [[Paragraph(cell, styleN) for cell in row] for row in data] frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height - 2 * cm, id='normal') colwidths = [frame._width / 5., 4 * frame._width / 5.] t = LongTable(data2, colWidths=colwidths) t.setStyle(TableStyle(tableStyle)) elements.append(t) template = PageTemplate(id='longtable', frames=frame) doc.addPageTemplates([template]) doc.build(elements) return open("Murojaatnomalar.pdf", 'rb')
def build_table(self): colwidths = [30, 68, 282, 60] right_align_paragraph_style = ParagraphStyle("adsadsa", alignment=TA_RIGHT, fontName="Helvetica", fontSize=9, rightIndent=17) header = [ Paragraph("<b>Pos</b>", style=size_nine_helvetica), Paragraph("<b>EAN / SKU</b>", style=size_nine_helvetica), Paragraph("<b>Bezeichnung</b>", style=size_nine_helvetica), Paragraph("<b>Menge</b>", style=right_align_paragraph_style), ] data = [] data.append(header) pos = 1 for productmission in self.mission.productmission_set.all(): data.append([ Paragraph(str(pos), style=size_nine_helvetica), Paragraph(productmission.get_ean_or_sku(), style=size_nine_helvetica), Paragraph(productmission.product.title, style=size_nine_helvetica), Paragraph(str(productmission.amount), style=right_align_paragraph_style), ], ) pos += 1 table = LongTable(data, splitByRow=True, colWidths=colwidths, repeatRows=1) table.setStyle( TableStyle([ ('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ('VALIGN', (0, 0), (-1, -1), "TOP"), ])) self.story.extend([table, mission_horizontal_line])
def users_to_pdf(pdf): """ Create a list of all users as PDF. """ data = [['#', _('Name'), _('Structure level'), _('Group')]] if config['users_sort_users_by_first_name']: sort = 'first_name' else: sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): counter += 1 groups = '' for group in user.groups.all(): if group.pk != 2: groups += "%s<br/>" % escape(_(group.name)) if sort == 'last_name': name = "%s" % escape(user.last_name) if user.first_name: name = "%s, %s" % (name, escape(user.first_name)) else: name = "%s %s" % (escape(user.first_name), escape(user.last_name)) if user.title: name = "%s %s" % (user.title, name) if user.number: name = "%s<br/>%s" % (name, user.number) data.append([ counter, Paragraph(name, stylesheet['Tablecell']), Paragraph(escape(user.structure_level), stylesheet['Tablecell']), Paragraph(groups, stylesheet['Tablecell']) ]) t = LongTable(data, style=[('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm pdf.append(t) return pdf
def add_days_colour(table: LongTable, table_data: List[Tuple]) -> None: """ Add colour to the boxes on the basis of the number of days for pending payments """ for elements in range(1, len(table_data) - 1): if elements % 3 == 1: bc = colors.lightgreen elif elements % 3 == 2: bc = colors.yellow else: bc = colors.orangered ts = TableStyle([('BACKGROUND', [1, elements], [3, elements], bc), ('TEXTCOLOR', [1, elements], [3, elements], colors.black)]) table.setStyle(ts)
def temp_f(data, y): cols = data.columns data = data.values.tolist() data.insert(0, cols) output = OUTPUT_PATH + y + '.pdf' elements = [] doc = SimpleDocTemplate(output, pagesize=landscape(A4)) t = LongTable(data, repeatRows=1) elements.append(t) doc.build(elements)
def add_day_number_colour(table: LongTable, table_data: List[Tuple], day_index) -> None: """ Add colour for boxes to show the category for number of days left. """ for x in range(1, len(table_data) - 2): if table_data[x][day_index] < 40: bc = colors.lightgreen elif 40 <= table_data[x][day_index] <= 70: bc = colors.yellow elif table_data[x][day_index] > 70: bc = colors.orangered else: bc = colors.burlywood ts = TableStyle([('BACKGROUND', [day_index, x], [day_index, x], bc), ('TEXTCOLOR', [day_index, x], [day_index, x], colors.black)]) table.setStyle(ts)
def all_words_marking_table(working_dir): query = DataExtrator(working_dir) analyzer = MessagesAnalyzer() analyzer.calculate_words(query.get_sms_list()) all_words_list = analyzer.all_words #print(all_words_list) data_tmp = list(all_words_list) data = [['Word', 'Times repeated']] for i in data_tmp: tmp = [] for j in i: tmp.append(str(j)) data.append(tmp) tableStyle = [ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BACKGROUND', (0, 0), (5, 0), colors.lightgreen) ] styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.wordWrap = 'CJK' data2 = [[Paragraph(cell, styleN) for cell in row] for row in data] colwidths = [3*cm, 1.85*cm] tableWords = LongTable(data2, colWidths=colwidths, repeatRows=1) tableWords.setStyle(TableStyle(tableStyle)) return tableWords
def print_userlist(request): response = HttpResponse(mimetype='application/pdf') filename = u'filename=%s.pdf;' % _("Participant-list") response['Content-Disposition'] = filename.encode('utf-8') doc = SimpleDocTemplate(response) story = [Spacer(1,2*cm)] doc.title = _("List of Participants") # Table data= [['#', _('Last Name'), _('First Name'), _('Group'), _('Type'), _('Committee')]] sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): try: counter += 1 user.get_profile() data.append([counter, Paragraph(user.last_name, stylesheet['Tablecell']), Paragraph(user.first_name, stylesheet['Tablecell']), Paragraph(user.profile.group, stylesheet['Tablecell']), Paragraph(user.profile.get_type_display(), stylesheet['Tablecell']), Paragraph(user.profile.committee, stylesheet['Tablecell']), ]) except Profile.DoesNotExist: counter -= 1 pass t=LongTable(data, style=[ ('VALIGN',(0,0),(-1,-1), 'TOP'), ('LINEABOVE',(0,0),(-1,0),2,colors.black), ('LINEABOVE',(0,1),(-1,1),1,colors.black), ('LINEBELOW',(0,-1),(-1,-1),2,colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9))), ]) t._argW[0]=0.75*cm story.append(t) doc.build(story, onFirstPage=firstPage, onLaterPages=laterPages) return response
def full_report_mini(x, y): try: data = pd.read_excel(x) cols = data.columns data = data.values.tolist() data.insert(0, cols) output = OUTPUT_PATH + y elements = [] doc = SimpleDocTemplate(output, pagesize=landscape(A4)) t = LongTable(data, repeatRows=1) elements.append(t) doc.build(elements) except: Upload.full_report_status.config(text='Error') sleep(1) Upload.full_report_status.config(text='K')
def textAccum1(): doc = MyDocTemplate(outputfile('test_platypus_accum1.pdf'), pagesize=(8.5 * inch, 11 * inch), showBoundary=1) story = [] story.append(Paragraph("A table with 500 rows", styleSheet['BodyText'])) sty = [ ('GRID', (0, 0), (-1, -1), 1, colors.green), ('BOX', (0, 0), (-1, -1), 2, colors.red), ] data = [[ str(i + 1), Paragraph("xx " * (i % 10), styleSheet["BodyText"]), Paragraph(("blah " * (i % 40)) + PA.onDrawText(i + 1), styleSheet["BodyText"]) ] for i in range(500)] t = LongTable(data, style=sty, colWidths=[50, 100, 200]) story.append(t) doc.build(story)
def invoice_generator(request, invoice_id): """ Prints a list of sponsors and children """ out_file_path = "somefilename.pdf" invoices = models.Invoice.objects.all() doct = SimpleDocTemplate(out_file_path) style_sheet = getSampleStyleSheet() normal_para = lambda x: Paragraph(unicode(x), style=style_sheet["Normal"]) data = [ map(normal_para, [_("Invoice Number"), _("Date"), _("Total Amount"), _("Customer")]) ] for invoice in invoices: row = map(normal_para, (invoice.invoice_no, u"%s %s" % (invoice.date, invoice.customer), invoice.total_amount, invoice.management_employee)) data.append(row) table = LongTable(data, style=GRID_STYLE) page_flowables = [table] doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Invoices"))) print canvas.getpdfdata() output_file = out_file_path.split('/')[-1] print "output_file", output_file #fs = FileSystemStorage(out_file_path) with open(out_file_path) as pdf: response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=%s' % smart_str( output_file) return response return response
def sponsoraddress(request, sponsors, style_sheet=None): """ Takes a list of sponsors and prints them out 12 at a time """ doct = doctemplate.SimpleDocTemplate(os.path.join(settings.TMP_DIR, 'sponsors_list.pdf'), pagesize=A4) style = GRID_STYLE style.add(*('VALIGN', (0, 0), (-1, -1), 'MIDDLE')) style.add(*('LEFTPADDING', (0, 0), (-1, -1), 15)) style.add(*('RIGHTPADDING', (0, 0), (-1, -1), 15)) data = [] normal_para = lambda x: Paragraph(x, style=style_sheet["Normal"]) sponsors = [Sponsor.objects.get(pk=ii) for ii in sponsors] sponsor_rows = ceil(len(sponsors) / 2.0) for ii in range(int(sponsor_rows)): try: col1 = normal_para( "%s %s<br />%s<br />%s" "<br />%s<br />%s" % (sponsors[2 * ii].fname, sponsors[2 * ii].lname, sponsors[2 * ii].street, sponsors[2 * ii].postal, sponsors[2 * ii].city, sponsors[2 * ii].country)) col2 = normal_para( "%s %s<br />%s<br />%s" "<br />%s<br />%s" % (sponsors[2 * ii + 1].fname, sponsors[2 * ii + 1].lname, sponsors[2 * ii + 1].street, sponsors[2 * ii + 1].postal, sponsors[2 * ii + 1].city, sponsors[2 * ii + 1].country)) except IndexError: continue data.append([col1, col2]) sponsor_table = LongTable(data, style=style) page_flowables = [sponsor_table] doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Sponsors List"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=sponsors_list.pdf" return response
def motion_poll_to_pdf_result(pdf, poll): """ Create a PDF list of all results of a personal voting. """ keypad_data_list = poll.keypad_data_list.select_related('keypad__user').order_by('serial_number', 'keypad') if (not poll.has_votes() or ( not keypad_data_list.exclude(keypad__user__exact=None).exists() and not keypad_data_list.exclude(serial_number__exact=None).exists())): raise Http404 identifier = '' if poll.motion.identifier: identifier = ' %s' % poll.motion.identifier pdf.append(Spacer(0, -1.5 * cm)) pdf.append(Paragraph('%s%s: %s' % (_('Motion'), identifier, poll.motion.title), stylesheet['Heading3'])) # total result option = poll.get_options()[0] totaldata = [] totaldata.append([ Paragraph(_('Yes'), stylesheet['Tablecell']), Paragraph(str(option['Yes']), stylesheet['Tablecell'])]) totaldata.append([ Paragraph(_('No'), stylesheet['Tablecell']), Paragraph(str(option['No']), stylesheet['Tablecell'])]) totaldata.append([ Paragraph(_('Abstention'), stylesheet['Tablecell']), Paragraph(str(option['Abstain']), stylesheet['Tablecell'])]) totaldata.append([ Paragraph(_('Valid votes'), stylesheet['Tablecell']), Paragraph(poll.print_votesvalid(), stylesheet['Tablecell'])]) totaltable = LongTable(totaldata, style=[ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 3), (-1, 3), 1, colors.black), ]) totaltable._argW[0] = 3 * cm totaltable._argW[1] = 3 * cm pdf.append(totaltable) pdf.append(Spacer(0, 0.5 * cm)) # table with single votes pdf.append(Paragraph(_('All single votes') + ':', stylesheet['Heading4'])) data = [['#', _('Name'), _('Keypad serial number'), _('Vote')]] counter = 0 for keypad_data in keypad_data_list: counter += 1 line = [] line.append(Paragraph(str(counter), stylesheet['Tablecell'])) if keypad_data.keypad is not None and keypad_data.keypad.user: line.append(Paragraph(str(keypad_data.keypad.user), stylesheet['Tablecell'])) else: line.append(Paragraph(_('Anonymous'), stylesheet['Tablecell'])) if keypad_data.serial_number: line.append(Paragraph(str(keypad_data.serial_number), stylesheet['Tablecell'])) else: line.append(Paragraph(str(keypad_data.keypad.keypad_id), stylesheet['Tablecell'])) line.append(Paragraph(str(keypad_data.get_value()), stylesheet['Tablecell'])) data.append(line) t = LongTable(data, style=[ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm pdf.append(t) return pdf
template = PageTemplate(id='test', frames=frame, onPage=org.get_header_footer()) doc.addPageTemplates([template]) #text = [] #for i in range(111): # text.append(Paragraph("This is line %d." % i, # styleN)) #doc.build(text) # =================== TABLE DATA elements = [] datas = [] headDate = Paragraph('Date', styleB) headDuration = Paragraph('Duration', styleN) headTopics = Paragraph('Topics Covered', styleN) headEval = Paragraph('Evaluation Instruments Used', styleN) headSign = Paragraph('Signature', styleN) datas = [[headDate, headDuration, headTopics, headEval, headSign]] for x in range(1, 50): datas.append( [x, x + 1, x + 2, x + 4, x + 5] ) t = LongTable(datas, colWidths=[1.5 * cm, 2 * cm, 8 * cm, 3 * cm, 3 * cm]) t.setStyle(TableStyle(org.getTableStyle())) elements.append(t) doc.build(elements)
def report_internal_courseoutline_pdf(request, course_name): response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefile.pdf"' buffer = BytesIO() org = Internal() styleN, styleB, styleH, styleSmaller = org.getTextStyles() doc = FooterDocTemplate(buffer, pagesize=A4) frame = org.getFrame(doc) template = PageTemplate(id='test', frames=frame, onPage=org.get_header_footer(doccode="", pagesize=A4)) doc.addPageTemplates([template]) width, height = A4 frame_width = width - ((doc.leftMargin - 20) * 2) logo_filename = os.path.join(os.path.dirname(__file__), 'images', get_config('logo_filename')) # Our main content holder elements = [] inst_name = Paragraph(get_config('inst_name'), styleH) dept_name = Paragraph(get_config('dept_name') + ", " + get_config('campus_name'), styleB) report_title = Paragraph('Course Outline', styleB) semester = Paragraph("(" + str(course_name.semester) + " " + str(course_name.year) + ")", styleB) logobox = Image(logo_filename, 100, 110) metainfo = [[logobox, inst_name], ['', dept_name], ['', report_title], ['', semester], ] metainfo_tablestyle = [('SPAN', (0, 0), (0, -1))] t1 = LongTable(metainfo, colWidths=[5 * cm, 14 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) # title page # inst_name_head = Paragraph('INSTITUTION', styleB) # inst_name = Paragraph(get_config('inst_name'), styleN) # dept_name_head = Paragraph('PROGRAM(S) TO BE EVALUATED', styleB) # dept_name = Paragraph("BS (CS)", styleN) # # metainfo_tablestyle = [ # # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), # ('LINEBELOW', (1, 0), (1, -1), 0.25, colors.black), # # ('BOX', (0, 0), (-1, -1), 0.25, colors.black), # ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # ] # metainfo = [[inst_name_head, inst_name], [dept_name_head, dept_name]] # t1 = LongTable(metainfo, colWidths=[3 * cm, frame_width - (3 * cm)]) # t1.setStyle(TableStyle(metainfo_tablestyle)) # elements.append(t1) elements.append(Spacer(1, 0.5 * cm)) # elements.append(Paragraph('A. COURSE DESCRIPTION', styleH)) # elements.append(Paragraph('(Fill out the following table for each course in your computer science curriculum. A filled out form should not be more than 2-3 pages.', styleN)) # elements.append(Spacer(1, 0.5 * cm)) # =================== TABLE DATA c = course_name try: co = CourseOutline.objects.filter(course=c)[0] # one-to-one relation except Exception, err: raise RuntimeError("Course outlines not defined for " + str(course_name))
def report_qec_faculty_profile_pdf(request, instructor): def make_table(data, widths, style=[]): table = LongTable(data, colWidths=widths) table.setStyle(TableStyle(style)) return table response = HttpResponse(mimetype='application/pdf') buffer = BytesIO() org = Qec() styleN, styleB, styleH, styleSmaller = org.getTextStyles() styleBC = copy.copy(styleB) styleBC.alignment = TA_CENTER width, height = A4 doc = FooterDocTemplate(buffer, pagesize=A4) frame = org.getFrame(doc) template = PageTemplate(id='test', frames=frame, onPage=org.get_header_footer(doccode="Proforma 9")) doc.addPageTemplates([template]) # Our main content holder logo_filename = os.path.join(os.path.dirname(__file__), '../../cscm/views/images', get_config('logo_filename')) elements = [] inst_name = Paragraph(get_config('inst_name'), styleH) dept_name = Paragraph(get_config('dept_name') + ", " + get_config('campus_name'), styleB) report_title = Paragraph('Proforma 9: Faculty CV', styleB) logobox = Image(logo_filename, 75, 80) metainfo = [[logobox, inst_name], ['', dept_name], ['', report_title], ] metainfo_tablestyle = [('SPAN', (0, 0), (0, -1))] t1 = LongTable(metainfo, colWidths=[3 * cm, 15 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) elements.append(Spacer(1, 0.5 * cm)) i = instructor ip = i.instructorprofile percent_time_teaching = ip.percent_time_teaching # title page data = [[Paragraph('Name', styleB), i.name], [Paragraph('Academic Rank', styleB), ip.designation], [Paragraph('Administrative Responsibility', styleB), Paragraph(ip.admin_responsibility.replace('\n', '<br />'), styleN)], [Paragraph('Date of Original Appointment', styleB), ip.joining_date], [Paragraph('Email', styleB), ip.email], [Paragraph('Address', styleB), Paragraph(clean_string(ip.contact_address), styleN)], [Paragraph('Contact Number', styleB), ip.contact_number], ] ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ] elements.append(make_table(data, widths=[5 * cm, 12 * cm], style=ts)) # elements.append(PageBreak()) # Education ieds = i.instructoreducation_set.all().order_by('-year') data = [[Paragraph('Education', styleB), Paragraph('Degree', styleB), Paragraph('Field', styleB), Paragraph('Institution', styleB), Paragraph('Date', styleB), ]] for ied in ieds: data.append(['', Paragraph(ied.degree, styleN), Paragraph(ied.field, styleN), Paragraph(ied.university, styleN), Paragraph(ied.year, styleN), ]) ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('SPAN', (0, 0), (0, -1)) ] elements.append(make_table(data, widths=[5 * cm, 2.5 * cm, 3 * cm, 5 * cm, 1.5 * cm], style=ts)) # events ievs = i.instructoreventparticpation_set.all().order_by('-start_date') counter = 1 cat_header = Paragraph('Conferences, workshops, and professional development programs participated during the past five years', styleB) data = [] for iev in ievs: iev_string = str(counter) + '. ' + iev.title + '. Role: ' + iev.role + ' (' + str(iev.duration) + ' at ' + str(iev.venue) + ')' data.append([cat_header, Paragraph(iev_string, styleN), Paragraph(str(iev.start_date.year), styleN), ]) cat_header = '' counter += 1 ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('SPAN', (0, 0), (0, -1)) ] if len(data) < 1: data.append([cat_header, 'None' , '-']) elements.append(make_table(data, widths=[5 * cm, 10.5 * cm, 1.5 * cm], style=ts)) # Consultancies icons = i.instructorconsultancy_set.all().order_by('-date') counter = 1 cat_header = Paragraph('Consulting activities during the last five years', styleB) data = [] for icon in icons: icon_string = str(counter) + '. <b>' + icon.organization + '</b>. ' + icon.description data.append([cat_header, Paragraph(icon_string, styleN), Paragraph(str(icon.date.year), styleN), ]) cat_header = '' counter += 1 ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('SPAN', (0, 0), (0, -1)) ] if len(data) < 1: data.append([cat_header, 'None' , '-']) elements.append(make_table(data, widths=[5 * cm, 10.5 * cm, 1.5 * cm], style=ts)) # research interest data = [[Paragraph('Research Statement', styleB), Paragraph(clean_string(ip.statement_of_research), styleN)], ] ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ] elements.append(make_table(data, widths=[5 * cm, 12 * cm], style=ts)) # Publications ipbs = i.instructorpublication_set.all().order_by('-pub_date') counter = 1 cat_header = Paragraph('Principal publications during the last five years (give in standard bibliogrpahic format)', styleB) data = [] for ipb in ipbs: pub_string = str(counter) + '. ' + ipb.get_citation() data.append([cat_header, Paragraph(pub_string, styleN), Paragraph(str(ipb.pub_date.year), styleN), ]) cat_header = '' counter = counter + 1 ts = [ ('INNERGRID', (1, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (0, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), # ('SPAN', (0, 0), (0, -1)) # gives error for some reason ] if len(data) < 1: data.append([cat_header, 'None' , '-']) elements.append(make_table(data, widths=[5 * cm, 10.5 * cm, 1.5 * cm], style=ts)) # Other activities ioas = i.instructorotheractivity_set.all().order_by('-date') counter = 1 cat_header = Paragraph('Other scholarly activities during the last five years (grants, sabbaticals, software development, etc.)', styleB) data = [] for ioa in ioas: pub_string = str(counter) + '. ' + str(ioa.title) + '. ' + str(ioa.description) data.append([cat_header, Paragraph(pub_string, styleN), Paragraph(str(ioa.date), styleN), ]) cat_header = '' counter += 1 ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('SPAN', (0, 0), (0, -1)) ] if len(data) < 1: data.append([cat_header, 'None' , '-']) elements.append(make_table(data, widths=[5 * cm, 10.5 * cm, 1.5 * cm], style=ts)) # courses during last two years ics = i.course_set.all().order_by('-year') data = [[Paragraph('Courses taught during this and last academic year', styleB), Paragraph('Year', styleB), Paragraph('Semester', styleB), Paragraph('Course Code', styleB), Paragraph('Course Title', styleB), ]] for ic in ics: data.append(['', str(ic.year), str(ic.semester), str(ic.course_code), Paragraph(str(ic.course_name), styleN) ]) ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), # ('SPAN', (0, 0), (0, -1)) ] elements.append(make_table(data, widths=[5 * cm, 1.5 * cm, 2 * cm, 2 * cm, 6.5 * cm], style=ts)) # Services to dept data = [[Paragraph('Services to the University', styleB), Paragraph(clean_string(ip.services_to_dept), styleN)], ] ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ] elements.append(make_table(data, widths=[5 * cm, 12 * cm], style=ts)) # END OF REPORT. NOW BUILD doc.build(elements) # OUTPUT FILE # doc.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def vc_report(story, checks_list,vCenterIP): loggerObj.LogMessage("info",file_name + " :: vc_report() Enter") count = 0 for checks in checks_list: count += 1 categoryList="" story.append(Spacer(1, 0.01 * inch)) categoryListLen = len(checks.get('Category')) for category in checks.get('Category'): categoryList += category if(categoryListLen > 1): categoryList += ", " categoryListLen = categoryListLen - 1 else : continue checks_data = [[str(count) + ". Check: " + checks.get('Name'), " Category: "+ categoryList]] checks_para_table = Table(checks_data, hAlign='LEFT') checks_para_table.setStyle(TableStyle([('ALIGN', (0, 0), (1, 0), 'LEFT'), ('FONTSIZE', (0, 0), (1, 0), 10.50)])) if checks.get('Name') == 'Network Resource Pool Settings': checks_property_data = [['Resource Pool','Exp Shares','Current Shares','Exp Level','Current Level','Exp Limit','Current Limit','Severity']] property_lenght = len(checks.get('Properties')) for properties in checks.get('Properties'): if properties is not None: xprop_msg, xprop_actual, xprop_exp = properties.get('Message').split("=") xprop_actual = xprop_actual.split(' (')[0] or xprop_actual.split(' ')[0] or "None" if xprop_actual is not None and xprop_actual != 'False': xprop_actual = xprop_actual.split("[")[1].split("]")[0] xprop_actual_list = xprop_actual.split(' ') current_share = xprop_actual_list[1].split(':')[-1] current_level = xprop_actual_list[2].split(':')[-1] current_limit = xprop_actual_list[0].split(':')[-1] xprop_exp = xprop_exp.split(' )')[0] or xprop_exp.split(' ')[0] or "None" if xprop_exp is not None: xprop_exp = xprop_exp.split("[")[1].split("]")[0] xprop_exp_list = xprop_exp.split(' ') expected_share = xprop_exp_list[1].split(':')[-1] expected_level = xprop_exp_list[2].split(':')[-1] expected_limit = xprop_exp_list[0].split(':')[-1] resource_pool = xprop_msg.split("[")[1].split("]")[0] checks_property_data.append([Paragraph(resource_pool, NormalMessageStyle), Paragraph(expected_share, NormalMessageStyle), Paragraph(current_share, NormalMessageStyle), Paragraph(expected_level, NormalMessageStyle), Paragraph(current_level, NormalMessageStyle), Paragraph(expected_limit, NormalMessageStyle), Paragraph(current_limit, NormalMessageStyle), Paragraph('warning', NormalMessageStyle)]) else: property_lenght-=1 continue else: property_lenght-=1 continue checks_property_table = LongTable(checks_property_data, colWidths=[1.2*inch,1*inch,1.1*inch,0.8*inch,1.1*inch,0.8*inch,1.1*inch,0.65*inch]) checks_property_table.setStyle(TableStyle([('BACKGROUND', (0, 0), (7, 0), colors.fidlightblue), ('ALIGN', (0, 0), (7, property_lenght), 'LEFT'), ('INNERGRID', (0, 0), (7, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (1, property_lenght), 0.25, colors.black), ('TEXTFONT', (0, 0), (7, 0), 'Times-Roman'), ('FONTSIZE', (0, 0), (7, 0), 10)])) elif checks.get('Name') == 'JVM Memory for vSphere Server': checks_property_data = [['Entity Checked','Memory Configured','Memory Recommended','Severity']] property_lenght = len(checks.get('Properties')) for properties in checks.get('Properties'): if properties is not None and properties.get('Status') == 'FAIL': xprop_msg, xprop_actual, xprop_exp = properties.get('Message').split("=") xprop_actual = xprop_actual.split(' (')[0] or xprop_actual.split(' ')[0] or "None" xprop_exp = xprop_exp.split(')')[0] or xprop_exp.split(' ')[0] or "None" if xprop_actual == 'SSH Connection Failed': property_lenght-=1 continue else: checks_property_data.append([Paragraph(xprop_msg, NormalMessageStyle), Paragraph(xprop_actual, NormalMessageStyle), Paragraph(xprop_exp, NormalMessageStyle), Paragraph("info", NormalMessageStyle)]) else: property_lenght-=1 continue checks_property_table = LongTable(checks_property_data, colWidths=[2.8*inch,1.6*inch,1.75*inch,1.5*inch]) checks_property_table.setStyle(TableStyle([('BACKGROUND', (0, 0), (3, 0), colors.fidlightblue), ('ALIGN', (0, 0), (3, property_lenght), 'LEFT'), ('INNERGRID', (0, 0), (3, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (1, property_lenght), 0.25, colors.black), ('TEXTFONT', (0, 0), (3, 0), 'Times-Roman'), ('FONTSIZE', (0, 0), (3, 0), 10)])) elif checks.get('Name') == 'Check if Default Password has Changed': checks_property_data = [['Component Name','IP Address','Username','Severity']] property_lenght = len(checks.get('Properties')) for properties in checks.get('Properties'): if properties is not None and properties.get('Status') == 'PASS': xprop_msg, xprop_actual, xprop_exp = properties.get('Message').split("=") xprop_actual = xprop_actual.split(' (')[0] or xprop_actual.split(' ')[0] or "None" if xprop_actual == 'SSH Connection Failed' or xprop_actual == 'Connection Failed': property_lenght-=1 continue else: xprop_msg_list = xprop_msg.split() if len(xprop_msg_list) == 5: component,component_ip = xprop_msg.split()[3:] elif len(xprop_msg_list) == 6: component1,component2,component_ip = xprop_msg.split()[3:] component = component1+" "+component2 component = component.strip(':') if xprop_actual == 'Not Changed': severity = 'info' else: severity = 'alert' if component == 'Host': username = '******' elif component == 'vCenter Server': username ='******' elif component == 'CVM': username = '******' elif component == 'Prism': username = '******' elif component == 'IPMI': username = '******' checks_property_data.append([Paragraph(component, NormalMessageStyle), Paragraph(component_ip, NormalMessageStyle), Paragraph(username, NormalMessageStyle), Paragraph(severity, NormalMessageStyle)]) else: property_lenght-=1 continue checks_property_table = LongTable(checks_property_data, colWidths=[2.8*inch,1.6*inch,1.75*inch,1.5*inch]) checks_property_table.setStyle(TableStyle([('BACKGROUND', (0, 0), (3, 0), colors.fidlightblue), ('ALIGN', (0, 0), (3, property_lenght), 'LEFT'), ('INNERGRID', (0, 0), (3, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (1, property_lenght), 0.25, colors.black), ('TEXTFONT', (0, 0), (3, 0), 'Times-Roman'), ('FONTSIZE', (0, 0), (3, 0), 10)])) else: checks_property_data = [['Entity Tested','Datacenter Name','Cluster Name','Expected Result','Check Status','Severity']] property_lenght = len(checks.get('Properties')) expected_result = checks.get('Expected_Result') for properties in checks.get('Properties'): if properties is not None: entity_tested_name = properties.get('Entity') datacenter_name = properties.get('Datacenter') cluster_name = properties.get('Cluster') #msg = '<br/>(Exp'.join(properties.get('Message').split('(Exp')) xprop_msg, xprop_actual, xprop_exp = properties.get('Message').split("=") if xprop_msg == "": xprop_msg = check['name'] xprop_actual = xprop_actual.split(' (')[0] or xprop_actual.split(' ')[0] or "None" actual_result, is_prop_include , severity =get_vc_check_actual_output_format(checks.get('Name'), xprop_actual, properties.get('Entity'), properties.get('Datacenter'), properties.get('Cluster'), properties.get('Host'), properties.get('Status'), properties.get('Message'), xprop_exp.strip(')'), vCenterIP) if is_prop_include == False: property_lenght-=1 continue checks_property_data.append([Paragraph(entity_tested_name, NormalMessageStyle), Paragraph(datacenter_name, NormalMessageStyle), Paragraph(cluster_name, NormalMessageStyle), Paragraph(expected_result, NormalMessageStyle), Paragraph(actual_result, NormalMessageStyle), Paragraph(severity, NormalMessageStyle)]) if len(checks_property_data) == 1: property_data = [['Status: PASS(Either all entities configured correctly or No entities found to run check)']] checks_property_table = LongTable(property_data, colWidths=[7.7*inch]) checks_property_table.setStyle(TableStyle([('BACKGROUND', (0, 0), (0, 0), colors.fidlightblue), ('ALIGN', (0, 0), (0, property_lenght), 'LEFT'), ('INNERGRID', (0, 0), (0, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (1, property_lenght), 0.25, colors.black), ('TEXTFONT', (0, 0), (0, 0), 'Times-Roman'), ('FONTSIZE', (0, 0), (0, 0), 10)])) elif len(checks_property_data) > 1: checks_property_table = LongTable(checks_property_data, colWidths=[1*inch,1.2*inch,1*inch,1.15*inch,2.7*inch,0.65*inch]) checks_property_table.setStyle(TableStyle([('BACKGROUND', (0, 0), (5, 0), colors.fidlightblue), ('ALIGN', (0, 0), (5, property_lenght), 'LEFT'), ('INNERGRID', (0, 0), (5, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (1, property_lenght), 0.25, colors.black), ('TEXTFONT', (0, 0), (5, 0), 'Times-Roman'), ('FONTSIZE', (0, 0), (5, 0), 10)])) story.append(checks_para_table) story.append(Spacer(1, 0.05 * inch)) story.append(checks_property_table) story.append(Spacer(1, 0.3 * inch)) loggerObj.LogMessage("info",file_name + " :: vc_report() Exit")
def PDFReportGenerator(resultJson,curdir=None): file_name = os.path.basename(__file__) loggerObj.LogMessage("info",file_name + " :: PDFReportGenerator() Enter") # Adding timestamp to the report name timestamp = time.strftime("%Y%m%d-%H%M%S") # path for generating the report if curdir is None: pdffilename = os.getcwd() + os.path.sep +"reports" + os.path.sep+ 'Healthcheck-' + timestamp + '.pdf' else: pdffilename = curdir + os.path.sep +"reports" + os.path.sep+ 'Healthcheck-' + timestamp + '.pdf' loggerObj.LogMessage("info",file_name + " :: PDF report path is - " + pdffilename) doc = SimpleDocTemplate(pdffilename, pagesizes=letter, format=landscape, rightMargin=inch / 8, leftMargin=inch / 12, topMargin=inch, bottomMargin=inch / 4) story = [] date = time.strftime("%B %d, %Y") png_path=os.path.abspath(os.path.dirname(__file__))+os.path.sep+'static'+os.path.sep+'images'+os.path.sep+'hcr.png' headingdata = [[" ", " ", " ", " ", Image(png_path, height=0.37 * inch, width=12 * cm)], [ " ", " ", " ", " ", " " , date]] headingtable = Table(headingdata) headingtable.setStyle(TableStyle([('ALIGN', (0, 1), (4, 1), 'RIGHT'), ('TEXTFONT', (0, 1), (4, 1), 'Times-Roman'), ('FONTSIZE', (0, 1), (4, 1), 12)])) story.append(headingtable) for checkers in resultJson.keys(): checkers_table_data = [] # Adding heading to the document based on the checkers if checkers == 'ncc': checkers_table_data = [["Nutanix Cluster"+ " ["+resultJson[checkers].get('ip')+"] "+" Health Check Results"]] checkers_table_data.append([Paragraph("Username:"******"vCenter"+ " ["+resultJson[checkers].get('ip')+"] "+" Health Check Results"]] checkers_table_data.append([Paragraph("Username:"******"VMware View"+ " ["+resultJson[checkers].get('ip')+"] "+" Check Results"]] checkers_table_data.append([Paragraph("Username:"******"info",file_name + " :: PDF report for vc") vc_report(story, resultJson[checkers].get('checks'),resultJson[checkers].get('ip')) if checkers == 'ncc': loggerObj.LogMessage("info",file_name + " :: PDF report for ncc") ncc_report(story, resultJson[checkers].get('checks')) if checkers == 'view': loggerObj.LogMessage("info",file_name + " :: PDF report for view") view_report(story, resultJson[checkers].get('checks')) doc.build(story, onFirstPage=_header_footer, onLaterPages=_header_footer) pdf_report_name = pdffilename.split(os.path.sep)[-1] generic_report_name = pdf_report_name.split('.')[0] if curdir is None: print "\nReport ("+pdf_report_name+") generated successfully at :: " + os.getcwd() + os.path.sep +"reports" else: print "\nReport ("+pdf_report_name+") generated successfully at :: " + curdir + os.path.sep +"reports" loggerObj.LogMessage("info",file_name + " :: PDF report generated successfully") loggerObj.LogMessage("info",file_name + " :: PDFReportGenerator() Exit") return pdf_report_name
def doexport(request, id): u = request.user uid = u.id fields = ['address', 'occupation', 'email', 'note'] showall = request.GET.get('all') format = request.GET.get('format', 'csvutf-8') header = request.GET.get('header') semicol = request.GET.get('semicol') p = Petition.objects.filter(pk=id) if not p: return error(request) p = p[0] if p.user_id != uid and not u.is_superuser: return unauth(request) s = p.signature_set.order_by('timestamp') if not s: return HttpResponseRedirect('/admin/petitionlist/') if format[:3] == 'csv': import csv from io import StringIO asciitbl=str.maketrans( 'áäčďéěëíĺľňóôöŕřšťúůüýžÁÄČĎÉĚËÍĹĽŇÓÔÖŔŘŠŤÚŮÜÝŽ', 'aacdeeeillnooorrstuuuyzAACDEEEILLNOOORRSTUUUYZ') def rawascii(l): return l.translate(asciitbl).encode('ascii', 'replace') enc = format[3:] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=podpisy.csv' if semicol: delimiter = ';' else: delimiter = ',' sio = StringIO() writer = csv.writer(sio, delimiter=delimiter) if header: hl = ['Jméno a příjmení', 'Adresa', 'Povolání', 'Datum narození', 'E-mail', 'Poznámka', 'Datum a čas podpisu'] writer.writerow(hl) for row in s: r = {} for f in fields: if showall or not row.__getattribute__(f + '_hidden'): r[f] = row.__getattribute__(f) else: r[f] = '' if row.birthdate and (showall or not row.birthdate_hidden): bd = row.birthdate.strftime('%d.%m.%Y') else: bd = '' if row.timestamp: ts = row.timestamp.strftime('%d.%m.%Y %H:%M') else: ts = '' w = [row.name, r['address'], r['occupation'], bd, r['email'], r['note'], ts] writer.writerow(w) sio.seek(0) u = sio.read() if enc == 'ascii': b = rawascii(u) else: b = u.encode(enc, 'replace') response.write(b) return response elif format == 'xml': xd = { 'petition': { 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:noNamespaceSchemaLocation': 'http://petice.pecina.cz/static/%s-%s.xsd' % (APP, VERSION), 'application': APP, 'version': VERSION, 'created': datetime.now().replace(microsecond=0).isoformat() } } xml = newXML('') d = xmldecorate(xml.new_tag('petition'), xd) xml.append(d) tag = xml.new_tag('name') tag.append(xmlescape(p.longname)) d.append(tag) sg = xml.new_tag('signatures') for ss in s: t = xml.new_tag('signature') tag = xml.new_tag('name') tag.append(xmlescape(ss.name)) t.append(tag) for f in ['address', 'birthdate', 'occupation', 'email', 'note']: if (showall or not ss.__getattribute__(f + '_hidden')) and \ ss.__getattribute__(f): tag = xml.new_tag(f) if f == 'birthdate': tag.append(ss.birthdate.isoformat()) else: tag.append(xmlescape(ss.__getattribute__(f))) if showall: tag['hidden'] = \ str(ss.__getattribute__(f + '_hidden')).lower() t.append(tag) if ss.birthdate and (showall or not ss.birthdate_hidden): tag = xml.new_tag('timestamp') tag.append(ss.timestamp.isoformat()) t.append(tag) sg.append(t) d.append(sg) response = HttpResponse(content_type='text/xml') response['Content-Disposition'] = 'inline; filename=export.xml' response.write(str(xml).encode('utf-8') + '\n') return response elif format == 'yaml': var = {'longname': p.longname, 'rows': []} var['timestamp'] = strftime('%Y-%m-%d %H:%M:%S', localtime(time())) for row in s: r = {} r['name'] = row.name for f in fields: if showall or not row.__getattribute__(f + '_hidden'): r[f] = row.__getattribute__(f) if row.birthdate and (showall or not row.birthdate_hidden): r['birthdate'] = row.birthdate.strftime('%Y-%m-%d') r['timestamp'] = row.timestamp.strftime('%Y-%m-%d %H:%M:%S') var['rows'].append(r) return render(request, 'export.yml', var, content_type='text/yaml') elif format == 'pdf': fontdir = os.path.join(os.path.dirname(__file__), 'fonts/') \ .replace('\\','/') def page1(c, d): c.saveState() c.setFont('Liberation-Sans', 7) c.drawCentredString((A4[0] / 2), 30, ('Strana %u' % d.page)) c.restoreState() def page2(c, d): page1(c, d) c.saveState() c.setFont('Liberation-SansB', 8) c.drawCentredString((A4[0] / 2), (A4[1] - 50), p.longname) c.restoreState() def sanitize(text, limit): l = text.split(' ') for i in range(len(l)): if len(l[i]) > limit: l[i] = l[i][:limit] + u'…' return ' '.join(l) reportlab.rl_config.warnOnMissingFontGlyphs = 0 registerFont(TTFont( 'Liberation-Sans', (fontdir + 'LiberationSans-Regular.ttf'))) registerFont(TTFont( 'Liberation-SansB', (fontdir + 'LiberationSans-Bold.ttf'))) registerFont(TTFont( 'Liberation-SansI', (fontdir + 'LiberationSans-Italic.ttf'))) registerFont(TTFont( 'Liberation-SansBI', (fontdir + 'LiberationSans-BoldItalic.ttf'))) registerFontFamily( 'Liberation-Sans', normal='Liberation-Sans', bold='Liberation-SansB', italic='Liberation-SansI', boldItalic='Liberation-SansBI') sh1 = ParagraphStyle( name='Heading1', fontName='Liberation-SansB', fontSize=12, leading=14, spaceAfter=0, alignment=TA_CENTER) sh2 = ParagraphStyle( name='Heading2', fontName='Liberation-SansI', fontSize=8, leading=10, spaceBefore=0, spaceAfter=9, alignment=TA_CENTER) sth = ParagraphStyle( name='TableHeading', fontName='Liberation-SansB', fontSize=5, leading=6, textColor='#ffffff', alignment=TA_CENTER) stcl = ParagraphStyle( name='TableContentsLeft', fontName='Liberation-Sans', fontSize=5, leading=6) stcc = ParagraphStyle( name='TableContentsCenter', fontName='Liberation-Sans', fontSize=5, leading=6, alignment=TA_CENTER) sno = ParagraphStyle( name='Notice', fontName='Liberation-SansI', fontSize=5, leading=6, spaceBefore=9, alignment=TA_RIGHT, rightIndent=-6) flow = [Paragraph(p.longname, sh1)] flow.append(Paragraph(('Počet podpisů: %u' % s.count()), sh2)) th = ['Pořadí', 'Datum a čas', 'Jméno a příjmení', 'Povolání', 'Adresa', 'Narozen/a', 'E-mail', 'Poznámka'] data = [[Paragraph(x, sth) for x in th]] n = 0 for row in s: n += 1 r = {} for f in fields: if showall or not row.__getattribute__(f + '_hidden'): r[f] = row.__getattribute__(f) else: r[f] = '' if row.birthdate and (showall or not row.birthdate_hidden): birthdate = row.birthdate.strftime('%d.%m.%Y') else: birthdate = '' data.append([ Paragraph(str(n), stcc), Paragraph(row.timestamp.strftime('%d.%m.%Y %H:%M'), stcc), Paragraph(sanitize(row.name, 20), stcl), Paragraph(sanitize(r['occupation'], 20), stcl), Paragraph(sanitize(r['address'], 30), stcl), Paragraph(birthdate, stcc), Paragraph(sanitize(r['email'].lower(), 30), stcl), Paragraph(sanitize(r['note'], 45), stcl), ]) t = LongTable(data, colWidths=[22.15, 46.10, 52.95, 52.95, 76.65, 30.35, 80.50, 120.25], repeatRows=1) t.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,0), '#000000'), ('ROWBACKGROUNDS', (0,1), (-1,-1), ['#FFFFFF', '#F0F0F0']), ('ALIGN', (0,0), (-1,0), 'CENTER'), ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ('LEFTPADDING', (0,0), (-1,-1), 2), ('RIGHTPADDING', (0,0), (-1,-1), 2), ('TOPPADDING', (0,0), (-1,-1), 2), ('BOTTOMPADDING', (0,0), (-1,-1), 2), ])) flow.append(t) flow.append(Paragraph(strftime( 'Vytvořeno: %d.%m.%Y %H:%M:%S', localtime(time())), sno)) temp = BytesIO() response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=export.pdf' doc = SimpleDocTemplate( temp, pagesize=A4, title='Seznam podpisů', leftMargin=56.7, rightMargin=56.7, topMargin=56.7, bottomMargin=56.7, ) doc.build(flow, onFirstPage=page1, onLaterPages=page2) response.write(temp.getvalue()) return response else: return error(request)
def export(self, extm, params, req): pdf_pagesz = params.pop('pdf_pagesz', 'a4') pdf_orient = params.pop('pdf_orient', 'portrait') try: pdf_hmargins = float(params.pop('pdf_hmargins', 1.8)) except ValueError: pdf_hmargins = 1.8 try: pdf_vmargins = float(params.pop('pdf_vmargins', 2.0)) except ValueError: pdf_vmargins = 2.0 fields = [] flddef = [] col_widths = [] col_flexes = [] total_width = 0 total_flex = 0 for field in extm.export_view: if isinstance(field, PseudoColumn): fld = field field = fld.name else: fld = extm.get_column(field) fields.append(field) flddef.append(fld) width = fld.column_width flex = fld.column_flex if not width: width = fld.pixels if not width: width = 200 width = width / 200 * inch col_widths.append(width) if flex: col_flexes.append(flex) total_flex += flex else: col_flexes.append(None) total_width += width if pdf_pagesz not in PAGE_SIZES: raise ValueError('Unknown page size specified') if pdf_orient not in ('portrait', 'landscape'): raise ValueError('Unknown page orientation specified') res = Response() loc = get_localizer(req) now = datetime.datetime.now() res.last_modified = now res.content_type = 'application/pdf' res.cache_control.no_cache = True res.cache_control.no_store = True res.cache_control.private = True res.cache_control.must_revalidate = True res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN')) if PY3: res.content_disposition = \ 'attachment; filename*=UTF-8\'\'%s-%s.pdf' % ( urllib.parse.quote(loc.translate(extm.menu_name), ''), now.date().isoformat() ) else: res.content_disposition = \ 'attachment; filename*=UTF-8\'\'%s-%s.pdf' % ( urllib.quote(loc.translate(extm.menu_name).encode(), ''), now.date().isoformat() ) for prop in ('__page', '__start', '__limit'): if prop in params: del params[prop] data = extm.read(params, req)['records'] doc = DefaultDocTemplate( res, request=req, pagesize=pdf_pagesz, orientation=pdf_orient, topMargin=pdf_vmargins * cm, leftMargin=pdf_hmargins * cm, rightMargin=pdf_hmargins * cm, bottomMargin=pdf_vmargins * cm, title=loc.translate(_('{0}, exported at {1}')).format( loc.translate(extm.menu_name), format_datetime(now, locale=req.current_locale) ) ) total_width = doc.width - total_width - 12 if total_flex > 0: width_per_flex = total_width / total_flex else: width_per_flex = 0.0 table_widths = [] for idx, field in enumerate(fields): if col_flexes[idx]: table_widths.append(col_flexes[idx] * width_per_flex) else: table_widths.append(col_widths[idx]) ss = req.pdf_styles if ss is None: raise RuntimeError('PDF subsystem is not configured. See application .INI files.') # TODO: add custom extmodel option to specify rowHeights, as an # optimization measure. Otherwise reportlab takes +Inf time on huge # tables. # Crude hack: rowHeights=([0.5 * inch] * (len(data) + 1) table = LongTable( tuple(storyteller(data, fields, flddef, localizer=loc, model=extm, styles=ss)), colWidths=table_widths, repeatRows=1 ) table.setStyle(TABLE_STYLE_DEFAULT) story = [table] doc.build(story) return res
['<b>Other Information</b>' , clean_string(co.other_information)], # ['<b>Topics Covered in the Course with Number of lectures on Each Topic</b>(assume 15 week instruction and one-hour lectures)', topics_covered_details], # ['<b>Laboratory Projects/Experiments Done in the Course</b>', c.lab_projects], # ['<b>Programming Assignments Done in the Course</b>', c.prog_assignments], ] for k in course_info: headpara = Paragraph(k[0], styleN) if len(k) > 2 : use_style = k[2] else: use_style = styleN datas.append([headpara , Paragraph(k[1] if k[1] != '' else '-', use_style)]) t = LongTable(datas, colWidths=[5 * cm, 12 * cm]) t.setStyle(org.getTableStyle()) elements.append(t) # topics covered in the course credits = c.credits try : datas = [[Paragraph('<b>Topics Covered in the Course with Number of lectures on Each Topic</b>', styleN), Paragraph('Week No. (Duration)', styleB), Paragraph('Topics', styleB), ]] wp = WeekPlan.objects.filter(course_outline=co) for w in wp: datas.append(['', Paragraph(unicode(w.week_no) + ' (' + unicode(credits) + ' hrs)', styleB), Paragraph(clean_string(unicode(w.topics)), styleN)])
def get_assignment(self, assignment, story): # title story.append(Paragraph( _("Election: %s") % escape(assignment.title), stylesheet['Heading1'])) story.append(Spacer(0, 0.5 * cm)) # Filling table rows... data = [] polls = assignment.polls.filter(published=True) # 1. posts data.append([ Paragraph("%s:" % _("Number of members to be elected"), stylesheet['Bold']), Paragraph(str(assignment.open_posts), stylesheet['Paragraph'])]) # 2a. if no polls available print candidates if not polls: data.append([ Paragraph("%s:<seqreset id='counter'>" % _("Candidates"), stylesheet['Heading4']), []]) for candidate in assignment.candidates: data.append([ [], Paragraph("<seq id='counter'/>. %s" % candidate, stylesheet['Signaturefield'])]) if assignment.phase == assignment.PHASE_SEARCH: for x in range(0, 7): data.append([ [], Paragraph("<seq id='counter'/>. " "__________________________________________", stylesheet['Signaturefield'])]) # 2b. if polls available print election result if polls: # Preparing vote_results = assignment.vote_results(only_published=True) data_votes = [] # Left side cell = [] cell.append(Paragraph( "%s:" % (_("Election result")), stylesheet['Heading4'])) # Add table head row headrow = [] headrow.append(_("Candidates")) for poll in polls: headrow.append("%s. %s" % (poll.get_ballot(), _("ballot"))) data_votes.append(headrow) # Add result rows elected_candidates = list(assignment.elected) length = len(vote_results) for candidate, poll_list in vote_results.iteritems(): row = [] candidate_string = candidate.clean_name if candidate in elected_candidates: candidate_string = "* " + candidate_string if candidate.name_suffix and length < 20: candidate_string += "\n(%s)" % candidate.name_suffix row.append(candidate_string) for vote in poll_list: if vote is None: row.append('–') elif 'Yes' in vote and 'No' in vote and 'Abstain' in vote: row.append( _("Y: %(YES)s\nN: %(NO)s\nA: %(ABSTAIN)s") % {'YES': vote['Yes'], 'NO': vote['No'], 'ABSTAIN': vote['Abstain']}) elif 'Votes' in vote: row.append(vote['Votes']) else: pass data_votes.append(row) # Add valid votes row footrow_one = [] footrow_one.append(_("Valid votes")) votesvalid_is_used = False for poll in polls: footrow_one.append(poll.print_votesvalid()) if poll.votesvalid is not None: votesvalid_is_used = True if votesvalid_is_used: data_votes.append(footrow_one) # Add invalid votes row footrow_two = [] footrow_two.append(_("Invalid votes")) votesinvalid_is_used = False for poll in polls: footrow_two.append(poll.print_votesinvalid()) if poll.votesinvalid is not None: votesinvalid_is_used = True if votesinvalid_is_used: data_votes.append(footrow_two) # Add votes cast row footrow_three = [] footrow_three.append(_("Votes cast")) votescast_is_used = False for poll in polls: footrow_three.append(poll.print_votescast()) if poll.votescast is not None: votescast_is_used = True if votescast_is_used: data_votes.append(footrow_three) table_votes = Table(data_votes) table_votes.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9))) ]) ) data.append([cell, table_votes]) if elected_candidates: data.append(['', '* = ' + _('elected')]) # table style data.append(['', '']) t = LongTable(data) t._argW[0] = 4.5 * cm t._argW[1] = 11 * cm t.setStyle(TableStyle([ ('BOX', (0, 0), (-1, -1), 1, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP')])) story.append(t) story.append(Spacer(0, 1 * cm)) # election description story.append( Paragraph("%s" % escape(assignment.description).replace('\r\n', '<br/>'), stylesheet['Paragraph']))
def report_nceac_courselog_pdf(request, course_name): response = HttpResponse(mimetype="application/pdf") response["Content-Disposition"] = 'attachment; filename="somefile.pdf"' buffer = BytesIO() org = Nceac() styleN, styleB, styleH, styleSmaller = org.getTextStyles() styleBC = copy.copy(styleB) styleBC.alignment = TA_CENTER doc = FooterDocTemplate(buffer, pagesize=A4) frame = org.getFrame(doc) template = PageTemplate(id="test", frames=frame, onPage=org.get_header_footer(doccode="NCEAC.DOC.008")) doc.addPageTemplates([template]) # Our main content holder elements = [] # title page metainfo_tablestyle = [("ALIGN", (0, 0), (-1, -1), "CENTER")] metainfo = [ [Paragraph("NCEAC Secretariat", styleBC)], [Paragraph("Foundation University Institute of Management & Computer Sciences", styleBC)], [Paragraph("New Lalazar, Gulberg Avenue, Rawalpindi Cantt, 46000", styleBC)], [Paragraph("Phone : 051- 5516094, Fax: 051-5584574, PABX: 051- 5790360-2 (Ext. 202)", styleBC)], [Paragraph("http://www.nceac.org/", styleBC)], [Spacer(1 * cm, 1 * cm)], [Paragraph("COURSE LOG TEMPLATE", styleBC)], ] t1 = LongTable(metainfo, colWidths=[20 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) elements.append(Spacer(1 * cm, 1 * cm)) inst_name_head = Paragraph("INSITUTION", styleB) inst_name = Paragraph(get_config("inst_name"), styleN) dept_name_head = Paragraph("PROGRAM(S) TO BE EVALUATED", styleB) dept_name = Paragraph("BS (CS)", styleN) metainfo_tablestyle = [ # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ("LINEBELOW", (1, 0), (1, -1), 0.25, colors.black), # ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ] metainfo = [[inst_name_head, inst_name], [dept_name_head, dept_name]] t1 = LongTable(metainfo, colWidths=[3 * cm, 12 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) elements.append(Spacer(1 * cm, 1 * cm)) this_course_name_head = Paragraph("Course Name", styleB) this_course_name = Paragraph(str(course_name), styleN) dept_name_head = Paragraph("Catalog Number", styleB) dept_name = Paragraph(str(course_name.course_code), styleN) inst_name_head = Paragraph("Instructor Name", styleB) inst_name = Paragraph(str(course_name.instructor), styleN) metainfo_tablestyle = [ # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ("LINEBELOW", (1, 0), (1, -1), 0.25, colors.black), # ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ] metainfo = [[this_course_name_head, this_course_name], [dept_name_head, dept_name], [inst_name_head, inst_name]] t1 = LongTable(metainfo, colWidths=[3 * cm, 12 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) elements.append(PageBreak()) # =================== TABLE DATA datas = [] headDate = Paragraph("Date", styleB) headDuration = Paragraph("Duration", styleB) headTopics = Paragraph("Topics Covered", styleB) headEval = Paragraph("Evaluation Instruments Used", styleB) headSign = Paragraph("Signature", styleB) emptypara = Paragraph(" ", styleN) datas = [[headDate, headDuration, headTopics, headEval, headSign]] # courselogentry_data = CourseLogEntry.objects.all() courselogentry_data = course_name.courselogentry_set.all() # for x in range(1, 50): # datas.append( # [x, x + 1, x + 2, x + 4, x + 5] # ) for i in courselogentry_data: # entered_logs += 1 l_date = Paragraph(str(i.lecture_date.strftime("%d-%m, %Y")), styleSmaller) l_duration = Paragraph(str(i.duration), styleSmaller) l_topics_covered = Paragraph(clean_string(i.topics_covered), styleSmaller) l_eval = Paragraph(clean_string(i.evaluation_instruments), styleSmaller) datas.append([l_date, l_duration, l_topics_covered, l_eval, emptypara]) # for i in range(entered_logs, 16): # data.append([[emptypara, emptypara, emptypara, emptypara, emptypara]]) t = LongTable(datas, colWidths=[1.5 * cm, 2 * cm, 8 * cm, 3 * cm, 3 * cm], repeatRows=1) t.setStyle(TableStyle(org.getTableStyle())) elements.append(t) doc.build(elements) # OUTPUT FILE # doc.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def make_table(data, widths, style=[]): table = LongTable(data, colWidths=widths) table.setStyle(TableStyle(style)) return table
def report_qec_courselog_pdf(request, course_name, week_range): response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefile.pdf"' buffer = BytesIO() org = Qec() styleN, styleB, styleH, styleSmaller = org.getTextStyles() doc = FooterDocTemplate(buffer, pagesize=A4) frame = org.getFrame(doc) logo_filename = os.path.join(os.path.dirname(__file__), 'images', get_config('logo_filename')) template = PageTemplate(id='test', frames=frame, onPage=org.get_header_footer()) doc.addPageTemplates([template]) # Our main content holder elements = [] # title page # SYMBOLS FOR CHECKED/UNCHECKED: \u2713 \u26aa or x inst_name = Paragraph(get_config('inst_name'), styleH) dept_name = Paragraph(get_config('dept_name') + ", " + get_config('campus_name'), styleB) report_title = Paragraph('Weekly Progress Report (Performa 11)', styleB) semester = Paragraph("(" + str(course_name.semester) + " " + str(course_name.year) + ")", styleB) logobox = Image(logo_filename, 100, 110) metainfo = [[logobox, inst_name], ['', dept_name], ['', report_title], ['', semester], ] metainfo_tablestyle = [('SPAN', (0, 0), (0, -1))] t1 = LongTable(metainfo, colWidths=[5 * cm, 14 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) # doc._draw_header_logo('/home/nam/documents/exps/django-tut/fastnu-csd-audit/csdexec/cscm/views/images/fastlogo.png', 10, 10) elements.append(Spacer(1, 0.5 * cm)) course_name_label = Paragraph(course_name.course_name, styleB) inst_name_label = Paragraph(str(course_name.instructor), styleB) from_week_label = Paragraph(str(week_range[0]), styleB) to_week_label = Paragraph(str(week_range[1]), styleB) metainfo = [['Course Name', course_name_label, 'Instructor', inst_name_label], ['From Week', from_week_label, 'To Week', to_week_label], ] metainfo_tablestyle = [] t1 = LongTable(metainfo, colWidths=[3 * cm, 6 * cm, 3 * cm, 6 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) elements.append(Spacer(1, 0.5 * cm)) # elements.append(PageBreak()) # =================== TABLE DATA datas = [] headLNo = Paragraph('Lec.', styleB) headWNo = Paragraph('Wk.', styleB) headDate = Paragraph('Date', styleB) headDuration = Paragraph('Duration', styleB) headTopics = Paragraph('Topics Covered', styleB) headEval = Paragraph('Evaluation Instruments Used', styleB) headRead = Paragraph('Reading Materials', styleB) headSign = Paragraph('Signature', styleB) emptypara = Paragraph(' ', styleN) datas = [[headLNo, headWNo, headDate, headDuration, headTopics, headEval, headRead]] # courselogentry_data = CourseLogEntry.objects.all() courselogentry_data = course_name.courselogentry_set.all().order_by('lecture_date') start_week = int(week_range[0]) end_week = int(week_range[1]) num_assignments = 0 num_quizzes = 0 gross_contents_covered = '' all_contents_covered = True l_no = 1 # start w_no = 1 starting_week_of_year = 0 other_activities = [] for i in courselogentry_data: l_no = i.lecture_no() w_no = i.week_no() if w_no < start_week or w_no > end_week: continue # entered_logs += 1 l_date = Paragraph(str(i.lecture_date.strftime("%d-%m, %Y")), styleSmaller) l_duration = Paragraph(str(i.duration), styleSmaller) l_topics_covered = Paragraph(clean_string(i.topics_covered), styleSmaller) l_eval = Paragraph(clean_string(i.evaluation_instruments), styleSmaller) l_reading = Paragraph(clean_string(i.reading_materials), styleSmaller) emptypara = Paragraph(str(l_no) + ' ' + str(w_no), styleSmaller) datas.append([str(l_no), str(w_no), l_date, l_duration, l_topics_covered, l_eval, l_reading]) # logic for calculating meta data num_assignments += i.evaluation_instruments.lower().count('assignment') num_quizzes += i.evaluation_instruments.lower().count('quiz') gross_contents_covered += i.contents_covered.strip() + '\n' if i.contents_covered.strip() != '': all_contents_covered = False other_activities.append(i.other_activities) if len(datas) < 2: # 2 because we do have a header in any case raise Exception("No Course Log Entries found!") t = LongTable(datas, colWidths=[1 * cm, 1 * cm, 1.5 * cm, 2 * cm, 6 * cm, 3 * cm, 3 * cm], repeatRows=1) t.setStyle(TableStyle(org.getTableStyle())) elements.append(t) elements.append(Spacer(1, 0.5 * cm)) # lower metadata metainfo = [[Paragraph('<b>Number of Assignments</b>', styleN), str(num_assignments)], [Paragraph('<b>Number of Quizzes', styleN), str(num_quizzes)], ] t1 = LongTable(metainfo, colWidths=[6 * cm, 12 * cm]) t1.setStyle(TableStyle()) elements.append(t1) elements.append(Spacer(1, 1 * cm)) metainfo = [[Paragraph('Other activities (if any)', styleB)]] for oa in other_activities: metainfo.append([Paragraph(str(oa), styleN)]) t1 = LongTable(metainfo, colWidths=[18 * cm]) t1.setStyle(TableStyle()) elements.append(t1) elements.append(Spacer(1, 0.5 * cm)) # elements.append(Spacer(1, 0.5 * cm)) if all_contents_covered: is_covered_yes = '\u2713' is_covered_no = 'x' else: is_covered_yes = 'x' is_covered_no = '\u2713' gross_contents_covered = 'NA' if all_contents_covered == '' else gross_contents_covered metainfo = [ [is_covered_yes, 'All contents planned for this period were covered.'], [is_covered_no, 'Some contens planned for this period were not covered. Details below:'], ['', ''], [Paragraph(clean_string(gross_contents_covered), styleN), ''] ] metainfo_tablestyle = [('SPAN', (0, 2), (1, 2)), ('BOX', (0, 3), (1, 3), 0.25, colors.black), ('BOX', (0, 0), (0, 0), 0.25, colors.black), ('BOX', (0, 1), (0, 1), 0.25, colors.black)] t1 = LongTable(metainfo, colWidths=[0.6 * cm, 16 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) # signature area elements.append(Spacer(1, 1 * cm)) metainfo = [ [Paragraph('Date', styleB), datetime.datetime.now().strftime('%d-%B-%Y'), Paragraph('Signature', styleB), '', ''], ] metainfo_tablestyle = [('LINEBELOW', (3, 0), (3, 0), 0.25, colors.black)] t1 = LongTable(metainfo, colWidths=[2 * cm, 4 * cm, 2 * cm , 4 * cm, 5 * cm]) t1.setStyle(TableStyle(metainfo_tablestyle)) elements.append(t1) # finalize document doc.build(elements) # OUTPUT FILE # doc.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response