def childreport(request, children, style_sheet=None): """ Takes a list of children and prints them out 4 at a time """ doct = doctemplate.SimpleDocTemplate(os.path.join(settings.TMP_DIR, 'child_report.pdf'), pagesize=A4) style = GRID_STYLE style.add(*('VALIGN', (0, 0), (-1, -1), 'MIDDLE')) style.add(*('LEFTPADDING', (0, 0), (-1, -1), 15)) style.add(*('RIGHTPADDING', (0, 0), (-1, -1), 15)) children = [ii for ii in children] num_pages = ceil(len(children) / 4.0) data = [] page_flowables = [] for ii in range(len(children)): data.append(child_report_data(children[ii], style_sheet=style_sheet)) col_table = lambda x: LongTable(x, colWidths=[100, 150], style=style) for ii in range(int(num_pages)): try: col11 = col_table(data[4 * ii]) except IndexError: col11 = Spacer(2, 2) try: col12 = col_table(data[4 * ii + 1]) except IndexError: col12 = Spacer(2, 2) try: col21 = col_table(data[4 * ii + 2]) except IndexError: col21 = Spacer(2, 2) try: col22 = col_table(data[4 * ii + 3]) except IndexError: col22 = Spacer(2, 2) page_table = LongTable([ [col11, Spacer(2, 0), col12], [col21, Spacer(2, 0), col22], ]) page_flowables.append(page_table) doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Child report"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=child_report.pdf" return response
def append_to_pdf(self, story): data = [[ '#', _('Last Name'), _('First Name'), _('Group'), _('Type'), _('Committee') ]] if config['participant_sort_users_by_first_name']: sort = 'first_name' else: sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): counter += 1 data.append([ counter, Paragraph(user.last_name, stylesheet['Tablecell']), Paragraph(user.first_name, stylesheet['Tablecell']), Paragraph(user.structure_level, stylesheet['Tablecell']), Paragraph(user.get_type_display(), stylesheet['Tablecell']), Paragraph(user.committee, stylesheet['Tablecell']) ]) t = LongTable(data, style=[('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm story.append(t)
def printstats(request, style_sheet=None): """ Prints a list of sponsors and children """ doct = doctemplate.SimpleDocTemplate(os.path.join(settings.TMP_DIR, 'proj_stats.pdf'), pagesize=A4) normal_para = lambda x: Paragraph(unicode(x), style=style_sheet["Normal"]) data = [ map(normal_para, [_("Sponsor Number"), _("Sponsor"), _("Child Number"), _("Child")]) ] sponsorships = Sponsorship.objects.filter( iscurrent=True).order_by('sponsor') for sponsorship in sponsorships: row = map(normal_para, (sponsorship.sponsor.code, u"%s %s" % (sponsorship.sponsor.fname, sponsorship.sponsor.lname), sponsorship.child.code, sponsorship.child.name)) data.append(row) table = LongTable(data, style=GRID_STYLE) page_flowables = [table] doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Statistics"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=stats.pdf" return response
def create(self, destination): doc = SimpleDocTemplate(destination, pagesize=A4) story = [] styles = self.para_style() comm_style = styles['CommunityName'] h5 = self.style['Heading5'] story.append(Paragraph("Community Accrual Report", styles['ReportName'])) container_data = [[Paragraph(self.community1, comm_style), Paragraph(self.community2, comm_style)], [Paragraph(self.date_range, h5), Paragraph(self.date_range, h5)]] report_style = self.inner_style() tables_data = [] for community_data in [self.data1, self.data2]: table_data, added_styles = self.community_table_data(community_data) tables_data.append(table_data) tables = [] report_style.extend(added_styles) for report_data in tables_data: table = LongTable(report_data, repeatRows=1) table.setStyle(report_style) tables.append(table) container_data.append(tables) container_table = Table(container_data, 2 * [3.6 * inch]) container_table.setStyle(TableStyle([ ('LINEABOVE', (0, 0), (-1, 0), 0.5, colors.HexColor('#ed4694')), ])) story.append(container_table) doc.build(story)
def append_to_pdf(self, story): data = [['#', _('Title'), _('Last Name'), _('First Name'), _('Structure level'), _('Group'), _('Committee')]] if config['participant_sort_users_by_first_name']: sort = 'first_name' else: sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): counter += 1 groups = '' for group in user.groups.all(): if group.pk != 2: groups += "%s<br/>" % unicode(_(group.name)) data.append([ counter, Paragraph(user.title, stylesheet['Tablecell']), Paragraph(user.last_name, stylesheet['Tablecell']), Paragraph(user.first_name, stylesheet['Tablecell']), Paragraph(user.structure_level, stylesheet['Tablecell']), Paragraph(groups, stylesheet['Tablecell']), Paragraph(user.committee, stylesheet['Tablecell'])]) t = LongTable(data, style=[ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm story.append(t)
def create_table(table_data: List[Tuple]) -> LongTable: """ Returns a table of the input data. """ table = LongTable(table_data, spaceAfter=5, spaceBefore=5) return table
def addTable(self,ndata,nkeys=None): data = [] if not nkeys: keys = self.hlib.getKeys(ndata) data.append(keys) else: keys = nkeys data.append(nkeys) for x in ndata: lister = [] for b in range(len(keys)): if keys[b] not in x: outb = None else: outb = x[keys[b]] t = Paragraph(str(outb),self.styles["Normal"]) lister.append(t) data.append(lister) tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('BOX',(0,0),(-1,-1),1,black), ('INNERGRID',(0,0),(-1,-1),1,black), ('BACKGROUND',(0,0),(-1,0),lightblue)]) t = LongTable(data,repeatRows=1) t.setStyle(tblStyle) self.story.append(t) self.story.append(CondPageBreak(6))
def 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 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 emp_report_mini(): Upload.emp_report_status.config(text='Running') try: data1 = pd.read_excel('Database/tmp_Report.xlsx') data2 = pd.read_excel('Database/Report.xlsx') cols = data1.columns data1 = data1.values.tolist() data2 = data2.values.tolist() data = [] for i in range(len(data1)): data.append(cols) data.append(data1[i]) data.append(data2[i]) data.append([]) output = OUTPUT_PATH + 'Emp_Report.pdf' elements = [] doc = SimpleDocTemplate(output, pagesize=landscape(A4)) t = LongTable(data, repeatRows=1) elements.append(t) doc.build(elements) except: Upload.emp_report_status.config(text='Error') sleep(1) Upload.emp_report_status.config(text='K')
def temp_f(data, y): cols = data.columns data = data.values.tolist() data.insert(0, cols) output = OUTPUT_PATH + y + '.pdf' elements = [] doc = SimpleDocTemplate(output, pagesize=landscape(A4)) t = LongTable(data, repeatRows=1) elements.append(t) doc.build(elements)
def 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 full_report_mini(x, y): try: data = pd.read_excel(x) cols = data.columns data = data.values.tolist() data.insert(0, cols) output = OUTPUT_PATH + y elements = [] doc = SimpleDocTemplate(output, pagesize=landscape(A4)) t = LongTable(data, repeatRows=1) elements.append(t) doc.build(elements) except: Upload.full_report_status.config(text='Error') sleep(1) Upload.full_report_status.config(text='K')
def 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 textAccum1(): doc = MyDocTemplate(outputfile('test_platypus_accum1.pdf'), pagesize=(8.5 * inch, 11 * inch), showBoundary=1) story = [] story.append(Paragraph("A table with 500 rows", styleSheet['BodyText'])) sty = [ ('GRID', (0, 0), (-1, -1), 1, colors.green), ('BOX', (0, 0), (-1, -1), 2, colors.red), ] data = [[ str(i + 1), Paragraph("xx " * (i % 10), styleSheet["BodyText"]), Paragraph(("blah " * (i % 40)) + PA.onDrawText(i + 1), styleSheet["BodyText"]) ] for i in range(500)] t = LongTable(data, style=sty, colWidths=[50, 100, 200]) story.append(t) doc.build(story)
def users_to_pdf(pdf): """ Create a list of all users as PDF. """ data = [['#', _('Name'), _('Structure level'), _('Group')]] if config['users_sort_users_by_first_name']: sort = 'first_name' else: sort = 'last_name' counter = 0 for user in User.objects.all().order_by(sort): counter += 1 groups = '' for group in user.groups.all(): if group.pk != 2: groups += "%s<br/>" % escape(_(group.name)) if sort == 'last_name': name = "%s" % escape(user.last_name) if user.first_name: name = "%s, %s" % (name, escape(user.first_name)) else: name = "%s %s" % (escape(user.first_name), escape(user.last_name)) if user.title: name = "%s %s" % (user.title, name) if user.number: name = "%s<br/>%s" % (name, user.number) data.append([ counter, Paragraph(name, stylesheet['Tablecell']), Paragraph(escape(user.structure_level), stylesheet['Tablecell']), Paragraph(groups, stylesheet['Tablecell']) ]) t = LongTable(data, style=[('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black), ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))]) t._argW[0] = 0.75 * cm pdf.append(t) return pdf
def invoice_generator(request, invoice_id): """ Prints a list of sponsors and children """ out_file_path = "somefilename.pdf" invoices = models.Invoice.objects.all() doct = SimpleDocTemplate(out_file_path) style_sheet = getSampleStyleSheet() normal_para = lambda x: Paragraph(unicode(x), style=style_sheet["Normal"]) data = [ map(normal_para, [_("Invoice Number"), _("Date"), _("Total Amount"), _("Customer")]) ] for invoice in invoices: row = map(normal_para, (invoice.invoice_no, u"%s %s" % (invoice.date, invoice.customer), invoice.total_amount, invoice.management_employee)) data.append(row) table = LongTable(data, style=GRID_STYLE) page_flowables = [table] doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Invoices"))) print canvas.getpdfdata() output_file = out_file_path.split('/')[-1] print "output_file", output_file #fs = FileSystemStorage(out_file_path) with open(out_file_path) as pdf: response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=%s' % smart_str( output_file) return response return response
def sponsoraddress(request, sponsors, style_sheet=None): """ Takes a list of sponsors and prints them out 12 at a time """ doct = doctemplate.SimpleDocTemplate(os.path.join(settings.TMP_DIR, 'sponsors_list.pdf'), pagesize=A4) style = GRID_STYLE style.add(*('VALIGN', (0, 0), (-1, -1), 'MIDDLE')) style.add(*('LEFTPADDING', (0, 0), (-1, -1), 15)) style.add(*('RIGHTPADDING', (0, 0), (-1, -1), 15)) data = [] normal_para = lambda x: Paragraph(x, style=style_sheet["Normal"]) sponsors = [Sponsor.objects.get(pk=ii) for ii in sponsors] sponsor_rows = ceil(len(sponsors) / 2.0) for ii in range(int(sponsor_rows)): try: col1 = normal_para( "%s %s<br />%s<br />%s" "<br />%s<br />%s" % (sponsors[2 * ii].fname, sponsors[2 * ii].lname, sponsors[2 * ii].street, sponsors[2 * ii].postal, sponsors[2 * ii].city, sponsors[2 * ii].country)) col2 = normal_para( "%s %s<br />%s<br />%s" "<br />%s<br />%s" % (sponsors[2 * ii + 1].fname, sponsors[2 * ii + 1].lname, sponsors[2 * ii + 1].street, sponsors[2 * ii + 1].postal, sponsors[2 * ii + 1].city, sponsors[2 * ii + 1].country)) except IndexError: continue data.append([col1, col2]) sponsor_table = LongTable(data, style=style) page_flowables = [sponsor_table] doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Sponsors List"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=sponsors_list.pdf" return response
def all_words_marking_table(working_dir): query = DataExtrator(working_dir) analyzer = MessagesAnalyzer() analyzer.calculate_words(query.get_sms_list()) all_words_list = analyzer.all_words #print(all_words_list) data_tmp = list(all_words_list) data = [['Word', 'Times repeated']] for i in data_tmp: tmp = [] for j in i: tmp.append(str(j)) data.append(tmp) tableStyle = [ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BACKGROUND', (0, 0), (5, 0), colors.lightgreen) ] styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.wordWrap = 'CJK' data2 = [[Paragraph(cell, styleN) for cell in row] for row in data] colwidths = [3*cm, 1.85*cm] tableWords = LongTable(data2, colWidths=colwidths, repeatRows=1) tableWords.setStyle(TableStyle(tableStyle)) return tableWords
def addTable(self, ndata): data = [] keys = self.getKeys(ndata) data.append(keys) for x in ndata: lister = [] for b in keys: outb = ndata[b] t = Paragraph(str(outb), self.styles["Normal"]) lister.append(t) data.append(lister) tblStyle = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('BOX', (0, 0), (-1, -1), 1, black), ('INNERGRID', (0, 0), (-1, -1), 1, black), ('BACKGROUND', (0, 0), (-1, 0), lightblue)]) t = LongTable(data, repeatRows=1) t.setStyle(tblStyle) self.story.append(t) self.story.append(CondPageBreak(6))
def printchildstory(request, children, style_sheet=None): doct = doctemplate.SimpleDocTemplate(os.path.join(settings.TMP_DIR, 'child_story.pdf'), pagesize=landscape(A4)) data = [] row = [] for child in children: try: child_story = ChildStory.objects.get(child=child) except ChildStory.DoesNotExist: child_story = None story_content = child_story and child_story.story or '-' if story_content: story_content = story_content.replace( '</p>', '</p><br /><br />', story_content.count('</p>') - 1) row.append((Paragraph(unicode(child_story or '-'), style=style_sheet["Title"]), Paragraph(story_content, style=style_sheet["Normal"]))) if len(row) == 2: data.append(row) row = [] if row: data.append(row) style = GRID_STYLE style.add(*('VALIGN', (0, 0), (-1, -1), 'MIDDLE')) style.add(*('LEFTPADDING', (0, 0), (-1, -1), 15)) style.add(*('RIGHTPADDING', (0, 0), (-1, -1), 15)) table = LongTable(data, colWidths=360, rowHeights=215, style=style) page_flowables = [table] doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Child Stories"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=child_story.pdf" return response
def textAccum2(): doc = MyDocTemplate(outputfile('test_platypus_accum2.pdf'), pagesize=(8.5 * inch, 11 * inch), showBoundary=1) story = [] story.append(Paragraph("A table with 500 rows", styleSheet['BodyText'])) sty = [ ('GRID', (0, 0), (-1, -1), 1, colors.green), ('BOX', (0, 0), (-1, -1), 2, colors.red), ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'), ('FONTSIZE', (0, 0), (-1, -1), 10), ] def myCV(s, fontName='Helvetica', fontSize=10, maxWidth=72): return '\n'.join(simpleSplit(s, fontName, fontSize, maxWidth)) data = [[ PA.onDrawStr(str(i + 1), i + 1), myCV("xx " * (i % 10), maxWidth=100 - 12), myCV("blah " * (i % 40), maxWidth=200 - 12) ] for i in range(500)] t = LongTable(data, style=sty, colWidths=[50, 100, 200]) story.append(t) doc.build(story)
def printannualreport(request, children, style_sheet=None): """ prints annual report of the selected children """ doct = doctemplate.SimpleDocTemplate(os.path.join(settings.TMP_DIR, 'annual_report.pdf'), pagesize=A4) style = GRID_STYLE style.add(*('VALIGN', (0, 0), (-1, -1), 'MIDDLE')) style.add(*('LEFTPADDING', (0, 0), (-1, -1), 15)) style.add(*('RIGHTPADDING', (0, 0), (-1, -1), 15)) img = Image(os.path.join(settings.MEDIA_ROOT, "pics/fidalogo.jpg"), width=100, height=60) page_title = Paragraph(_(u"Annual Sponsorship child report"), style=style_sheet["Heading1"]) project_name = Paragraph(_(unicode(settings.PROJECT_NAME)), style=style_sheet["Heading3"]) normal_para = lambda x: Paragraph(unicode(x), style=style_sheet["Normal"]) child_data_heading = Paragraph(_(u"General information about the child"), style=style_sheet["Heading3"]) child_health_heading = Paragraph( _(u"Information about the child's health"), style=style_sheet["Heading3"]) children_row = [] children_health_row = [] for child in children: child_row = [] health_row = [] child_row.append((normal_para(_(u"Name")), normal_para(child.name))) child_row.append( (normal_para(_(u"Child number")), normal_para(child.code))) child_row.append( (normal_para(_(u"Village area")), normal_para(child.area))) child_row.append( (normal_para(_(u"Sex")), normal_para(child.get_sex_display()))) child_row.append((normal_para(_(u"Date of birth")), normal_para(child.dob.strftime("%d-%m-%Y")))) child_row.append((normal_para(_(u"Language")), normal_para(child.language.name or "-"))) child_row.append((normal_para(_(u"Religion")), normal_para(child.get_religion_display()))) child_row.append((normal_para(_(u"Character")), normal_para( _(u", ".join([ unicode(hob.name) for hob in child.character.all() if hob.name ]))))) child_row.append((normal_para(_(u"School standard")), normal_para(child.schoolstd.name or "-"))) child_row.append((normal_para(_(u"School performance")), normal_para(child.get_schoolperf_display()))) child_row.append( (normal_para(_(u"Free time")), normal_para(u", ".join([ unicode(hob.name) for hob in child.hobbies.all() if hob.name ]).capitalize()))) checkup_exists = Checkup.objects.filter( child=child.id).order_by('-chkdate') checkup_child = None if checkup_exists.count(): checkup_child = checkup_exists[0] health_row.append([normal_para(_(u"Health")), normal_para("-")]) health_row.append([normal_para(_(u"Height")), normal_para("-")]) health_row.append([normal_para(_(u"Weight")), normal_para("-")]) health_row.append( [normal_para(_(u"Long term diagnosis")), normal_para("-")]) health_row.append( [normal_para(_(u"Medical remarks")), normal_para("-")]) if checkup_child: health_row[-5][1] = normal_para(checkup_child.get_health_display()) health_row[-4][1] = normal_para(checkup_child.height) health_row[-3][1] = normal_para(checkup_child.weight) health_row[-2][1] = normal_para(u",".join([ unicode(rem.name) for rem in checkup_child.ltdiag.all() if rem.name ])) health_row[-1][1] = normal_para(u",".join( [unicode(rem.name) for rem in checkup_child.medrem.all()])) health_row.append( [normal_para(_(u"Remarks")), normal_para(child.remarks)]) health_row.append([ normal_para(_(u"Date")), normal_para(datetime.now().strftime("%d-%m-%Y")) ]) children_row.append(child_row) children_health_row.append(health_row) page_flowables = [] for ii in range(len(children_row)): child_data_table = LongTable(children_row[ii], style=style) child_health_table = LongTable(children_health_row[ii], style=style) page_flowables.extend([ header_img, page_title, project_name, child_data_heading, child_data_table, child_health_heading, child_health_table, PageBreak(), ]) doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Annual Sponsorship child report"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=annual_report.pdf" return response
def printannualreportnew(request, projectid, children, style_sheet=None): """ prints annual report of the selected children """ project = Project.objects.get(pk=projectid) doct = doctemplate.SimpleDocTemplate( os.path.join( settings.TMP_DIR, 'annual_report.pdf', ), pagesize=A4, leftMargin=5, rightMargin=5, topMargin=5, bottomMargin=5, ) style = GRID_STYLE style.add(*('VALIGN', (0, 0), (-1, -1), 'TOP')) style.add(*('LEFTPADDING', (0, 0), (-1, -1), 5)) style.add(*('RIGHTPADDING', (0, 0), (-1, -1), 5)) style1 = BOX_STYLE style1.add(*('VALIGN', (0, 0), (1, 1), 'TOP')) style1.add(*('ALIGN', (0, 1), (1, 1), 'RIGHT')) headimg = PIL.Image.open( os.path.join(settings.MEDIA_ROOT, "pics/fidalogo.jpg")) headimg.thumbnail((120, 120), PIL.Image.ANTIALIAS) headimg.save(os.path.join(settings.MEDIA_ROOT, "fidalogo.tn"), "JPEG") header_img = Image(os.path.join(settings.MEDIA_ROOT, "fidalogo.tn")) page_title = Paragraph(_(u"Sponsored child report"), style=style_sheet["Heading3"]) project_name = Paragraph((project.name), style=style_sheet["Heading3"]) normal_para = lambda x: Paragraph(unicode(x), style=style_sheet["Normal"]) child_data_heading = Paragraph(_(u"General information about the child"), style=style_sheet["Heading3"]) child_story_heading = Paragraph(_(u"Child story"), style=style_sheet["Heading3"]) date_printed = Paragraph(_(u"Dated %s" % datetime.today().strftime("%d-%m-%Y")), style=style_sheet["Heading3"]) children_row = [] for child in children: try: childimg = PIL.Image.open( os.path.join(settings.MEDIA_ROOT, str(child.picture))) childimg.thumbnail((300, 300), PIL.Image.ANTIALIAS) childimg.save( os.path.join(settings.MEDIA_ROOT, str(child.picture) + ".tn"), "JPEG") img = Image( os.path.join(settings.MEDIA_ROOT, str(child.picture) + ".tn")) except: img = None child_row = [] child_row.append((normal_para(_(u"Name")), normal_para(child))) child_row.append( (normal_para(_(u"Village area")), normal_para(child.area))) child_row.append( (normal_para(_(u"Sex")), normal_para(child.get_sex_display()))) child_row.append((normal_para(_(u"Date of birth")), normal_para(child.dob.strftime("%d-%m-%Y")))) child_row.append((normal_para(_(u"Language")), normal_para(child.language.name or "-"))) child_row.append((normal_para(_(u"Religion")), normal_para(child.get_religion_display()))) child_row.append((normal_para(_(u"Character")), normal_para( _(u", ".join([ unicode(hob.name) for hob in child.character.all() if hob.name ]))))) child_row.append((normal_para(_(u"School standard")), normal_para(child.schoolstd.name or "-"))) child_row.append((normal_para(_(u"School performance")), normal_para(child.get_schoolperf_display()))) child_row.append( (normal_para(_(u"Free time")), normal_para(u", ".join([ unicode(hob.name) for hob in child.hobbies.all() if hob.name ]).capitalize()))) child_row.append((normal_para(_(u"Male guardian type")), normal_para(child.get_maleguardiantype_display() or "-"))) child_row.append((normal_para(_(u"Male guardian name")), normal_para(child.fathername or "-"))) child_row.append((normal_para(_(u"Male guardian job")), normal_para(child.fatherjob or "-"))) child_row.append((normal_para(_(u"Female guardian type")), normal_para(child.get_femaleguardiantype_display() or "-"))) child_row.append((normal_para(_(u"Female guardian name")), normal_para(child.mothername or "-"))) child_row.append((normal_para(_(u"Female guardian job")), normal_para(child.motherjob or "-"))) if child.sibling_set.all().count() > 0: child_row.append( (normal_para(_(u"Siblings")), normal_para( _(u", ".join( [unicode(hob) for hob in child.sibling_set.all()]))))) child_row.append( (normal_para(_(u"Remarks")), normal_para(child.remarks or "-"))) try: child_story = ChildStory.objects.get(child=child) except ChildStory.DoesNotExist: child_story = None story_content = child_story.story or '-' c_st = normal_para((story_content)) #if story_content: # story_content = story_content.replace('</p>', '</p><br /><br />', # story_content.count('</p>') - 1) children_row.append((child_row, img, c_st)) page_flowables = [] for ii in range(len(children_row)): head_row = [] head_row.append((header_img, children_row[ii][1])) head_row.append((page_title, project_name)) head_data_table = LongTable(head_row, style=style1) child_data_table = LongTable(children_row[ii][0], colWidths=(150, 422), style=style) page_flowables.extend([head_data_table]) page_flowables.extend([ child_data_table, child_story_heading, children_row[ii][2], date_printed, PageBreak(), ]) doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle(unicode(_("Annual Sponsorship child report"))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=annual_report.pdf" return response
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
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 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 mailinglist(request, projectid, style_sheet=None): project = Project.objects.get(pk=projectid) sponsorships_list = Sponsorship.objects.filter( child__area__project=project) project_sponsorships_list = Projectsponsorship.objects.filter( area__project=project) sponsors_list = [ii for ii in project_sponsorships_list] sponsors_list += [ii for ii in sponsorships_list] if request.POST: ordering_field = request.POST.get("ordering_field").strip() if ordering_field: ordering_map = { u"Id": u"_temp_id", u"FirstName": u"sponsor.fname", u"Surname": u"sponsor.lname", u"Sponsorships": u"", u"From": u"startdate", u"Country": u"sponsor.country", u"Address": u"sponsor.code", u"Remarks": u"remarks" } for idx, ii in enumerate(sponsors_list): ii._temp_id = idx order = request.POST.get("ordering") reverse = False if order == u"desc": reverse = True if ordering_map.get(ordering_field): attr = operator.attrgetter(ordering_map.get(ordering_field)) sponsors_list.sort(key=attr, reverse=reverse) doct = doctemplate.SimpleDocTemplate(os.path.join( settings.TMP_DIR, 'mailing_list.pdf'), pagesize=landscape(A4)) header = Paragraph(unicode(_("List of sponsors")), style_sheet["Title"]) spacer = Spacer(10, 10) data = [ map(unicode, [ _(u"First Name"), _(u"Last Name"), _(u"Sponsorships"), _(u"From"), _(u"Country"), _(u"Address"), _(u"Remarks") ]) ] def fit_into_paragraph(ustr): return Paragraph(u"\n".join(textwrap.wrap(ustr, 18)), style_sheet["Normal"]) for ii in sponsors_list: if isinstance(ii, Projectsponsorship): child_details = u"%s: %s %s" % (ii.area.code, ii.children or 0, _("children")) else: child_details = u"%s: %s" % (ii.child.code, ii.child.name) data.append( (fit_into_paragraph(ii.sponsor.fname), fit_into_paragraph(ii.sponsor.lname), fit_into_paragraph(child_details), fit_into_paragraph(ii.startdate.strftime("%d-%m-%Y")), fit_into_paragraph(ii.sponsor.country), fit_into_paragraph( u"%s: %s\n%s\n%s - " "%s\n%s\n%s\n%s" % (_("Code"), ii.sponsor.code, ii.sponsor.street, ii.sponsor.city, ii.sponsor.postal, ii.sponsor.country, ii.sponsor.phone, ii.sponsor.email)), fit_into_paragraph(ii.remarks or '-'))) table = LongTable(data, style=GRID_STYLE) page_flowables = [header, spacer, table] doct._doSave = 0 doct.build(page_flowables) canvas = doct.canv canvas.setTitle( unicode(_("%s Sponsor List" % settings.SHORT_PROJECT_NAME))) response = HttpResponse(canvas.getpdfdata(), mimetype="application/pdf") response[ "Content-Disposition"] = 'attachment;filename=mailing_list.pdf' return response total_sponsor_count = range(1, project_sponsorships_list.count()\ + sponsorships_list.count() + 1) total_sponsor_count.reverse() ctx = { 'sponsor_id': total_sponsor_count, 'project_sponsorships_list': project_sponsorships_list, 'sponsorships_list': sponsorships_list, 'active_tab': 'mailinglist', 'project': project } return render_to_response("web/mailinglist.html", context_instance=RequestContext(request, ctx))