def _draw_opinion(self, story): t = Table([["Section 2: Opinion of Local Study Doctor"]], (18 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) story.append(t) rows = [] row = ["Main cause of death:"] if not self.death_report.cause_of_death: row.append(self.not_reported_text) else: if self.death_report.cause_of_death.name == OTHER: row.append( fill( f"{self.death_report.cause_of_death.name}: " f"{self.death_report.cause_of_death_other}", width=80, )) else: row.append(fill(self.death_report.cause_of_death.name)) rows.append(row) t = Table(rows, (4 * cm, 14 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) t.hAlign = "LEFT" story.append(t) self.draw_narrative(story, title="Narrative:", text=self.death_report.narrative)
def _draw_opinion(self, story): t = Table([["Section 2: Opinion of Local Study Doctor"]], (18 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) story.append(t) rows = [] row = ["Main cause of death:"] if self.death_report.cause_of_death.short_name == OTHER: row.append( fill( f"{self.death_report.cause_of_death.name}: " f"{self.death_report.cause_of_death_other}", width=80, )) else: row.append(fill(self.death_report.cause_of_death.name)) rows.append(row) if self.death_report.cause_of_death == TUBERCULOSIS: rows.append([ "If cause of death is TB, site of TB disease:", self.death_report.get_tb_site_display(), ]) t = Table(rows, (4 * cm, 14 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) t.hAlign = "LEFT" story.append(t) self.draw_narrative(story, title="Narrative:", text=self.death_report.narrative)
def draw_demographics(self, story, **kwargs): try: assignment = fill(self.assignment, width=80) except NotAllowed: assignment = "*****************" rows = [ ["Subject:", self.subject_identifier], [ "Gender/Age:", f"{self.registered_subject.get_gender_display()} {self.age}", ], ["Weight:", f"{self.weight_at_timepoint} kg"], [ "Study site:", f"{self.registered_subject.site.id}: " f"{self.registered_subject.site.name.title()}", ], [ "Randomization date:", self.registered_subject.randomization_datetime.strftime( "%Y-%m-%d %H:%M"), ], ["Assignment:", assignment], ] t = Table(rows, (4 * cm, 14 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) t.hAlign = "LEFT" story.append(t)
def _draw_death_overview(self, story): # basics rows = [ ["Reference:", self.death_report.identifier], [ "Report date:", self.death_report.report_datetime.strftime("%Y-%m-%d %H:%M"), ], [ "Death date:", getattr(self.death_report, self.death_report.death_date_field).strftime( "%Y-%m-%d %H:%M"), ], [ "Study day:", self.death_report.study_day or self.not_reported_text ], [ "Death as inpatient:", self.death_report.death_as_inpatient or self.not_reported_text, ], ] t = Table(rows, (4 * cm, 14 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) t.hAlign = "LEFT" story.append(t)
def _make(self, rows): ta = Table(rows) ta.hAlign = 'LEFT' self._set_column_widths(ta) self._set_row_heights(ta, rows) s = self._get_style(rows) ta.setStyle(s) return ta
def get_report_story(self, **kwargs): story = [] data = [[Paragraph(dummy_text, self.styles["line_data_large"])]] t = Table(data, colWidths=(9 * cm)) t.setStyle( TableStyle([ ("INNERGRID", (0, 0), (0, 1), 0.25, colors.black), ("INNERGRID", (0, 2), (0, 3), 0.25, colors.black), ])) t.hAlign = "RIGHT" story.append(t) return story
def export_dynamic_data(dict_data): date = dict_data.get("date") data = dict_data.get("data") headers = dict_data.get("headers") file_name = "{}.pdf".format(dict_data.get("file_name")) title = str(dict_data.get("title")) el = [] # htable = headers hdata = [(title, "", "", ""), (date, "", "", "")] htable = Table(hdata) htable.hAlign = "LEFT" ldata = [] ldata.append(headers) # style_ = ParagraphStyle( # name='Normal', # ) for r in data: ldata.append(r) btable = Table(ldata) # btable = Table(ldata, colWidths=[(inch) for i in range(1, len(ldata) + 1)]) # btable = Table(ldata) btable.hAlign = "LEFT" btable.setStyle(TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), HexColor("#C0C0C0")), ('GRID', (0, 1), (-1, -1), 0.01 * inch, (0, 0, 0,)), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold')])) el.append(htable) el.append(btable) doc = SimpleDocTemplate(file_name, pagesize=A4) doc.build(el) openFile(file_name)
def pdf(group, bill): """PDF version of bill""" width, height = A4 margin = 1 * cm heading = 2 * cm logo_height = 1.5 * cm font_name = 'Times-Roman' font_size = 16 filename = '%s-%s-%s-%s' % (date.today(), group, _('bill'), bill.id) response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s.pdf' % ( slugify(filename)) show_logo = bool(group.logo and group.logo.storage.exists(group.logo.path)) if show_logo: ratio = group.logo.width / group.logo.height logo = Image(group.logo.path, width=logo_height * ratio, height=logo_height) def draw_header(canvas, doc): if show_logo: logo.drawOn(canvas, width / 2 - 1 * margin - logo_height * ratio, height - margin - logo_height) canvas.setFont(font_name, font_size) canvas.drawString(margin, height - margin - font_size, _('Bill #%d') % (bill.id)) canvas.setFont(font_name, font_size - 4) canvas.drawString( margin, height - margin - 2 * font_size, bill.created.strftime(_('%Y-%m-%d %H:%M').encode('utf-8'))) frames = [ Frame(0, 0, width / 2, height - heading, leftPadding=margin, bottomPadding=margin, rightPadding=margin / 2, topPadding=margin), Frame(width / 2, 0, width / 2, height, leftPadding=margin / 2, bottomPadding=margin, rightPadding=margin, topPadding=margin), ] templates = [PageTemplate(frames=frames, onPage=draw_header)] doc = BaseDocTemplate(response, pagesize=(width, height)) doc.addPageTemplates(templates) data = [[_('Description'), _('Amount')]] total = 0 for line in bill.billingline_set.all(): data.append([line.description, '%.2f' % line.amount]) total += line.amount data.append(['', '%.2f' % total]) table = Table(data, colWidths=[doc.width * 0.4, doc.width * 0.15]) table.setStyle(table_style) table.hAlign = 'LEFT' parts = [] for line in bill.description.split('\n'): parts.append(Paragraph(escape(line), styles['Normal'])) parts.append(Spacer(0.2 * cm, 0.2 * cm)) parts.append(KeepTogether(table)) doc.build(parts) return response
def getContent(self, item, bump_headings=False): pdf = [] if isinstance(item, Tag): className=item.get('class', '').split() item_type = item.name if item_type in ['h2', 'h3', 'h4', 'h5', 'h6']: item_style = self.tag_to_style.get(item_type) h = Paragraph(self.getItemText(item), self.styles[item_style]) h.keepWithNext = True pdf.append(h) if item_type == 'h2' and not bump_headings: hr = HRFlowable(width='100%', thickness=0.25, spaceBefore=2, spaceAfter=4, color=self.styles[item_style].textColor) hr.keepWithNext = True pdf.append(hr) elif item_type in ['table']: (table_data, table_style, caption) = self.getTableData(item) table = Table(table_data) table.setStyle(table_style) table.hAlign = 'LEFT' table.spaceBefore = 10 table.spaceAfter = 10 if caption: caption_el = Paragraph(self.getInlineContents(caption), self.styles['Discreet']) pdf.append(KeepTogether([table, caption_el])) else: pdf.append(table) elif item_type in ['ul']: for i in item.findAll('li'): pdf.append(Paragraph('<bullet>•</bullet>%s' % self.getInlineContents(i), self.styles['BulletList'])) elif item_type in ['ol']: # Sequences were incrementing based on previous PDF generations. # Including explicit ID and reset li_uuid = uuid1().hex for i in item.findAll('li'): pdf.append(Paragraph('<seq id="%s" />. %s' % (li_uuid, self.getInlineContents(i)), self.styles['BulletList'])) pdf.append(Paragraph('<seqReset id="%s" />' % li_uuid, self.styles['Normal'])) elif item_type in ['p'] or (item_type in ['div'] and 'captionedImage' in className or 'callout' in className or 'pullquote' in className): has_image = False # Pull images out of items and add before for img in item.findAll('img'): img.extract() src = img['src'].replace(self.site.absolute_url(), '') if src.startswith('/'): src = src.replace('/', '', 1) img_obj = self.getPloneImageObject(src) if img_obj: has_image = True img_data = img_obj.image.data try: pil_image = self.getImageFromData(img_data) except IOError: pass else: pdf_image = self.getImage(pil_image) pdf.append(pdf_image) # If we had an image, and the next paragraph has the # 'discreet' class (is a caption) then keep them together if has_image: s = item.findNextSiblings() if s and 'discreet' in s[0].get('class', ''): pdf[-1].keepWithNext = True # Get paragraph contents p_contents = self.getInlineContents(item) # Don't add anything if no contents. if not p_contents: pass elif 'callout' in className or 'pullquote' in className: pdf.append(Paragraph(p_contents, self.styles['Callout'])) elif 'discreet' in className or 'captionedImage' in className: if len(pdf) and isinstance(pdf[-1], Image): pdf[-1].keepWithNext = True pdf.append(Paragraph(p_contents, self.styles['Discreet'])) else: pdf.append(Paragraph(p_contents, self.styles["Normal"])) elif item_type in ['div']: for i in item.contents: pdf.extend(self.getContent(i)) elif item_type == 'blockquote': pdf.append(Paragraph(self.getItemText(item), self.styles['Blockquote'])) else: pdf.append(Paragraph(self.getItemText(item), self.styles["Normal"])) elif isinstance(item, NavigableString): if item.strip(): pdf.append(Paragraph(item, self.styles["Normal"])) return pdf
def post(self, *unused): try: nonce = self.request.get('nonce') username = self.request.get('username') today = str(date.today()) # Check nonce if not memcache.get(nonce): self.redirect('/' + username) return pricelist = Pricelist.all().filter('username ='******'http://www.tipidpc.com/useritems.php?username='******'t connect to TPC at the moment. Please try again later.") return try: location, contact_no = soup.find('p', 'usermeta').findAll('em', 'red') location = location.string contact_no = contact_no.string item_list = [] for tr in soup.find('table', 'itemlist').findAll('tr'): item, price = tr.findAll('td') item_list.append([item.text, price.string]) except (AttributeError, ValueError): self.response.set_status(400) self.response.out.write('Invalid username, incomplete info (missing location/contact no) or no user items.') return # Prepare pdf values item_count = len(item_list) page_count = int(math.ceil(float(item_count) / ITEM_PER_PAGE)) h_style = TableStyle([('FONT', (0, 0), (0, 0), 'Helvetica', 10), ('FONT', (1, 0), (-1, 0), 'Helvetica', 6), ('ALIGN', (1, 0), (-1, 0), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TOPPADDING', (0, 0), (-1, -1), 0), ]) f_style = ParagraphStyle('f_style', fontName='Helvetica', fontSize=6, spaceBefore=2, leading=8, alignment=TA_CENTER) table_style = TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica', 8), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('ROWBACKGROUNDS', (0, 0), (-1, -1), [None, HexColor(0xCCCCCC)]), ]) # Render pdf c = canvas.Canvas(blob, pagesize=LETTER) c.setAuthor(username) h = Table([[username + ' Pricelist (' + today + ')', 'Location: ' + location + '\n' + 'Contact Number: ' + contact_no, ]], colWidths=(4*inch, 4*inch), style=h_style) h.hAlign = 'LEFT' for i in range(0, page_count): t = Table(item_list[i*ITEM_PER_PAGE:(i+1)*ITEM_PER_PAGE], colWidths=(6*inch, 2*inch), style=table_style) t.hAlign = 'LEFT' f = Paragraph('Page ' + str(i + 1) + '/' + str(page_count) + '<br/><br/>' + 'Generated by TipidPC Pricelists (tpcpricelists.appspot.com)<br/>' + '<b>DISCLAIMER:</b> ' + 'Availability and prices are subject to change without prior notice.', f_style) Frame(0.25*inch, 0.25*inch, 8*inch, 10.5*inch).addFromList([h, t, f], c) c.showPage() c.save() pricelist.pdf = blob.getvalue() pricelist.last_updated = current_time() pricelist.put() # Set Headers self.response.headers['Content-Type'] = 'application/pdf' self.response.headers['Content-Disposition'] = ( 'attachment; filename=' + username + '_pricelist_' + today.replace('-', '_') + '.pdf' ) # Write pdf to response self.response.out.write(pricelist.pdf) except DeadlineExceededError: self.response.set_status(500) self.response.out.write('Timeout.')
def pdf(group, bill): """PDF version of bill""" width, height = A4 margin = 1*cm heading = 2*cm logo_height = 1.5*cm font_name = 'Times-Roman' font_size = 16 filename = '%s-%s-%s-%s' % (date.today(), group, _('bill'), bill.id) response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s.pdf' % ( slugify(filename)) show_logo = bool(group.logo and group.logo.storage.exists(group.logo.path)) if show_logo: ratio = group.logo.width / group.logo.height logo = Image( group.logo.path, width=logo_height*ratio, height=logo_height) def draw_header(canvas, doc): if show_logo: logo.drawOn( canvas, width/2 - 1*margin - logo_height*ratio, height - margin - logo_height) canvas.setFont(font_name, font_size) canvas.drawString( margin, height - margin - font_size, _('Bill #%d') % (bill.id)) canvas.setFont(font_name, font_size - 4) canvas.drawString( margin, height - margin - 2*font_size, bill.created.strftime(_('%Y-%m-%d %H:%M').encode('utf-8'))) frames = [ Frame( 0, 0, width/2, height-heading, leftPadding=margin, bottomPadding=margin, rightPadding=margin/2, topPadding=margin), Frame( width/2, 0, width/2, height, leftPadding=margin/2, bottomPadding=margin, rightPadding=margin, topPadding=margin), ] templates = [PageTemplate(frames=frames, onPage=draw_header)] doc = BaseDocTemplate(response, pagesize=(width, height)) doc.addPageTemplates(templates) data = [[_('Description'), _('Amount')]] total = 0 for line in bill.billingline_set.all(): data.append([line.description, '%.2f' % line.amount]) total += line.amount data.append(['', '%.2f' % total]) table = Table(data, colWidths=[doc.width*0.4, doc.width*0.15]) table.setStyle(table_style) table.hAlign = 'LEFT' parts = [] for line in bill.description.split('\n'): parts.append(Paragraph(escape(line), styles['Normal'])) parts.append(Spacer(0.2*cm, 0.2*cm)) parts.append(KeepTogether(table)) doc.build(parts) return response
def pdf(group, bill): """PDF version of bill""" width, height = A4 margin = 1 * cm heading = 2 * cm logo_height = 1.5 * cm font_name = "Times-Roman" font_size = 16 filename = "{}-{}-{}-{}".format(date.today(), group, _("bill"), bill.id) response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "attachment; filename=%s.pdf" % ( slugify(filename)) show_logo = bool(group.logo and group.logo.storage.exists(group.logo.path)) if show_logo: ratio = group.logo.width / group.logo.height logo = Image(group.logo.path, width=logo_height * ratio, height=logo_height) def draw_header(canvas, doc): if show_logo: logo.drawOn( canvas, width / 2 - 1 * margin - logo_height * ratio, height - margin - logo_height, ) canvas.setFont(font_name, font_size) canvas.drawString(margin, height - margin - font_size, _("Bill #%d") % (bill.id)) canvas.setFont(font_name, font_size - 4) canvas.drawString( margin, height - margin - 2 * font_size, bill.created.strftime(_("%Y-%m-%d %H:%M").encode("utf-8")), ) frames = [ Frame( 0, 0, width / 2, height - heading, leftPadding=margin, bottomPadding=margin, rightPadding=margin / 2, topPadding=margin, ), Frame( width / 2, 0, width / 2, height, leftPadding=margin / 2, bottomPadding=margin, rightPadding=margin, topPadding=margin, ), ] templates = [PageTemplate(frames=frames, onPage=draw_header)] doc = BaseDocTemplate(response, pagesize=(width, height)) doc.addPageTemplates(templates) data = [[_("Description"), _("Amount")]] total = 0 for line in bill.billingline_set.all(): data.append([line.description, "%.2f" % line.amount]) total += line.amount data.append(["", "%.2f" % total]) table = Table(data, colWidths=[doc.width * 0.4, doc.width * 0.15]) table.setStyle(table_style) table.hAlign = "LEFT" parts = [] for line in bill.description.split("\n"): parts.append(Paragraph(escape(line), styles["Normal"])) parts.append(Spacer(0.2 * cm, 0.2 * cm)) parts.append(KeepTogether(table)) doc.build(parts) return response