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 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 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 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 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 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_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 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 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 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 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 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 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
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 add_table_font(table: LongTable, font_name: str) -> None: """ Add a font to the entire table """ table_style = TableStyle([('FONTNAME', (0, 1), (-1, -3), font_name)]) table.setStyle(table_style)
def get_assignment(self, assignment, story): # title story.append(Paragraph( _("Election: %s") % escape(assignment.name), stylesheet['Heading1'])) story.append(Spacer(0, 0.5 * cm)) # Filling table rows... data = [] polls = assignment.poll_set.filter(published=True) # 1. posts data.append([ Paragraph("%s:" % _("Number of available posts"), stylesheet['Bold']), Paragraph(str(assignment.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.status == "sea": 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 generate_report(username, data): directory = os.path.join(os.path.dirname(current_app.instance_path), f'app/userdata/{username}/reports') if not os.path.exists(directory): os.makedirs(directory) url = directory + '/report_' + username + '.pdf' styles = getSampleStyleSheet() ordinary = PS(name='ordinary', fontName='Helvetica', alignment=1, fontSize=12, leading=14) centered = PS(name='centered', fontSize=14, leading=16, alignment=1, spaceAfter=10) bold = PS(name='bold', fontName='Helvetica-Bold', fontSize=14, leading=16) centered_bold = PS(name='centered_bold', fontSize=16, fontName='Helvetica-Bold', leading=18, alignment=1, spaceAfter=10) h2 = PS(name='Heading2', fontSize=12, leading=14) Report = [] logo = Image('app/static/images/hse.jpg', 1 * inch, 1 * inch) Report.append(logo) Report.append(Spacer(1, 12)) Report.append(Spacer(1, 12)) Report.append(Paragraph('Coronavirus Statistics, HSE', centered_bold)) Report.append(Spacer(1, 12)) Report.append(Spacer(1, 12)) Report.append(Paragraph(f'Report for user: {username}', centered_bold)) Report.append(Spacer(1, 12)) Report.append(Spacer(1, 12)) curr_time = str(datetime.now()).split(".")[0] Report.append(Paragraph(f'Time of Report creation: {curr_time}', centered)) Report.append(PageBreak()) styleN = styles['Normal'] styleN.wordWrap = 'CJK' Report.append(Paragraph('COVID-19 Main Live Statistics', centered_bold)) Report.append(Spacer(1, 12)) Report.append(Spacer(1, 12)) total_cases = data['statistics']['total_cases'] total_deaths = data['statistics']['total_deaths'] total_recovered = data['statistics']['total_recovered'] Report.append(Paragraph(f'COVID-19 Total Cases: {total_cases}', bold)) Report.append(Spacer(1, 12)) Report.append(Paragraph(f'COVID-19 Total Deaths: {total_deaths}', bold)) Report.append(Spacer(1, 12)) Report.append( Paragraph(f'COVID-19 Total Recovered: {total_recovered}', bold)) Report.append(Spacer(1, 12)) Report.append(Spacer(1, 12)) Report.append(Paragraph('COVID-19 Demographics Data:', centered_bold)) Report.append(Spacer(1, 12)) data_age = [[Paragraph(cell, styleN) for cell in row] for row in data['demographics']['death_rate_by_age']] data_age.insert(0, ["Age", "Death Rate of\nConfirmed Cases"]) table_age = LongTable(data_age, colWidths=['50%', '50%']) table_age.setStyle( TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.blue), ('GRID', (0, 0), (-1, -1), 0.5, colors.blue), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.gray)])) Report.append(Paragraph('Fig.1. Age of Coronavirus Deaths:', ordinary)) Report.append(Spacer(1, 10)) Report.append(table_age) Report.append(Spacer(1, 12)) data_sex = [[Paragraph(cell, styleN) for cell in row] for row in data['demographics']['death_rate_by_sex']] data_sex.insert( 0, ["Sex", "Death Rate of\nConfirmed Cases", "Death Rate of\nAll Cases"]) (data_sex) table_sex = LongTable(data_sex, colWidths=['33%', '33%', '33%']) table_sex.setStyle( TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.blue), ('GRID', (0, 0), (-1, -1), 0.5, colors.blue), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.gray)])) Report.append(Paragraph('Fig.2. Sex of Coronavirus Deaths:', ordinary)) Report.append(Spacer(1, 10)) Report.append(table_sex) Report.append(Spacer(1, 12)) data_disease = [[Paragraph(cell, styleN) for cell in row] for row in data['demographics']['pre_existing_conditions']] data_disease.insert(0, [ "Pre-Existing\nCondition", "Death Rate of\nConfirmed Cases", "Death Rate of\nAll Cases" ]) table_disease = LongTable(data_age, colWidths=['33%', '33%', '33%']) table_disease.setStyle( TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.blue), ('GRID', (0, 0), (-1, -1), 0.5, colors.blue), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.gray)])) Report.append( Paragraph('Fig.3. Pre-existing medical conditions (comorbidities):', ordinary)) Report.append(Spacer(1, 10)) Report.append(table_disease) Report.append(Spacer(1, 12)) Report.append(PageBreak()) Report.append( Paragraph( 'COVID-19 Confirmed Cases and Deaths by Country, Territory, or Conveyance', centered_bold)) data_proccessed = [[Paragraph(cell, styleN) for cell in row] for row in data['countries']['countries_adv_data']] data_proccessed.insert(0, [ "Country", "Total\nCases", "New\nCases", "Total\nDeaths", "New\nDeaths", "Total\nRecovered", "Active\nCases", "Serious", "Cases\n1M Pop" ]) table_countries = LongTable(data_proccessed, colWidths=[ '17%', '10%', '10%', '10%', '10%', '13%', '10%', '10%', '10%' ]) table_countries.setStyle( TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.blue), ('GRID', (0, 0), (-1, -1), 0.5, colors.blue), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.gray)])) Report.append(table_countries) Report.append(Spacer(1, 12)) Report.append(PageBreak()) doc = SimpleDocTemplate(url) doc.multiBuild(Report, canvasmaker=PageNumCanvas) return url
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 csv_to_db(csv_path): conn = psycopg2.connect("host=localhost dbname=postgres user=postgres") cur = conn.cursor() cur.execute("""DELETE FROM users;""") cur.execute(""" CREATE TABLE IF NOT EXISTS users( name text, surname text, company text, title text, dateofbirth text, photo text ) """) with open(csv_path, 'r') as csv_file: cur.copy_from(csv_file, 'users', sep=',') cur.execute(""" SELECT * FROM users ORDER BY company ASC, title ASC; """) rows = cur.fetchall() doc = SimpleDocTemplate("list_of_people.pdf", pagesize=A4, rightMargin=30, leftMargin=20, topMargin=30, bottomMargin=18) pdf_elements = [] s = getSampleStyleSheet() s = s["BodyText"] data_rows = [('NAME', 'SURNAME', 'COMPANY', 'TITLE', 'DOB', 'PHOTO'), ] for row in rows: img = urllib.urlretrieve(row[5], "pic of {} {}.jpg".format(row[0], row[1])) watermark = str(row[0]) edit_image("pic of {} {}.jpg".format(row[0], row[1]), watermark) I = Image("pic of {} {}.jpg".format(row[0], row[1])) data_rows.append((row[0], row[1], Paragraph(row[2], s), Paragraph(row[3], s), row[4], I),) main_table_from_db = LongTable(data_rows, 5 * [1 * inch], len(data_rows) * [1 * inch], repeatRows=1, splitByRow=1) main_table_from_db.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) cur.execute("""SELECT company, COUNT(company) FROM users GROUP BY company""") table_of_people = cur.fetchall() people_in_company = [] for row in table_of_people: people_in_company.append((Paragraph(row[0], s), row[1]),) people_in_company = [('COMPANY', Paragraph('NUMBER OF EMPLOYEES', s)), ] + people_in_company table_for_employees_amount = Table(people_in_company, 5 * [1 * inch], len(people_in_company) * [0.4 * inch]) table_for_employees_amount.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) pdf_elements.append(main_table_from_db) pdf_elements.append(Spacer(1, 30)) pdf_elements.append(table_for_employees_amount) doc.build(pdf_elements) conn.commit()
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 generate_report(data): ip = str(data['camInfo']['ip']) port = str(data['camInfo']['port']) cam = 'Device Under Test: ' + ip + ':' + port mycam = ONVIFCamera(ip, int(port), str(data['camInfo']['username']), str(data['camInfo']['password'])) device_info = mycam.devicemgmt.GetDeviceInformation() manufacturer = 'Manufacturer: {}\n'.format(device_info.Manufacturer) model = 'Model: {}\n'.format(device_info.Model) firmware = 'Firmware Version: {}\n'.format(device_info.FirmwareVersion) serial = 'Serial Number: {}\n'.format(device_info.SerialNumber) hardware = 'Hardware ID: {}\n'.format(device_info.HardwareId) test_time = 'Report generated: ' + str( datetime.now().strftime('%Y-%m-%d %H:%M:%S')) testsResults = data['runnedTests'] img_url = '.' + data['camInfo']['snapshot_url'] url = 'reports/' + ip + ':' + port + '.' + str( datetime.now().strftime('%Y-%m-%d:%H:%M:%S')) + '.pdf' print_cam_response = data['printResponses'] styles = getSampleStyleSheet() centered = PS(name='centered', fontSize=14, leading=16, alignment=1, spaceAfter=10) bold = PS(name='bold', fontName='Helvetica-Bold', fontSize=14, leading=16) centered_bold = PS(name='centered_bold', fontSize=14, fontName='Helvetica-Bold', leading=16, alignment=1, spaceAfter=10) h2 = PS(name='Heading2', fontSize=12, leading=14) def define_nvt_class(cam): types = [] profiles = [] scopes = cam.devicemgmt.GetScopes() for item in scopes: groupe = re.findall(r'onvif:\/\/www\.onvif\.org\/(.*)\/(.*)', item.ScopeItem) if groupe[0][0] == 'type': types.append(str(groupe[0][1]).capitalize()) if groupe[0][0] == 'Profile' or groupe[0][0] == 'profile': profiles.append(str(groupe[0][1]).capitalize()) profiles_verdict = ( ", ".join(profiles)) if len(profiles) > 0 else 'Not Specified' return 'Device Class: {}; Profiles: {}'.format((", ".join(types)), profiles_verdict) Report = [] Report.append(Paragraph('ONVIF COMPLIANCE TESTER', centered_bold)) Report.append(Spacer(1, 12)) Report.append(Spacer(1, 12)) im = Image(img_url, 5 * inch, 3 * inch) Report.append(im) Report.append(Spacer(1, 12)) Report.append(Spacer(1, 12)) Report.append(Paragraph('REPORT DATASHEET', centered_bold)) Report.append(Spacer(1, 12)) Report.append(Spacer(1, 12)) Report.append(Paragraph(cam, centered)) Report.append(Paragraph(define_nvt_class(mycam), centered)) Report.append(Paragraph(test_time, centered)) Report.append(Spacer(1, 12)) Report.append(Paragraph(manufacturer, centered)) Report.append(Paragraph(model, centered)) Report.append(Paragraph(serial, centered)) Report.append(Paragraph(firmware, centered)) Report.append(Paragraph(hardware, centered)) logo = Image( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logo.png')) Report.append(TopPadder(logo)) Report.append(PageBreak()) Report.append(Paragraph('<b>Table of contents</b>', centered)) toc = TableOfContents() toc.levelStyles = [ PS(fontName='Times-Bold', fontSize=14, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10, leading=16), PS(fontSize=12, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12), ] Report.append(toc) Report.append(PageBreak()) styleN = styles['Normal'] styleN.wordWrap = 'CJK' def doHeading(text, sty): from hashlib import sha1 bn = sha1(text + sty.name).hexdigest() h = Paragraph(text + '<a name="%s"/>' % bn, sty) h._bookmarkName = bn Report.append(h) for item in testsResults.keys(): doHeading('{} Service Features'.format(item.capitalize()), h2) Report.append(Spacer(1, 12)) data = [] data.append(['Features', 'Description']) for response in testsResults[item]: if response['data']['result']['supported'] == False: report = 'Not Supported' else: try: response['data']['result']['report'] report = response['data']['result']['report'] except: report = 'Supported' data.append([ response['data']['result']['report_name'], report.replace('\n', '<br/>') ]) data_proccessed = [[Paragraph(cell, styleN) for cell in row] for row in data] table = LongTable(data_proccessed, colWidths=['30%', '70%']) table.setStyle( TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 0.5, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.gray), ('ALIGN', (0, 0), (-1, -0), 'CENTER')])) Report.append(table) Report.append(Spacer(1, 12)) def printResponses(testsResults): for item in testsResults.keys(): doHeading('{} Service Responses'.format(item.capitalize()), h2) Report.append(Spacer(1, 12)) for response in testsResults[item]: if response["data"]["name"]: ptext = "Test: " + str(response["data"]["name"]) else: ptext = "Test: " + "NameError" if response["data"]["result"]["supported"]: flag = response["data"]["result"]["supported"] if (flag == False): sutext = str(response["data"]["name"] + ' is not supported') else: sutext = str(response["data"]["name"] + ' is supported') else: sutext = str(response["data"]["result"]["report"]) if response["data"]["result"]["response"]: rtext = "Response: " + str( json.dumps( response["data"]["result"]["response"].replace( '\n', '<br/>').replace('\"', '').replace( ' ', ' '), sort_keys=True, indent=4)) else: rtext = "Response: " + "None" Report.append(Paragraph(ptext, h2)) Report.append(Spacer(1, 8)) if (sutext is not None): Report.append( Paragraph("<font size=10>%s</font>" % ptext, styles["Normal"], bulletText=u'\u25cf')) Report.append(Spacer(1, 8)) if ((response["data"]["result"]["response"]) or (len(response["data"]["result"]["response"]) != 0)): Report.append( Paragraph("<font size=10>%s</font>" % rtext, styles["Normal"], bulletText=u'\u25cf')) Report.append(Spacer(1, 8)) Report.append(Spacer(1, 12)) if (print_cam_response == True): Report.append(PageBreak()) printResponses(testsResults) Report.append(PageBreak()) doc = MyDocTemplate(url, pagesize=A4, rightMargin=15 * mm, leftMargin=15 * mm, topMargin=15 * mm, bottomMargin=15 * mm) doc.multiBuild(Report, canvasmaker=PageNumCanvas) return url
def build_table(self): colwidths = [30, 70, 55, 100, 60, 65, 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>Zustand</b>", style=size_nine_helvetica), Paragraph("<b>Bezeichnung</b>", style=size_nine_helvetica), Paragraph("<b>Menge</b>", style=right_align_paragraph_style), Paragraph("<b>Einzelpreis</b>", style=right_align_paragraph_style), Paragraph("<b>Betrag</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.state, style=size_nine_helvetica), Paragraph(productmission.product.title or "", style=size_nine_helvetica), Paragraph(str(productmission.amount), style=right_align_paragraph_style), Paragraph(format_number_thousand_decimal_points(productmission.netto_price), style=right_align_paragraph_style), Paragraph(format_number_thousand_decimal_points( (productmission.netto_price * 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"), ]) ) total_netto = 0 for productmission in self.mission.productmission_set.all(): total_netto += productmission.amount * productmission.netto_price horizontal_line_betrag = Drawing(20, 1) horizontal_line_betrag.add(Line(425, 0, 200, 0)) betrag_data = [ [ Paragraph(f"Nettobetrag", style=right_align_paragraph_style), Paragraph(f"{format_number_thousand_decimal_points(total_netto)} €", style=right_align_paragraph_style), ], [ Paragraph(f"+ Umsatzsteuer (19,00%)", style=right_align_paragraph_style), Paragraph(f"{format_number_thousand_decimal_points(total_netto*0.19)} €", style=right_align_paragraph_style), ], [ horizontal_line_betrag, ], [ Paragraph(f"GESAMT", style=right_align_bold_paragraph_style), Paragraph(f"{format_number_thousand_decimal_points(total_netto+(total_netto*0.19))} €", style=right_align_bold_paragraph_style), ] ] betrag_table = Table(betrag_data, colWidths=[None, 70, 75]) betrag_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, KeepTogether(betrag_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
def pdf_generate(user_pk): user = User.objects.get(pk=user_pk) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=landscape(legal), verbosity=1, leftMargin=0.25 * inch, rightMargin=0.25 * inch, topMargin=0.5 * inch, bottomMargin=1.25 * inch) styles = getSampleStyleSheet() story = [] def entry(object, flight): if not object or object is False: entry = '-' elif object is True: entry = str(flight.duration) else: entry = str(object) return entry # cover page starts here def title_page(canvas, doc): canvas.saveState() canvas.drawImage('pdf_output/wings.png', 103, 205, width=800, height=229) canvas.setFont('Helvetica-Oblique', 7) canvas.drawString( 800, 30, "Powered by Direct2Logbook.com and ReportLab") canvas.setFont('Helvetica', 10) page_number_text = "%d" % (doc.page) canvas.drawCentredString( 14 * inch / 2, 30, page_number_text ) canvas.restoreState() def add_later_page_number(canvas, doc): canvas.saveState() canvas.setFont('Helvetica-Oblique', 7) canvas.drawString( 800, 30, "Powered by Direct2Logbook.com and ReportLab") if Signature.objects.filter(user=user).exists(): sig = Signature.objects.get(user=user) signature_path = sig.signature.url canvas.drawImage(str(signature_path), 240, 50, width=100, height=40) else: None canvas.setFont('Helvetica', 10) canvas.drawString( 30, 50, "I certify that the entries in this logbook are true.") canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.line(240, 50, 480, 50) canvas.setFont('Helvetica', 10) page_number_text = "%d" % (doc.page) canvas.drawCentredString( 14 * inch / 2, 30, page_number_text ) canvas.restoreState() spacer15 = Spacer(1, 1.5 * inch) spacer025 = Spacer(1, .25 * inch) story.append(spacer15) story.append(spacer025) text = "<para size=50 align=center>Logbook for {} {}</para>".format( user.first_name, user.last_name) title = Paragraph(text, style=styles["Normal"]) story.append(title) story.append(spacer15) story.append(spacer15) text = "<para size=15 align=center>Data current as of {}</para>".format( datetime.date.today().strftime("%m/%d/%Y")) title = Paragraph(text, style=styles["Normal"]) story.append(title) story.append(PageBreak()) # summary page starts here spacer = Spacer(1, 0.25 * inch) text = "<para size=15 align=left><u><b>Category and Class Summary</b></u></para>" cat_class_title = Paragraph(text, style=styles["Normal"]) story.append(cat_class_title) story.append(spacer) # total table total_objects = Total.objects.filter(user=user) totals_that_exist = [] for total in total_objects: if total.total_time > 0.0: totals_that_exist.append(str(total.total)) total_data = [] for total in totals_that_exist: total = Total.objects.filter(user=user).get(total=total) row = [str(total.total), str(total.total_time), str(total.pilot_in_command), str(total.second_in_command), str(total.cross_country), str(total.instructor), str(total.dual), str(total.solo), str( total.instrument), str(total.night), str(total.simulated_instrument), str(total.simulator), str(total.landings_day), str( total.landings_night), str(total.landings_day + total.landings_night), str(total.last_flown.strftime("%m/%d/%Y")), str(total.last_30), str( total.last_60), str(total.last_90), str(total.last_180), str(total.last_yr), str(total.last_2yr), str(total.ytd)] total_data.append(row) total_header = ["Cat/Class", "Time", "PIC", "SIC", "XC", "CFI", "Dual", "Solo", "IFR", "Night", "Hood", "Sim", "D Ldg", "N Ldg", "Total Ldg", "Last Flown", "30", "60", "90", "6mo", "1yr", "2yr", "Ytd"] total_data.insert(0, total_header) total_table = Table(total_data, hAlign='LEFT') cat_class_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) total_table.setStyle(cat_class_tablestyle) story.append(total_table) story.append(spacer) # misc tables start here # role_table role_objects = Power.objects.filter(user=user) role_data = [] for role in role_objects: row = [str(role.role), str(role.turbine), str(role.piston)] role_data.append(row) role_header = ["Role", "Turbine", "Piston"] role_data.insert(0, role_header) role_table = Table(role_data, hAlign="LEFT") role_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) role_table.setStyle(role_tablestyle) # regs_table regs_objects = Regs.objects.filter(user=user) regs_data = [] for regs in regs_objects: row = [str(regs.reg_type), str(regs.pilot_in_command), str(regs.second_in_command)] regs_data.append(row) regs_header = ["FAR", "PIC", "SIC"] regs_data.insert(0, regs_header) regs_table = Table(regs_data, hAlign='LEFT') reg_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ]) regs_table.setStyle(reg_tablestyle) # weight_table weight_objects = Weight.objects.filter(user=user) weights_that_exist = [] for weight in weight_objects: if weight.total > 0.0: weights_that_exist.append(weight) weight_data = [] for weight in weights_that_exist: row = [str(weight.weight), str(weight.total)] weight_data.append(row) weight_header = ['Weight', 'Total'] weight_data.insert(0, weight_header) weight_table = Table(weight_data, hAlign='LEFT') weight_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) weight_table.setStyle(weight_tablestyle) # endoresment_table endorsement_objects = Endorsement.objects.filter(user=user) endorsements_that_exist = [] for endorsement in endorsement_objects: if endorsement.total > 0.0: endorsements_that_exist.append(endorsement) endorsement_data = [] for endorsement in endorsements_that_exist: row = [str(endorsement.endorsement), str(endorsement.total)] endorsement_data.append(row) endorsement_header = ['Endorsement', 'Total'] endorsement_data.insert(0, endorsement_header) endorsement_table = Table(endorsement_data, hAlign='LEFT') endorsement_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) endorsement_table.setStyle(endorsement_tablestyle) # misc_table text = "<para size=15 align=left><u><b>Misc Summary</b></u></para>" misc_title = Paragraph(text, style=styles["Normal"]) story.append(misc_title) story.append(spacer) misc_data = [ [role_table, regs_table, weight_table, endorsement_table] ] misc_table = Table(misc_data, hAlign="LEFT") story.append(misc_table) story.append(spacer) # aircraft stats table text = "<para size=15 align=left><u><b>Aircraft Summary</b></u></para>" aircraft_stats_title = Paragraph(text, style=styles["Normal"]) story.append(aircraft_stats_title) story.append(spacer) stat_objects = Stat.objects.filter(user=user) stat_data = [] for stat in stat_objects: # avoids None failure when user hasn't logged time in aircraft date_condition = [stat.last_flown, stat.last_30, stat.last_60, stat.last_90, stat.last_180, stat.last_yr, stat.last_2yr, stat.ytd] if None not in date_condition: row = [str(stat.aircraft_type), str(stat.total_time), str(stat.pilot_in_command), str(stat.second_in_command), str(stat.cross_country), str(stat.instructor), str(stat.dual), str(stat.solo), str( stat.instrument), str(stat.night), str(stat.simulated_instrument), str(stat.simulator), str( stat.landings_day), str(stat.landings_night), str(stat.last_flown.strftime("%m/%d/%Y")), str(stat.last_30), str( stat.last_60), str(stat.last_90), str(stat.last_180), str(stat.last_yr), str(stat.last_2yr), str(stat.ytd)] stat_data.append(row) else: pass stat_header = ["Type", "Time", "PIC", "SIC", "XC", "CFI", "Dual", "Solo", "IFR", "Night", "Hood", "Sim", "D Ldg", "N Ldg", "Last Flown", "30", "60", "90", "6mo", "1yr", "2yr", "Ytd"] stat_data.insert(0, stat_header) stat_table = Table(stat_data, repeatRows=(1), hAlign='LEFT') stat_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) stat_table.setStyle(stat_tablestyle) story.append(stat_table) story.append(spacer) # story.append(PageBreak()) # logbook starts here if os.getenv('DEBUG') is True: flight_objects = Flight.objects.filter(user=user).order_by('-date')[:100] else: flight_objects = Flight.objects.filter(user=user).order_by('-date') logbook_data = [] logbook_header = ['Date', 'Type', 'Reg', 'Route', 'Block', 'PIC', 'SIC', 'XC', 'Night', 'IFR', 'Appr', 'Hold', 'D Ldg', 'N Ldg', 'Hood', 'CFI', 'Dual', 'Solo', 'Sim'] for flight in flight_objects: date = flight.date Date = date.strftime("%m/%d/%Y") PIC = entry(flight.pilot_in_command, flight) SIC = entry(flight.second_in_command, flight) XC = entry(flight.cross_country, flight) Night = entry(flight.night, flight) IFR = entry(flight.instrument, flight) CFI = entry(flight.instructor, flight) Dual = entry(flight.dual, flight) Solo = entry(flight.solo, flight) Sim = entry(flight.simulator, flight) Day_LDG = entry(flight.landings_day, flight) Night_LDG = entry(flight.landings_night, flight) Hood = entry(flight.simulated_instrument, flight) appr = '' for approach in flight.approach_set.all(): appr = appr + str(approach.approach_type) + \ '-' + str(approach.number) + ' ' hold = '' for holding in flight.holding_set.all(): if holding.hold: hold = 'Yes' else: hold = '-' row = [Date, str(flight.aircraft_type), str(flight.registration), str(flight.route), str( flight.duration), PIC, SIC, XC, Night, IFR, appr, hold, Day_LDG, Night_LDG, Hood, CFI, Dual, Solo, Sim] logbook_data.append(row) logbook_data.insert(0, logbook_header) logbook_table = LongTable(logbook_data, repeatRows=(1), hAlign='LEFT') logbook_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (4, 0), (-1, -1), 'RIGHT'), ]) logbook_table.setStyle(logbook_tablestyle) styles = getSampleStyleSheet() text = "<para size=15 align=left><u><b>Logbook</b></u></para>" logbook_title = Paragraph(text, style=styles["Normal"]) story.append(logbook_title) story.append(spacer) story.append(logbook_table) # build pdf # doc.multiBuild(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc.multiBuild(story, onFirstPage=title_page, onLaterPages=add_later_page_number) # doc.build(story) # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() # email message/attachment subject = "Logbook for {} {}".format(user.first_name, user.last_name) user_email = user.email email = EmailMessage( subject, 'Good luck on your interview!', '*****@*****.**', [user_email], reply_to=['*****@*****.**'], headers={'Message-ID': 'logbook'}, ) email.attach('Logbook.pdf', pdf, 'application/pdf') email.send() return None
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 buildXRef(self): fields = [] for plate in self.study.plateList(): if self.plateFilter and \ not self.plateFilter.contains(plate.number()): continue for field in plate.fieldList(): bb = field.boundingBox() if bb is None: continue fields.append((field, plate)) fields.sort( key=lambda x: (x[0].name.lower(), x[1].number(), x[0].number)) styles = stylesheet() styleN = styles['default'] styleT = styles['title'] cols = [] xrefs = [] firstChar = None tablestyle = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, -1), 1, lightgrey) ]) for field, plate in fields: if firstChar != field.name[0]: if firstChar is not None: table = LongTable(cols, colWidths=[65, 90, 32, 32], splitByRow=1, repeatRows=2, hAlign='LEFT') table.setStyle(tablestyle) xrefs.append(table) xrefs.append(Spacer(0, 20)) cols = [] cols.append([ Paragraph('{0}'.format(field.name[0].upper()), styleT), Paragraph('', styleN), Paragraph('', styleN), Paragraph('', styleN) ]) cols.append([ Paragraph('<b>Name</b>', styleN), Paragraph('<b>Description</b>', styleN), Paragraph('<para alignment="right"><b>Plate</b></para>', styleN), Paragraph('<para alignment="right"><b>Field</b></para>', styleN) ]) firstChar = field.name[0] description = field.description if description is None: description = '' bookmark = '#P{0}F{1}'.format(plate.number(), field.number) cols.append([ Paragraph( '<a href="{0}" color="blue">{1}</a>'.format( bookmark, field.name), styleN), Paragraph(description, styleN), Paragraph( '<para alignment="right">{0}</para>'.format( plate.number()), styleN), Paragraph( '<para alignment="right">{0}</para>'.format(field.number), styleN) ]), if len(cols): table = LongTable(cols, colWidths=[65, 90, 32, 32], splitByRow=1, repeatRows=2, hAlign='LEFT') table.setStyle(tablestyle) xrefs.append(table) return xrefs
# ['<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 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
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 make_table(data, widths, style=[]): table = LongTable(data, colWidths=widths) table.setStyle(TableStyle(style)) return table
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