def draw_logo(self, canvas): """ Draw the logo on pdf according to following settings: logo_path: absolute path to image wanted_height: wanted height in mm (optional, default 20 mm) logo_x: x coordinate in mm (optional, default 13 mm) logo_y: y coordinate in mm (optional, default 55 mm) """ if not self.company_logo_settings: return # Get logo settings logo_path = self.company_logo_settings.get('path', None) wanted_height = self.company_logo_settings.get('wanted_height', 20) logo_x = self.company_logo_settings.get('x', 13) logo_y = self.company_logo_settings.get('y', 55) # Sanity check if not os.access(logo_path, os.R_OK): return # get original lgo dimensions to compute ratio logo = utils.ImageReader(logo_path) width, height = logo.getSize() ratio = float(width) / height # Compute width according to wanted height computed_width = int(wanted_height * ratio) # Draw logo im = Image(logo_path, computed_width * mm, wanted_height * mm) im.drawOn(canvas, *self.coord(logo_x, logo_y))
def tradingReport(self, c): title = "DAILY TRADING" c.setFont("Helvetica", 24) c.drawString(50,770, title) c.setFont("Helvetica", 16) c.drawString(50,730, "DATE :") c.drawString(110,730, str(today.year) + "/" + str(today.month) + "/" + str(today.day) ) # DATE c.line(110, 727, 185, 727) c.drawString(300,730, "Today's Performance :") c.line(465, 727, 515, 727) c.drawString(470,730, "4%") # PROFIT value c.drawString(50,680, "Market Analysis") columHeight = [1*cm, 1*cm, 1*cm, 1*cm] t=Table(self._data, 2.5*cm, columHeight) # The size of each cells t.setStyle(TableStyle([('GRID',(0,0),(-1,-1),1,colors.black), ('VALIGN',(0,0),(-1,-1),'TOP')])) t.wrapOn(c, 50,50) t.drawOn(c, 50,550) #Table Location c.drawString(50,500, "Intraday performance of Algorithm1") graph_1 = Image("example.png") graph_1.drawHeight = 6*cm graph_1.drawWidth = 17.5*cm #graph_1.wrapOn(c, 50,20) graph_1.drawOn(c,50,322) c.drawString(50,295, "Intraday performance of Algorithm2") graph_2 = Image("example2.png") graph_2.drawHeight = 6*cm graph_2.drawWidth = 17.5*cm #graph_2.wrapOn(c, 50,20) graph_2.drawOn(c,50,117)
def __init__(self, filename, width=None, height=None, kind='absolute', mask='auto', lazy=1, hAlign='CENTER', vAlign='CENTER'): try: super(BackgroundImage, self).__init__( filename=filename, width=width, height=height, kind=kind, mask=mask, lazy=lazy, hAlign=hAlign) except TypeError: # old style calling of parent # this is still used by reportlab Image.__init__( self, filename=filename, width=width, height=height, kind=kind, mask=mask, lazy=lazy, hAlign=hAlign) self.vAlign = vAlign
def draw(self): canvas = self.canv h, w = float(self.img.height), float(self.img.width) if not self.img.iptc.caption: fsz = 5.0 else: fsz = 0.85*inch if w > h*1.3: fsz = 0.25*inch s = self.size - fsz if h > w: ratio = w / h h = s w = s * ratio else: ratio = h / w w = s h = s * ratio img = Image(self.img.path, height=h, width=w) w, h = img.wrap(w, h) iw, ih = w, h imgx, imgy = (self.size - s - (fsz/2.0), self.size - h) img.drawOn(self.canv, imgx, imgy) print "%.2f x %.2f (%.2f x %.2f dpi)" % (w/inch, h/inch, float(o.width) / (w/inch), float(o.height) / (h/inch) ) p = Paragraph(self.img.iptc.caption, styleN) w, h = p.wrap(self.size - 10.0, 1.3*inch) print "Text %.2f x %.2f" % (w/inch, h/inch) p.drawOn(self.canv, 3.0, (imgy - h) - 3.0) canvas.rect(imgx, imgy, iw, ih, stroke=1, fill=0)
def _create_pdf_all(cls, items): styles = _prepare_styles() style_header = styles['FieldHead'] style_normal = styles['Normal'] style_title = styles['ItemTitle'] fields = cls.fields table_style = TableStyle([('GRID', (0, 0), (-1, -1), 0.25, colors.black)]) for item in items: if cls.title_show: yield Paragraph(item.title, style_title) rows = [] for field_name, field_type, dummy, dummy in fields: row = [Paragraph(objects.get_field_value_human(field_name), style_header)] if field_type == 'image': blob = item.get_blob(field_name) if blob: img = Image(StringIO(blob), lazy=2) img.drawWidth = img.drawWidth / 150. * inch img.drawHeight = img.drawHeight / 150. * inch row.append(img) else: row.append(Paragraph(objects.get_field_value_human( item.get_value(field_name)), style_normal)) rows.append(row) yield Table(rows, [5 * cm, None], style=table_style) yield Spacer(0.5 * cm, 0.5 * cm)
def export_pdf(metadata_report_sobject): report_data = json.loads(metadata_report_sobject.get('report_data')) parser = SafeConfigParser() config_path = os.path.abspath(os.path.dirname(__file__)) parser.read(config_path + '/config.ini') file_name = metadata_report_sobject.get('name') + '.pdf' save_location = parser.get('save', 'metadata_directory') saved_file_path = os.path.join(save_location, file_name) styleSheet = getSampleStyleSheet() I = Image(os.path.dirname(os.path.realpath(__file__)) + '/2g_logo.png') I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth I.drawWidth = 1.25 * inch top_address_paragraph = Paragraph('<strong>2G Digital Post, Inc.</strong>', styleSheet["BodyText"]) address_table_data = [ [top_address_paragraph], ['280 E. Magnolia Blvd.'], ['Burbank, CA 91502'], ['310 - 840 - 0600'], ['www.2gdigitalpost.com'] ] address_table = Table(address_table_data) P = Paragraph('<strong>Metadata Report</strong>', styleSheet["Heading2"]) header_table = Table([[I, address_table, P]]) title_table = get_title_table(metadata_report_sobject) section_one_header = Paragraph('Section 1 - Video Configuration', styleSheet['Heading3']) section_one_table_one = get_video_configuration_table_one(report_data) section_one_table_two = get_video_configuration_table_two(report_data) section_two_header = Paragraph('Section 2 - Audio Configuration', styleSheet['Heading3']) section_two_table_one = get_audio_configuration_table_one(report_data) section_two_table_two = get_audio_configuration_table_two(report_data) elements = [] elements.append(header_table) elements.append(title_table) elements.append(section_one_header) elements.append(section_one_table_one) elements.append(section_one_table_two) elements.append(section_two_header) elements.append(section_two_table_one) elements.append(section_two_table_two) doc = SimpleDocTemplate(saved_file_path) doc.build(elements, canvasmaker=NumberedCanvas)
def get_image(self, path, width=3*inch, alignement='LEFT'): img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) final_im = Image(path, width=width, height=(width * aspect)) final_im.hAlign = alignement return final_im
def build_marco_logo_y_empresa(dde): """ dde es una lista con la ruta al logotipo de la empresa (o None) y una serie de líneas de texto con los datos a mostrar de la empresa. Devuelve una tabla con los marcos transparentes con el logo y las líneas. """ if dde[0] != None: logo = Image(dde[0]) logo.drawHeight = 2*cm * logo.drawHeight / logo.drawWidth logo.drawWidth = 2*cm else: logo = Paragraph("", estilos["Normal"]) lineas_empresa = dde[1:] if len(lineas_empresa) <= 3: empresa = Preformatted("\n".join(lineas_empresa), estilos["Normal"]) else: texto_empresa = lineas_empresa[0] + "\n" #+ ". ".join(lineas_empresa[1:]) resto_lineas = lineas_empresa[1:] pivot = len(resto_lineas)/2 r1, r2 = resto_lineas[:pivot], resto_lineas[pivot:] texto_empresa += ". ".join(r1) + "\n" + ". ".join(r2) empresa = Preformatted(texto_empresa, estilos["Normal"]) datos = [[logo, empresa]] tabla = Table(datos, colWidths = (PAGE_WIDTH * 0.25, PAGE_WIDTH * 0.65)) tabla.setStyle(TableStyle([ ("ALIGN", (0, 0), (1, 0), "RIGHT"), ("ALIGN", (1, 0), (-1, -1), "LEFT"), ("VALIGN", (0, 0), (-1, -1), "CENTER"), ])) return tabla
def __init__(self, path): Image.__init__(self, path) import PIL w, h = PIL.Image.open(path).size self.maxw = w self.maxh = h
def build_logo_y_empresa_por_separado(dde): """ Ganas de matar aumentando... dde es una lista con la ruta al logotipo de la empresa (o None) y una serie de líneas de texto con los datos a mostrar de la empresa. Devuelve una imagen con el logotipo y una lista de líneas con los datos de la empresa para dibujarlas (drawText) al lado. Si no hay logo, devuelve None y la lista de líneas. """ if dde[0] != None: logo = Image(dde[0]) logo.drawHeight = 2*cm * logo.drawHeight / logo.drawWidth logo.drawWidth = 2*cm else: logo = None lineas_empresa = dde[1:] if len(lineas_empresa) <= 3: while len(lineas_empresa) < 3: lineas_empresa.append("") empresa = lineas_empresa else: texto_empresa = lineas_empresa[0] + "\n" #+ ". ".join(lineas_empresa[1:]) resto_lineas = lineas_empresa[1:] pivot = len(resto_lineas)/2 r1, r2 = resto_lineas[:pivot], resto_lineas[pivot:] texto_empresa += ". ".join(r1) + "\n" + ". ".join(r2) # Escuse moi, pero necesito aprovechar lo que ya hay. Un split no # hace daño a nadie, si acaso "un poquito" al rendimiento. lineas_empresa = texto_empresa.split("\n") return logo, lineas_empresa
def build(self): doc = TagDocTemplate(self.out_file) doc.addPageTemplates([BackgroundTemplate( 'qringly.pdf', name='background')]) story = [] style = styles['Normal'] # FIXME: The tempfiles are handled in an ugly manner. tempfiles = [] for sticker in self.stickers: try: handle, tmp = mkstemp('_qrtag.png') os.close(handle) img = sticker.build() img.save(tmp, 'png') scaled_size = INNER_WIDTH - 4 * PAD story.append(NextPageTemplate('background')) qr_img = PDFImage(tmp, width=scaled_size, height=scaled_size) qr_img.hAlign = 'CENTER' story.append(Spacer(INNER_WIDTH, 2 * PAD)) story.append(qr_img) story.append(Paragraph(sticker.line, line_style)) story.append(PageBreak()) finally: tempfiles.append(tmp) doc.build(story) for tmp in tempfiles: os.remove(tmp)
def __headImage(self, zone): if zone == self.EST: imagePath = common.rootPath+"evenement_est.jpg" else: #zone == self.SUD-EST imagePath = common.rootPath+"evenement_sud_est.jpg" evenement_Image = Image(imagePath, width=484 , height=102) evenement_Image.spaceAfter = 30 self.elements.append(evenement_Image)
def export_pdf(prequal_eval_sobject): parser = SafeConfigParser() config_path = os.path.abspath(os.path.dirname(__file__)) parser.read(config_path + '/config.ini') file_name = prequal_eval_sobject.get('name') + '.pdf' save_location = parser.get('save', 'directory') saved_file_path = os.path.join(save_location, file_name) doc = SimpleDocTemplate(saved_file_path, pagesize=letter) elements = [] styleSheet = getSampleStyleSheet() I = Image(os.path.dirname(os.path.realpath(__file__)) + '/2g_logo.png') I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth I.drawWidth = 1.25 * inch top_address_paragraph = Paragraph('<strong>2G Digital Post, Inc.</strong>', styleSheet["BodyText"]) address_table_data = [ [top_address_paragraph], ['280 E. Magnolia Blvd.'], ['Burbank, CA 91502'], ['310 - 840 - 0600'], ['www.2gdigitalpost.com'] ] address_table = Table(address_table_data) approved_rejected_status = prequal_eval_sobject.get('status') approved_rejected_table_data = [[Paragraph('Status: <strong>{0}</strong>'.format(approved_rejected_status), styleSheet["BodyText"])]] approved_rejected_table = Table(approved_rejected_table_data) client_name = get_name_from_code(prequal_eval_sobject.get('client_code'), 'twog/client') # If a client name is not specified, just put 'Element Evaluation' at the top of the report in its place if not client_name: client_name = "Element Evaluation" P = Paragraph('<strong>{0}</strong>'.format(client_name), styleSheet["Heading2"]) header_table = Table([[I, address_table, P, approved_rejected_table]]) elements.append(header_table) general_comments_header = Paragraph('General Comments', styleSheet['Heading3']) general_comments = Paragraph(prequal_eval_sobject.get('general_comments'), styleSheet['BodyText']) top_table = get_top_table(prequal_eval_sobject) title_table = get_title_table(prequal_eval_sobject) prequal_eval_lines_table = get_prequal_eval_lines_table(prequal_eval_sobject)
def _header_footer(self, canvas, doc): """ Renders a header and footer which will be inserted regardless of pdf method""" # Save the state of our canvas so we can draw on it canvas.saveState() stylesheet = getSampleStyleSheet() # Header logo = Image("http://www.fabco.la/fabco-seal-1.png", width=1.5*inch, height=1.5*inch) logo.hAlign = 'CENTER' stylesheet['BodyText'].fontSize = 10 stylesheet['BodyText'].leading = 14 stylesheet['BodyText'].leftIndent = 5 stylesheet['BodyText'].textColor = 'gray' FabcoAddress = "Fabco Art Services\n166 West Avenue 34\nLos Angeles CA 90031" project = get_object_or_404(Project, pk=self.pk) rightHeader = "Job #%s\nCompletion Date %s" % (project.project_id, project.due_date) # Build and format Left Header Table: leftHeaderData = [[FabcoAddress], [project.client.first_name + ' ' + project.client.last_name+'\n'+project.client.address.street+'\n'+project.client.address.city + ' ' + project.client.address.zip_code], ] leftHeaderTable = Table(leftHeaderData) leftHeaderTable.setStyle(TableStyle([ ('LEFTPADDING',(0,0),(0, 1),0), ('TOPPADDING',(0,1),(0, 1), 30), ('BOTTOMPADDING',(0,1),(0, 1), 0), ])) # Build and format Header Table: headerData = [([leftHeaderTable, logo, rightHeader])] headerTable = Table(headerData, colWidths=doc.width/3) headerTable.setStyle(TableStyle([ ('VALIGN', (0, 0), (-3, 0), 'MIDDLE'), ('VALIGN', (0, 0), (0, 0), 'TOP'), ('ALIGN',(1,0),(1,0),'CENTER'), ('ALIGN',(2,0),(2,0),'RIGHT'), ('LEFTPADDING',(0,0),(0,0),-1), ('RIGHTPADDING',(2,0),(2,0),-1), ])) # find required space | I don't really understand this.. w, h = headerTable.wrap(doc.width, doc.height) # render to canvas | I also don't really understand this.. headerTable.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - doc.bottomMargin) # Footer footer = Paragraph('Client Signature: _________________________', stylesheet['Normal']) w, h = footer.wrap(doc.width, doc.bottomMargin) footer.drawOn(canvas, doc.leftMargin, doc.bottomMargin) # Release the canvas canvas.restoreState()
def chooseSig(elements): msg = wx.MessageDialog(None, "Include signature?", "Message", wx.YES_NO | wx.ICON_QUESTION) if msg.ShowModal() == wx.ID_YES: logo = "/home/mb/Dropbox/Office/%sSignature.png" % settings.HOME_FOLDER im = Image(logo, 2*inch, 0.75*inch) im.hAlign = "LEFT" elements.append(im) else: elements.append(Spacer(1, 36))
def img(self, e): width = toLength(e.get('width')) height = toLength(e.get('height')) path = e.get('src') align = e.get('align', 'left').upper() img_obj = Image(self.get_from_url(path), width=width, height=height) img_obj.hAlign = align yield img_obj
def generateCertificate(user,event_name): try: userProfile = UserProfile.objects.using('mainsite').get(user = user) except: return None """ if event.__class__.__name__!='GenericEvent': return None """ # Create a buffer to store the contents of the PDF. # http://stackoverflow.com/questions/4378713/django-reportlab-pdf-generation-attached-to-an-email buffer = StringIO() CS = (3508, 2480) # Certificate [Page] Size #CS = landscape(A4) # Create the PDF object, using the response object as its "file." pdf = canvas.Canvas(buffer, pagesize=CS) # Get the width and height of the page. (pageWidth, pageHeight) = CS y = pageHeight x = 0 im = Image("/home/shaastra/hospi/certis/certback_final.jpg") im.hAlign = 'LEFT' paintImage(pdf, x, y, im) # Set font for Participant Name lineheight = PDFSetFont(pdf, 'Times-Bold', 80) xuser = (30.8 + (65.54/2))*cm yuser = 45.62*cm + lineheight name = constructName(user) pdf.drawString(xuser, yuser, '%s' % name) xevent = (24.3 + (65.54/2))*cm yevent = 37.62*cm + lineheight ename = event_name pdf.drawString(xevent, yevent, '%s' % ename) pdf.showPage() pdf.save() response = buffer.getvalue() buffer.close() return response
def insert_image(image, full_width=False, max_height=None): """Return image flowable, scaled to fit. For landscape images, 'fit' means page width. For portrait images, 'fit' means the height has to be the same as that of a landscape image. """ width, height = image.getSize() if not width: return [] if full_width: max_width = (21 - 2.5 - 2.5) * units.cm else: # Add a bit of padding, as otherwise you won't commonly get two photos # on the same page. max_width = (21 - 2.5 - 2.5 - 2) * units.cm if width >= height or full_width: # Landscape (or portrait where we want to use the full width/height). img_width = max_width img_height = max_width * height / width # Compensation for too-high images if not max_height: max_height = (29.7 - 4 - 3 - 2) * units.cm if img_height > max_height: factor = max_height / img_height img_width = img_width * factor img_height = img_height * factor else: # Portrait. img_height = max_width * width / height img_width = img_height * width / height url = image.absolute_url() try: image = Image(url, width=img_width, height=img_height) except ValueError: # Unreadable image: anon doesn't have permission. temp_name = tempfile.mktemp() temp_file = open(temp_name, 'w') temp_file.write(image.getImageAsFile().read()) temp_file.close() image = Image(temp_name, width=img_width, height=img_height) return [Spacer(1, 0.1 * units.cm), image, ]
def report4(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=somefilename.pdf' doc = SimpleDocTemplate(response, pagesize=letter) # container for the 'Flowable' objects elements = [] styleSheet = getSampleStyleSheet() I = Image('replogo.jpeg') I.drawHeight = 1.25*inch*I.drawHeight / I.drawWidth I.drawWidth = 1.25*inch P0 = Paragraph(''' <b>A pa<font color=red>r</font>a<i>graph</i></b> <super><font color=yellow>1</font></super>''', styleSheet["BodyText"]) P = Paragraph(''' <para align=center spaceb=3>The <b>ReportLab Left <font color=red>Logo</font></b> Image</para>''', styleSheet["BodyText"]) data= [['A', 'B', 'C', P0, 'D'], ['00', '01', '02', [I,P], '04'], ['10', '11', '12', [P,I], '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']] t=Table(data,style=[('GRID',(1,1),(-2,-2),1,colors.green), ('BOX',(0,0),(1,-1),2,colors.red), ('LINEABOVE',(1,2),(-2,2),1,colors.blue), ('LINEBEFORE',(2,1),(2,-2),1,colors.pink), ('BACKGROUND', (0, 0), (0, 1), colors.pink), ('BACKGROUND', (1, 1), (1, 2), colors.lavender), ('BACKGROUND', (2, 2), (2, 3), colors.orange), ('BOX',(0,0),(-1,-1),2,colors.black), ('GRID',(0,0),(-1,-1),0.5,colors.black), ('VALIGN',(3,0),(3,0),'BOTTOM'), ('BACKGROUND',(3,0),(3,0),colors.limegreen), ('BACKGROUND',(3,1),(3,1),colors.khaki), ('ALIGN',(3,1),(3,1),'CENTER'), ('BACKGROUND',(3,2),(3,2),colors.beige), ('ALIGN',(3,2),(3,2),'LEFT'), ]) t._argW[3]=1.5*inch elements.append(t) # write the document to disk doc.build(elements) return response
def add_header(self): # aiddata logo logo = self.dir_base + "/templates/logo.png" im = Image(logo, 2.188 * inch, 0.5 * inch) im.hAlign = "LEFT" self.Story.append(im) self.Story.append(Spacer(1, 0.25 * inch)) # title ptext = "<font size=20>AidData geo(query) Request Documentation</font>" self.Story.append(Paragraph(ptext, self.styles["Center"]))
def pdf(request): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import mm from reportlab.platypus import Paragraph, Table, TableStyle, SimpleDocTemplate, Image from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont events = ScheduleSection.objects.all() data = [] for event in events: title = event.title or u"" if event.lecture: speakers = event.lecture.get_speakers() title = u"%s%s «%s»" % (title, speakers, event.lecture.title) data.append([unicode(event.start_time), title]) table = Table(data) pdfmetrics.registerFont(TTFont("font", PROJECT_ROOT + "/font.ttf")) styleSheet = getSampleStyleSheet() style = styleSheet["BodyText"] style.fontName = "font" style.spaceAfter = 10 * mm logo = Image(STATIC_ROOT + "/img/branding/logo.png") logo.drawHeight = 40 * mm * logo.drawHeight / logo.drawWidth logo.drawWidth = 40 * mm P = Paragraph("Конференция ProfsoUX", style) table.setStyle(TableStyle([("FONTNAME", (0, 0), (-1, -1), "font")])) lst = [] lst.append(logo) lst.append(P) lst.append(table) saved_file = MEDIA_ROOT + "/schedule.pdf" SimpleDocTemplate(saved_file, showBoundary=0).build(lst) f = open(saved_file) response = HttpResponse(f, mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=ProfsoUX-2012-schedule.pdf" return response
def generiraj_header_tablicu(self, stranica=1, total=3): """ generiranje header tablice sa logotipom """ stil1 = self.generate_paragraph_style(align=TA_CENTER, size=11) stil2 = self.generate_paragraph_style(font='FreeSansBold', align=TA_CENTER, size=14) stil3 = self.generate_paragraph_style(align=TA_CENTER, size=10) stil4 = self.generate_paragraph_style(font='FreeSansBold', align=TA_CENTER, size=12) stil5 = self.generate_paragraph_style(font='FreeSansBold', align=TA_CENTER, size=10) #defaultne vrijednosti polja iz mape - isti kljuc je string unutar [] stranica = str(stranica) total = str(total) norma = str(self.datastore.get_izabranaNormaObrasca()) broj_obrasca = str(self.datastore.get_izabraniBrojObrasca()) revizija = str(self.datastore.get_izabranaRevizijaIzvjesca()) #logo logotip = Image(self.logo) logotip.drawHeight = 0.75*inch*1.25 logotip.drawWidth = 0.75*inch a2 = Paragraph('Laboratorij za istraživanje kvalitete zraka', stil1) a3 = Paragraph('OBRAZAC', stil2) a4 = Paragraph('Ozn', stil1) a5 = Paragraph(broj_obrasca, stil3) b3 = Paragraph('Terensko ispitivanje mjernog uređaja prema:', stil4) b4 = Paragraph('Rev', stil1) b5 = Paragraph(revizija, stil3) c3 = Paragraph(norma, stil5) c4 = Paragraph('Str', stil1) c5 = Paragraph("".join([stranica, '/', total]), stil3) layout_tablice = [ [logotip, a2, a3, a4, a5], ['', '', b3, b4, b5], ['', '', c3, c4, c5]] stil_tablice = TableStyle( [ ('SPAN', (0, 0), (0, -1)), ('SPAN', (1, 0), (1, -1)), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ]) sirina_stupaca = [0.75*inch, 1*inch, 3.6*inch, 0.5*inch, 1.4*inch] visina_stupaca = [0.4*inch, None, None] tablica = Table(layout_tablice, colWidths=sirina_stupaca, rowHeights=visina_stupaca, hAlign='LEFT') tablica.setStyle(stil_tablice) return tablica
def render(self, stream=None): ''' Render the pdf with current lines & style ''' # Use a buffer when no stream is given if stream is None: stream = StringIO() # Build lines self.add_days() self.build_lines() # Canvas is landscape oriented pdf = SimpleDocTemplate(stream, pagesize=landscape(letter)) # Table is in a frame table = Table(self.lines, [1.5* inch ] * 7, self.row_heights, style=self.tableStyle, repeatRows=1) table.wrap(0,0) # important hacky way to span on full width tableFrame = Frame(inch / 2, inch / 2, 10*inch, 7*inch) # RunReport logo logo = Image('./medias/img/logo_ligne.png') logo.drawHeight = 2.2*inch*logo.drawHeight / logo.drawWidth logo.drawWidth = 2.2*inch # Plan infos are in a frame, in top left corner context = { 'site' : self.site, 'plan' : self.plan, } title = Paragraph(render_to_string('plan/export.pdf.title.html', context), self.titleStyle) # Add table elements pdf.addPageTemplates([ PageTemplate(id='table', frames=[tableFrame]), ]) story = [ logo, title, Spacer(1, 0.4*inch), # make room for header table, # the plan ] pdf.build(story) if isinstance(stream, StringIO): output = stream.getvalue() stream.close() return output return None
def add_header(self): # aiddata logo logo = self.dir_base + '/templates/logo.png' im = Image(logo, 2.188*inch, 0.5*inch) im.hAlign = 'LEFT' self.Story.append(im) self.Story.append(Spacer(1, 0.25*inch)) # title ptext = '<font size=20>Data Extraction Tool Request Documentation</font>' self.Story.append(Paragraph(ptext, self.styles['Center'])) self.Story.append(Spacer(1, 0.5*inch))
def main(): doc = SimpleDocTemplate("json2pdf_example.pdf", pagesize=A4) # container for the 'Flowable' objects elements = [] styleSheet = getSampleStyleSheet() I = Image('BMW.gif') I.drawHeight = 1.25 * cm * I.drawHeight / I.drawWidth I.drawWidth = 1.25 * cm P0 = Paragraph(''' <b>A pa<font color=red>r</font>a<i>graph</i></b> <super><font color=yellow>1</font></super>''', styleSheet["BodyText"]) P = Paragraph(''' <para align=center spaceb=3>The <b>ReportLab Left <font color=red>Logo</font></b> Image</para>''', styleSheet["BodyText"]) data = [['A', 'B', 'C', P0, 'D'], ['00', '01', '02', [I, P], '04'], ['10', '11', '12', [P, I], '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']] style = [('GRID', (1, 1), (-2, -2), 1, colors.green), ('BOX', (0, 0), (1, -1), 2, colors.red), ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue), ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink), ('BACKGROUND', (0, 0), (0, 1), colors.pink), ('BACKGROUND', (1, 1), (1, 2), colors.lavender), ('BACKGROUND', (2, 2), (2, 3), colors.orange), ('BOX', (0, 0), (-1, -1), 2, colors.black), ('GRID', (0, 0), (-1, -1), 0.5, colors.black), ('VALIGN', (3, 0), (3, 0), 'BOTTOM'), ('BACKGROUND', (3, 0), (3, 0), colors.limegreen), ('BACKGROUND', (3, 1), (3, 1), colors.khaki), ('ALIGN', (3, 1), (3, 1), 'CENTER'), ('BACKGROUND', (3, 2), (3, 2), colors.beige), ('ALIGN', (3, 2), (3, 2), 'LEFT'), ] style1 = [('BACKGROUND', (0, 0), (-1, 0), colors.Color(245, 215, 165))] t = Table(data, style=style) t._argW[3] = 1.5 * cm elements.append(t) # write the document to disk doc.build(elements)
def build_index_Casse(self, records, sito): if os.name == "posix": home = os.environ["HOME"] elif os.name == "nt": home = os.environ["HOMEPATH"] home_DB_path = ("%s%s%s") % (home, os.sep, "pyarchinit_DB_folder") logo_path = ("%s%s%s") % (home_DB_path, os.sep, "logo.jpg") logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet["Normal"] styBackground = ParagraphStyle("background", parent=styNormal, backColor=colors.pink) styH1 = styleSheet["Heading3"] data = self.datestrfdate() lst = [logo] lst.append(Paragraph("<b>ELENCO CASSE CAMPIONI</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = CASSE_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [20, 350, 250, 100] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" # table_data_formatted.setStyle(styles) lst.append(table_data_formatted) lst.append(Spacer(0, 0)) filename = ("%s%s%s") % (self.PDF_path, os.sep, "elenco_casse_campioni.pdf") f = open(filename, "wb") doc = SimpleDocTemplate( f, pagesize=(29 * cm, 21 * cm), showBoundary=0, topMargin=15, bottomMargin=40, leftMargin=30, rightMargin=30 ) # doc.build(lst, canvasmaker=NumberedCanvas_Sindex) doc.build(lst) f.close()
def capa(canvas, doc): cabecalho = Image('static/topFrame.png', 535, 63) w, h = cabecalho.wrap(doc.width, doc.topMargin) cabecalho.drawOn(canvas, doc.leftMargin + 5, doc.height + doc.topMargin - 40) canvas.setFont('Helvetica', 14) canvas.setFillColor(HexColor('#3366cc')) canvas.drawRightString(560, 220, doc_config['laudo']) canvas.setFont('Helvetica', 10) canvas.setFillColor(HexColor('#6a6a6a')) canvas.drawRightString(560, 180, doc_config['nome']) canvas.setFillColor(HexColor('#6a6a6a')) canvas.drawRightString(560, 160, doc_config['empresa']) canvas.setFillColor(HexColor('#6a6a6a')) canvas.drawRightString(560, 140, doc_config['cargo'])
def build_index_US(self, records, sito): if os.name == 'posix': home = os.environ['HOME'] elif os.name == 'nt': home = os.environ['HOMEPATH'] home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder') logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5*inch*logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5*inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append(Paragraph("<b>ELENCO UNITA' STRATIGRAFICHE</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = US_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths=[28,28,120,45,58,45,58,55,64,64,52,52,52] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) lst.append(Spacer(0,2)) dt = datetime.datetime.now() filename = ('%s%s%s_%s_%s_%s_%s_%s_%s%s') % (self.PDF_path, os.sep, 'elenco_us', dt.day, dt.month, dt.year, dt.hour, dt.minute, dt.second, ".pdf") f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29*cm, 21*cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_USindex) f.close()
def Image(path, width=None, height=None, ratio=None, hAlign='CENTER', **kw): """ An image with the file at *path*. The ratio is the width divided by the height of the source image. If the width or the height is given with the ratio, the other dimension is calculated from the first. """ if width and ratio: height = width / ratio elif height and ratio: width = height * ratio image = BaseImage(path, width, height, **kw) image.hAlign = hAlign return image
def wrap(self, awidth, aheight): wr, wh = self.maxw / awidth, self.maxh / aheight if wr > 1 or wh > 1: r = max(wr, wh) self.drawHeight = self.maxh / r self.drawWidth = self.maxw / r return Image.wrap(self, awidth, aheight)
def pdfGen(): x = ''.join( random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(32)) code = str(x)[0:5] fileName = str(x) + ".pdf" doc = SimpleDocTemplate(fileName, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) Story = [] logo = "python.png" formatted_time = time.ctime() full_name = "Don Anil Jasinghe" address_parts = [ "29/3A,Second Lane", "Purana Road, Wattegedara, Maharagama" ] im = Image(logo, 3 * inch, 2 * inch) Story.append(im) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ptext = '<font size="12">%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # Create return address ptext = '<font size="12">%s</font>' % full_name Story.append(Paragraph(ptext, styles["Normal"])) for part in address_parts: ptext = '<font size="12">%s</font>' % part.strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size="12">Dear %s:</font>' % full_name.split()[0].strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size="12">We would like to welcome you to Onclinic Platform. As you already know Onclinic is the\ Best platform for Online channeling and Doctor booking. This is your final part of registration. All u want to do is\ Add verification code in web browser</font>' Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) ptext = '<font size="12">Here is your Verification Code: %s</font>' % ( code) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 15)) ptext = '<font size="12">Thank you very much and we look forward to serving you.</font>' Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) ptext = '<font size="12">Sincerely,</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 48)) ptext = '<font size="12">Ran Sucker</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) doc.build(Story) cred = credentials.Certificate( "./onclinic-dd11a-firebase-adminsdk-g3ixz-639c96122f.json") firebase_admin.initialize_app( cred, {'storageBucket': 'onclinic-dd11a.appspot.com'}) db = firestore.client() bucket = storage.bucket() blob = bucket.blob(fileName) outfile = fileName blob.upload_from_filename(outfile) print(blob.generate_signed_url(datetime.timedelta(days=300), method='GET')) os.remove(fileName) return jsonfy(fileName)
def toPDF(data, filename): """ Export doc9303 instance to PDF @param doc: doc9303 @type doc: doc9303 instance (pyPassport) @param filename: output file @type filename: String @return: None """ doc = SimpleDocTemplate(filename, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) Story = [] styles = getSampleStyleSheet() # NAME name = (data["EP"]["DG1"]["5F5B"]).split("<<") Story.append( Paragraph( getItem(name[1].upper()) + " " + getItem(name[0].upper()), styles["Heading1"])) # PICTURE tag = None if data["EP"]["DG2"]["A1"].has_key("5F2E"): tag = "5F2E" elif data["EP"]["DG2"]["A1"].has_key("7F2E"): tag = "7F2E" if tag != None: path = None raw = data["EP"]["DG2"]["A1"][tag] profile = writeImageToDisk(raw, "~picture") img_file = PIL.Image.open(profile) width, height = img_file.size ratio = float(width) / float(2 * inch) h_img = float(height) / ratio im = Image(profile, 2 * inch, h_img) Story.append(im) try: if data["EP"].has_key("DG7") and data["EP"]["DG7"].has_key("5F43"): raw = data["EP"]["DG7"]["5F43"][0] signature = writeImageToDisk(raw, "~signature") img_signature = PIL.Image.open(signature) width, height = img_signature.size ratio = float(width) / float(2 * inch) h_img = float(height) / ratio sign = Image(signature, 2 * inch, h_img) Story.append(sign) except Exception: pass # OVERVIEW Story.append(Paragraph("Overview", styles["Heading2"])) Story.append( Paragraph( "<font size=12>Type: " + getItemByTag(data["EP"], 'DG1', '5F03') + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Passport #: " + str(getItemByTag(data["EP"], 'DG1', '5A')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Country: " + str(getItemByTag(data["EP"], 'DG1', '5F28')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Authority: " + str(getItemByTag(data["EP"], 'DG12', '5F19')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Issue Date: " + str(getItemByTag(data["EP"], 'DG12', '5F26')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Expiry Place: " + str(getItemByTag(data["EP"], 'DG1', '59')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Nationality: " + str(getItemByTag(data["EP"], 'DG1', '5F2C')) + "</font>", styles["Normal"])) Story.append(Spacer(1, 12)) Story.append( Paragraph("<font size=12>Name: " + str(getItem(name[0])) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Surname: " + str(getItem(name[1])) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Birth Date: " + str(getItemByTag(data["EP"], 'DG1', '5F57')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Birth Place: " + str(getItemByTag(data["EP"], 'DG11', '5F11')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Sex: " + str(getItemByTag(data["EP"], 'DG1', '5F35')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Height: " + str(getItemByTag(data["EP"], 'DG13', '9F01')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Colour of eyes: " + str(getItemByTag(data["EP"], 'DG13', '9F02')) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Residence: " + str(getItemByTag(data["EP"], 'DG13', '9F03')) + "</font>", styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(Paragraph("Basic Access Control", styles["Heading2"])) Story.append( Paragraph( "<font size=12>Basic Access Control: " + data["bac"] + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Reading time: " + str(data["ReadingTime"]) + "</font>", styles["Normal"])) Story.append( Paragraph("<font size=12>Data Groups size:</font>", styles["Normal"])) for key, value in data["DGs"]: Story.append( Paragraph( "<font size=12>  - " + str(key) + ": " + str(value) + " octets" + "</font>", styles["Normal"])) # PRESENT DATAGROUPS #Story.append(Paragraph("Present DataGroups", styles["Heading2"])) #k = map(toOrder, data["EP"].keys()) #k.sort() #k = map(toDG,k) #for dg in k: # Story.append(Paragraph("<font size=12> - "+str(dg)+"</font>", styles["Normal"])) #Story.append(Spacer(1, 20)) # DUMP Story.append(Paragraph("MRZ information", styles["Heading3"])) for item in data["EP"]["DG1"]: try: tag_name = tagToName[item] except Exception: tag_name = item Story.append( Paragraph( "<font size=12> " + tag_name + ": " + getItemRaw(data["EP"], 'DG1', item) + "</font>", styles["Normal"])) Story.append(Spacer(1, 12)) if data["EP"].has_key("DG11"): Story.append( Paragraph("Additional document holder details", styles["Heading3"])) for item in data["EP"]["DG11"]["5C"]: try: tag_name = tagToName[item] except Exception: tag_name = item Story.append( Paragraph( "<font size=12> " + tag_name + ": " + getItemRaw(data["EP"], 'DG11', item) + "</font>", styles["Normal"])) Story.append(Spacer(1, 12)) if data["EP"].has_key("DG12"): Story.append( Paragraph("Additional document information", styles["Heading3"])) for item in data["EP"]["DG12"]["5C"]: try: tag_name = tagToName[item] except Exception: tag_name = item Story.append( Paragraph( "<font size=12> " + tag_name + ": " + getItemRaw(data["EP"], 'DG12', item) + "</font>", styles["Normal"])) Story.append(Spacer(1, 12)) if data["EP"].has_key("DG13"): Story.append( Paragraph("Reserved for national specific data", styles["Heading3"])) for item in data["EP"]["DG13"]["5C"]: try: tag_name = tagToName[item] except Exception: tag_name = item Story.append( Paragraph( "<font size=12> " + tag_name + ": " + getItemRaw(data["EP"], 'DG13', item) + "</font>", styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(Spacer(1, 12)) Story.append(Paragraph("Passive Authentication", styles["Heading2"])) Story.append(Paragraph("DG integrity:", styles["Heading3"])) for dgi in data["Integrity"]: if data["Integrity"][dgi] == True: v = "Verified" elif data["Integrity"][dgi] == False: v = "Not verified" elif data["Integrity"][dgi] == None: v = "No hash present in SOD for this EF" else: v = "N/A" Story.append( Paragraph("<font size=12> " + dgi + ": " + v + "</font>", styles["Normal"])) Story.append(Paragraph("DG hashes:", styles["Heading3"])) for dgi in data["Hashes"]: Story.append( Paragraph( "<font size=12> " + dgi + ": " + binToHexRep(data["Hashes"][dgi]) + "</font>", styles["Normal"])) Story.append(Paragraph("SOD", styles["Heading3"])) Story.append( Paragraph( "<font size=10>" + data["SOD"].replace("\n", "<br/>") + "</font>", styles["Normal"])) Story.append(Paragraph("Certificate", styles["Heading3"])) Story.append( Paragraph( "<font size=12>Certificate Serial Number:" + data["certSerialNumber"] + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Certificate Fingerprint:" + data["certFingerPrint"] + "</font>", styles["Normal"])) Story.append(Paragraph("Document Signer", styles["Heading3"])) data["DSCertificate"] = data["DSCertificate"].replace("\n", "<br/>") data["DSCertificate"] = data["DSCertificate"].replace(" ", " ") Story.append( Paragraph("<font size=10>" + data["DSCertificate"] + "</font>", styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(Paragraph("Active Authentication", styles["Heading2"])) Story.append( Paragraph( "<font size=12>Active Authentication executed:" + data["activeAuth"] + "</font>", styles["Normal"])) Story.append(Paragraph("Public Key", styles["Heading3"])) data["pubKey"] = data["pubKey"].replace("\n", "<br/>") data["pubKey"] = data["pubKey"].replace(" ", " ") Story.append( Paragraph("<font size=10>" + data["pubKey"] + "</font>", styles["Normal"])) Story.append(Paragraph("Extended Access Control", styles["Heading2"])) Story.append( Paragraph("<font size=12>EAC has not been implemented yet.</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Here is of DG that the reader cannot access:</font>", styles["Normal"])) for fdg in data["failedToRead"]: Story.append( Paragraph("<font size=12> - " + fdg + "</font>", styles["Normal"])) if not data["failedToRead"]: Story.append( Paragraph( "<font size=12> List empty: No EAC implemented in passport</font>", styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(Paragraph("Security investigation", styles["Heading2"])) Story.append(Paragraph("Security measures", styles["Heading3"])) Story.append( Paragraph( "<font size=12>Delay security measure after a wrong BAC: " + str(data["delaySecurity"]) + "</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12>Block the communication after a wrong BAC: " + str(data["blockAfterFail"]) + "</font>", styles["Normal"])) Story.append(Paragraph("Potential vulnerabilities", styles["Heading3"])) (vuln, ans) = data["activeAuthWithoutBac"] Story.append( Paragraph( "<font size=12>Active Authentication before BAC: " + str(vuln) + "</font>", styles["Normal"])) if vuln: Story.append( Paragraph( "<font size=12> * Vulnerable to AA Traceability</font>", styles["Normal"])) Story.append(Spacer(1, 12)) Story.append( Paragraph( "<font size=12>Different response time for wrong message or MAC: " + str(data["macTraceability"]) + "</font>", styles["Normal"])) if data["macTraceability"]: Story.append( Paragraph( "<font size=12> * Vulnerable to MAC traceability</font>", styles["Normal"])) Story.append( Paragraph( "<font size=12> Note: If delay security measure implemented, this might be a false positive</font>", styles["Normal"])) Story.append(Spacer(1, 12)) (vuln, error) = data["getChallengeNull"] Story.append( Paragraph( "<font size=12>Passport answers to a GET CHALLENGE with the Le set to '01': " + str(vuln) + "</font>", styles["Normal"])) if vuln: Story.append( Paragraph( "<font size=12> * Vulnerable to lookup brute force</font>", styles["Normal"])) Story.append(Paragraph("Error Fingerprinting", styles["Heading3"])) for ins in data["Errors"]: Story.append( Paragraph( '<font size=12>APDU "00" "' + ins + '" "00" "00" "" "" "00": ' + data["Errors"][ins] + "</font>", styles["Normal"])) doc.build(Story) if tag != None: os.remove(profile) try: os.remove(signature) except NameError: pass
def makePdf(npm_mahasiswa, nama_mahasiswa, tipe_bimbingan, kode_dosen_pembimbing, nama_pembimbing, nidn_pembimbing, tahun_ajaran, photo, judul, total_nilai): checkDir() makeQrcodeVerifySign( link=makeLinkVerify(kode_dosen=kode_dosen_pembimbing, npm_mahasiswa=npm_mahasiswa, tipe_bimbingan=switcherTipeBimbingan(tipe_bimbingan), total_nilai=total_nilai), kode_dosen=kode_dosen_pembimbing, npm_mahasiswa=npm_mahasiswa, tipe_bimbingan=switcherTipeBimbingan(tipe_bimbingan) ) bulan = date.today().strftime("%m") d2 = date.today().strftime(f"%d {bkd.bulanSwitcher(bulan)} %Y") STUDENT_EMAIL=getStudentEmail(npm_mahasiswa) doc = SimpleDocTemplate(f'./kambing/{npm_mahasiswa}-{kode_dosen_pembimbing}-{STUDENT_EMAIL}-{switcherTipeBimbingan(tipe_bimbingan)}.pdf', pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = portrait(A4) elements = [] logo = Image("logoKAMBING.PNG", 3.5 * inch, 1 * inch) logo.hAlign = "LEFT" elements.append(logo) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT)) ptext = '<font name="Times" size="14">FORMULIR KEGIATAN</font>' elements.append(Paragraph(ptext, styles["Center"])) elements.append(Spacer(1, 12)) ptext = f'<font name="Times" size="14">{switcherTipeBimbingan(tipe_bimbingan)}</font>' elements.append(Paragraph(ptext, styles["Center"])) elements.append(Spacer(1, 12)) ptext = '<font name="Times" size="14">TA. ' + tahun_ajaran + '</font>' elements.append(Paragraph(ptext, styles["Center"])) elements.append(Spacer(1, 0.5 * inch)) image = Image(photo, 1.1 * inch, 1.5 * inch) image.hAlign = "RIGHT" elements.append(image) elements.append(Spacer(1, 1.5 * inch)) ptext = '<font size=12> </font>' elements.append(Paragraph(ptext, styles["Center"])) elements.append(Spacer(1, -3 * inch)) table = [['<font name="Times" size="12">Nama</font>', '<font name="Times" size="12">: ' + nama_mahasiswa + '</font>'], ['<font name="Times" size="12">Npm</font>', '<font name="Times" size="12">: ' + npm_mahasiswa + '</font>'], ['<font name="Times" size="12">Judul</font>', '<font name="Times" size="12">: ' + judul + '</font>'], ['<font name="Times" size="12">Pembimbing</font>', '<font name="Times" size="12">: ' + nama_pembimbing + '</font>']] style = TableStyle([('ALIGN', (1, 1), (-2, -2), 'RIGHT'), ('VALIGN', (0, 0), (0, -1), 'TOP'), ('ALIGN', (0, -1), (-1, -1), 'LEFT'), ('VALIGN', (0, -1), (-1, -1), 'MIDDLE') ]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' data1 = [[Paragraph(cell, s) for cell in row] for row in table] tab = Table(data1, hAlign='LEFT', colWidths=[75, 290]) tab.setStyle(style) elements.append(tab) elements.append(Spacer(1, 0.6 * inch)) data = [['Pertemuan', 'Tanggal', 'Sudah Dikerjakan', 'Pekerjaan Selanjutnya', 'Nilai']] inner_data_list=makeListDataBimbinganByDosens(npm_mahasiswa, kode_dosen_pembimbing, tipe_bimbingan) for i in inner_data_list: data.append(i) nilai_data_list=['', '', '', 'Rata-Rata: ', '%.2f' % round(float(total_nilai), 2)] data.append(nilai_data_list) # Get this line right instead of just copying it from the docs style = TableStyle([('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('VALIGN', (0, 0), (0, -1), 'MIDDLE'), ('ALIGN', (0, 0), (0, -1), 'CENTER'), ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black) ]) # Configure style and word wrap s = getSampleStyleSheet() s = s["Normal"] s.wordWrap = 'CJK' data2 = [[Paragraph(cell, s) for cell in row] for row in data] t = Table(data2, hAlign='CENTER', colWidths=[62.5, 65, 180, 180, 40]) t.setStyle(style) elements.append(t) elements.append(Spacer(1, 10)) ptext = '<font size=12> </font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, .5 * inch)) ptext = '<font name="Times" size="12">Bandung, ' + d2 + '</font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, 12)) ptext = '<font name="Times" size="12">Pembimbing,</font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, .1 * inch)) data = approve_kambing.getDataPembimbing(npm_mahasiswa, kode_dosen_pembimbing) pembimbingke = approve_kambing.pembimbingPositionAs(data, kode_dosen_pembimbing) if approve_kambing.cekApprovalTrueorFalse(npm_mahasiswa, pembimbingke): qrcode = f"./kambingqrcode/{npm_mahasiswa}-{kode_dosen_pembimbing}-{switcherTipeBimbingan(tipe_bimbingan)}.PNG" else: qrcode = f"./kambingqrcode/whiteimage.png" im = Image(qrcode, 1.5 * inch, 1.5 * inch) im.hAlign = "RIGHT" elements.append(im) ptext = '<font name="Times" size="12">' + nama_pembimbing + '</font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, 1)) ptext = '<font name="Times" size="12">NIDN. ' + nidn_pembimbing + '</font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, 12)) doc.build(elements)
def rpt(): parser = argparse.ArgumentParser(description='make report') parser.add_argument('-f', metavar='csvfilename', type=str) parser.add_argument('-p', metavar='csvpath', type=str) parser.add_argument('-n', metavar='username', type=str) parser.add_argument('-i', metavar='userid', type=str) parser.add_argument('-d', metavar='deviceid', type=str) parser.add_argument('-t', metavar='date', type=str) parser.add_argument('-o', metavar='ifupload', type=str) args = parser.parse_args() info = { 'csvfilename': args.f, 'csvpath': args.p, 'username': args.n, 'userid': args.i, 'deviceid': args.d, 'date': args.t, 'ifupload': args.o } y_p, abs_time, time = predict.predictdata(info) story = [] stylesheet = getSampleStyleSheet() titileStyle = stylesheet['Normal'] titileStyle.wordWrap = 'CJK' titileStyle.leading = 25 normalStyle = stylesheet['Normal'] normalStyle.wordWrap = 'CJK' normalStyle.leading = 21 normalStyle.firstLineIndent = 32 normalStyle.fontSize = 14 normalStyle.alignment = 0 rpt_title = '<para autoLeading="off" fontSize=24 align=center><b><font face="msyh">CPAT数据导出报告</font></b><br/><br/><br/></para>' story.append(Paragraph(rpt_title, titileStyle)) text = '<para autoLeading="off" fontSize=18><br/><br/><br/><b><font face="msyh">- 用户基本信息:</font></b><br/><br/></para>' story.append(Paragraph(text, titileStyle)) text = '<font face="msyh" color=grey>用户姓名: %s</font><br/>' % info[ 'username'] story.append(Paragraph(text, normalStyle)) text = '<font face="msyh" color=grey>数据导出日期: %s</font><br/>' % info['date'] story.append(Paragraph(text, normalStyle)) text = '<font face="msyh" color=grey>是否存储到MyActilifeCloud: %s</font><br/>' % info[ 'ifupload'] story.append(Paragraph(text, normalStyle)) text = '<para autoLeading="off" fontSize=18><br/><br/><br/><b><font face="msyh">- 数据概况:</font></b><br/><br/></para>' story.append(Paragraph(text, titileStyle)) with open(info['csvpath'] + info['csvfilename'] + ".txt", "r") as f: for line in f.readlines(): line = line.strip('\n') if "测试持续时间" in line: temp = line.split(" ") hours = int(temp[1]) mins = int(temp[3]) seconds = int(temp[5]) text = '<font face="msyh" color=grey>%s</font><br/>' % line story.append(Paragraph(text, normalStyle)) text = '<para autoLeading="off" fontSize=18><br/><br/><br/><b><font face="msyh">- 原始数据图表:</font></b><br/><br/></para>' story.append(Paragraph(text, titileStyle)) hei = 300 wid = 600 img = Image(info['csvpath'] + info['csvfilename'] + "_" + "X-axis" + '.png') img.drawHeight = hei img.drawWidth = wid story.append(img) img = Image(info['csvpath'] + info['csvfilename'] + "_" + "Y-axis" + '.png') img.drawHeight = hei img.drawWidth = wid story.append(img) img = Image(info['csvpath'] + info['csvfilename'] + "_" + "Z-axis" + '.png') img.drawHeight = hei img.drawWidth = wid story.append(img) img = Image(info['csvpath'] + info['csvfilename'] + "_" + "combined" + '.png') img.drawHeight = hei img.drawWidth = wid story.append(img) text = '<para autoLeading="off" fontSize=18><br/><br/><br/><b><font face="msyh">- 数据分析结果:</font></b><br/><br/></para>' story.append(Paragraph(text, titileStyle)) print(y_p) alltime = time2second(hours, mins, seconds) text = '<font face="msyh" color=grey>总记录时间:%d 小时 %d 分钟 %d 秒</font><br/>' % ( hours, mins, seconds) story.append(Paragraph(text, normalStyle)) p0 = sum(l == 0 for l in y_p) * 100 / len(y_p) p1 = sum(l == 1 for l in y_p) * 100 / len(y_p) p2 = sum(l == 2 for l in y_p) * 100 / len(y_p) hours, mins, seconds = second2time(alltime * p0 / 100) text = '<font face="msyh" color=grey>轻度运动时间时间:%d 小时 %d 分钟 %d 秒</font><br/>' % ( hours, mins, seconds) story.append(Paragraph(text, normalStyle)) hours, mins, seconds = second2time(alltime * p1 / 100) text = '<font face="msyh" color=grey>中度运动时间时间:%d 小时 %d 分钟 %d 秒</font><br/>' % ( hours, mins, seconds) story.append(Paragraph(text, normalStyle)) hours, mins, seconds = second2time(alltime * p2 / 100) text = '<font face="msyh" color=grey>剧烈运动时间时间:%d 小时 %d 分钟 %d 秒</font><br/>' % ( hours, mins, seconds) story.append(Paragraph(text, normalStyle)) t0 = "轻度运动时间 %.2f%%" % p0 t1 = "中等运动时间 %.2f%%" % p1 t2 = "剧烈运动时间 %.2f%%" % p2 data = [p0, p1, p2] labs = [t0, t1, t2] colorss = [HexColor("#D8BFD8"), HexColor("#778899"), HexColor("#483D8B")] z = autoLegender(draw_pie(data, labs, colorss), "各运动强度分布比例图") story.append(z) import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker fig = plt.figure(figsize=(25, 12)) ax = fig.add_subplot(111) y_p = [l + 1 for l in y_p] ax.plot(abs_time, y_p) # ax.set_xticks(xtick) ax.grid() ax.set_yticks([1, 2, 3]) ax.xaxis.set_major_locator(ticker.MultipleLocator(24)) ax.set_xticklabels(abs_time, rotation=30) ax.set_yticklabels(['L', 'M', 'V']) ax.set_xlabel("abs_time") ax.set_ylabel("PA") fig.savefig(info['csvpath'] + "detail") img = Image(info['csvpath'] + "detail" + '.png') img.drawHeight = 400 img.drawWidth = 600 story.append(img) # lp = LinePlot() # lp.height = 150 # lp.width = 300 # da = [] # for i in range(0,len(y_p)): # da.append((i,y_p[i])) # lp.data = [da] # lp.lines[0].strokeColor = colors.blue # d = Drawing(448,230) # lab = Label() # lab.x = 220 # lab.y = 210 # lab.setText('具体运动情况折线图') # lab.fontName = 'msyh' # lab.fontSize = 20 # d.add(lab) # d.background = Rect(0,0,448,230,strokeWidth=1.5,strokeColor="#000000",fillColor=None) #边框颜色 # d.add(lp) # story.append(d) report = SimpleDocTemplate(info['csvpath'] + info['csvfilename'] + '.pdf') report.multiBuild(story) return "1"
def students(request): queryset = student.objects.all().order_by('zID') f = StudentFilter(request.GET, queryset=queryset) all_students = StudentTable(f.qs) RequestConfig(request, paginate = {'per_page':25}).configure(all_students) ################################################################ if 'pdf' in request.GET: response = HttpResponse(content_type='application/pdf') # today = date.today() # filename = 'pdf_demo' + today.strftime('%Y-%m-%d') response['Content-Disposition'] = 'filename="list_of_students.pdf"' # response.write(pdf) doc = SimpleDocTemplate(response, rightMargin=2*cm, leftMargin=2*cm, topMargin=0*cm, bottomMargin=0) styles = getSampleStyleSheet() styles.add(ParagraphStyle( name="TableHeader", fontSize=11, alignment=TA_CENTER, fontName="Helvetica")) styles.add(ParagraphStyle( name="ParagraphTitle", fontSize=11, alignment=TA_JUSTIFY, fontName="FreeSansBold")) styles.add(ParagraphStyle( name="Justify", alignment=TA_JUSTIFY, fontName="FreeSans")) ########elements container######## elements = [] ###########header############### UNSWLogo = Image('report/images/pdfheader.PNG') UNSWLogo.drawHeight = 4*cm UNSWLogo.drawWidth = 21 *cm elements.append(UNSWLogo) s = Spacer(1, 0.2*cm) elements.append(s) #########title############ title = """Reports by Students""" elements.append(Paragraph(title, styles['Heading2'])) s = Spacer(1, 0.2*cm) elements.append(s) #p = Paragraph('''<para align=center spaceb=3> TITLE''') ############table header############ header_Data = [["zID","First Name","Last Name", "Email","Degree","Start Year"]] t1 = Table(header_Data,[1.5*cm,1.75*cm,2*cm,5*cm,7.75*cm,1.5*cm]) t1.setStyle(TableStyle([('LINEABOVE',(0,0),(-1,-1),1, colors.black), ('LINEBELOW',(0,0),(-1,-1),1, colors.black), ('FONTSIZE', (0,0), (-1,-1), 8), ('INNERGRID',(0,0),(-1,-1),2,colors.black), ('BACKGROUND',(0,0),(-1,-1), HexColor('#50A6C2'))])) elements.append(t1) s1 = Spacer(1, 0.1*cm) elements.append(s1) ######table data ################## table_data = [[str(my_data.zID), str(my_data.f_name), str(my_data.l_name), str(my_data.email), str(my_data.degreeCode), str(my_data.startYear)] for my_data in f] #'''str(my_data.apptType)''' t = Table(table_data,[1.5*cm,1.75*cm,2*cm,5*cm,7.75*cm,1.5*cm]) #,[6*cm, 7*cm, 2.25*cm, 3*cm]) t.setStyle(TableStyle([('LINEABOVE',(0,0),(-1,-1),2, colors.white), ('LINEBELOW', (0,0), (-1,-1), 2, colors.white), ('ROWBACKGROUNDS', (0,0), (-1,-1), [HexColor('#e6f2ff'), HexColor('#c1e0ff')]), ('FONTSIZE', (0,0), (-1,-1), 8)])) elements.append(t) ############footer################## '''pdffooter = Image('report/images/pdffooter.PNG') pdffooter.drawHeight = 1.5*cm pdffooter.drawWidth = 22 *cm s1 = Spacer(1, 20*cm) elements.append(s1) elements.append(pdffooter)''' # elements.append(t) doc.build(elements) return response return render(request, 'studentReport.html', {'all_students': all_students, 'filter':f})
def padded_image_save(original_file): _, padded_image = resize_image_padding(original_file) pad_image = Image.fromarray(padded_image) make_dirs("pictures/padded_images/") pad_image.save("pictures/padded_images/%s" % (original_file.split('/'))[2])
def cabecalho(canvas, doc): cabecalho = Image('static/topFrame.png', 535, 63) w, h = cabecalho.wrap(doc.width, doc.topMargin) cabecalho.drawOn(canvas, doc.leftMargin + 5, doc.height + doc.topMargin - 40)
def generate_run_metadata(huc12): """Information about DEP modelling of this huc12.""" styles = getSampleStyleSheet() res = [] pgconn = get_dbconn("idep") # Get the number of runs cursor = pgconn.cursor() cursor.execute( """ select count(*), min(ST_Length(geom)), avg(ST_Length(geom)), max(ST_Length(geom)) from flowpaths where huc_12 = %s and scenario = 0 """, (huc12, ), ) row = cursor.fetchone() res.append( Paragraph( ("The Daily Erosion Project models %s hill slopes within this HUC12." "These slopes range in length from %.1f to %.1f meters " "(%.1f to %.1f feet) with an overall average of %.1f meters " "(%.1f feet).") % ( row[0], row[1], row[3], m2f(row[1]), m2f(row[3]), row[2], m2f(row[2]), ), styles["Normal"], )) # Something about managements and crops rows = [["Year", "Corn", "Soybean", "Pasture", "Other"]] for year in range(2016, 2019): df = read_sql( """ select lu""" + str(year) + """ as datum, count(*) from flowpath_points p JOIN flowpaths f on (p.flowpath = f.fid) WHERE f.huc_12 = %s and f.scenario = 0 GROUP by datum """, pgconn, params=(huc12, ), index_col="datum", ) total = df["count"].sum() leftover = total rows.append([year]) for cropcode in ["C", "B", "P"]: if cropcode in df.index: val = df.loc[cropcode, "count"] leftover -= val rows[-1].append("%.1f%%" % (val / total * 100.0, )) else: rows[-1].append("None") rows[-1].append("%.1f%%" % (leftover / total * 100.0, )) # Histogram of slope profiles tablestyle = TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP")]) res.append( Table( [[ [ Image( get_image_bytes( ("http://dailyerosion.local/" "auto/huc12_slopes.py?huc12=%s") % (huc12, )), width=3.6 * inch, height=2.4 * inch, ), Paragraph( ("Figure 3: This plot shows the most dominate combination of slope " "length and general steepness in the watershed."), styles["Normal"], ), ], [ Spacer(inch, inch * 0.25), Paragraph("Cropping Systems", styles["Heading3"]), Table(rows), Paragraph( ("Table 1: Estimated cropping percentage based on modelled " "hillslopes. The 'Other' column represents all other cropping " "types supported by DEP."), styles["Normal"], ), ], ]], style=tablestyle, )) return res
def main(): """See how we are called""" form = cgi.FieldStorage() huc12 = form.getfirst("huc", "070801050306")[:12] ishuc12 = len(huc12) == 12 bio = BytesIO() styles = getSampleStyleSheet() doc = SimpleDocTemplate(bio, pagesize=letter, topMargin=(inch * 1.5)) story = [] story.append(Paragraph(INTROTEXT, styles["Normal"])) story.append(Spacer(inch, inch * 0.25)) story.append(Paragraph("Geographic Location", styles["Heading1"])) story.append( Table([[ [ Image( get_image_bytes( ("http://dailyerosion.local/" "auto/map.wsgi?overview=1&huc=%s&zoom=250") % (huc12, )), width=3.6 * inch, height=2.4 * inch, ), Paragraph(LOCALIZATION["F1"][int(ishuc12)], styles["Normal"]), ], [ Image( get_image_bytes( ("http://dailyerosion.local/" "auto/map.wsgi?overview=1&huc=%s&zoom=11") % (huc12, )), width=3.6 * inch, height=2.4 * inch, ), Paragraph(LOCALIZATION["F2"][int(ishuc12)], styles["Normal"]), ], ]])) story.append(Spacer(inch, inch * 0.25)) story.append(Paragraph("DEP Input Data", styles["Heading1"])) story.extend(generate_run_metadata(huc12)) story.append(PageBreak()) story.append(Spacer(inch, inch * 0.25)) story.append(Paragraph("Yearly Summary", styles["Heading1"])) story.append(generate_summary_table(huc12)) story.append( Paragraph( ("Table 2: Average value does not include the " "current year. Events column are the number of " "days with non-zero soil loss. " "(* year to date total)"), styles["Normal"], )) story.append(PageBreak()) story.append(Spacer(inch, inch * 0.25)) story.append(Paragraph("Monthly Summary", styles["Heading1"])) story.append(generate_monthly_summary_table(huc12)) story.append( Paragraph( ("Table 3: Monthly Totals. Events column are the number of " "days with non-zero soil loss. (* month to date total)"), styles["Normal"], )) def pagecb(canvas, doc): """Proxy to our draw_header func""" draw_header(canvas, doc, huc12) doc.build(story, onFirstPage=pagecb, onLaterPages=pagecb) ssw("Content-type: application/pdf\n\n") ssw(bio.getvalue())
def run(): from reportlab.platypus import BaseDocTemplate, PageTemplate, Image, Frame, PageTemplate, \ ShowBoundaryValue, SimpleDocTemplate, FrameBG, Paragraph, \ FrameBreak from reportlab.lib.colors import toColor from reportlab.lib.utils import haveImages, _RL_DIR, rl_isfile, open_for_read, fileName2FSEnc, asNative from reportlab.lib.styles import getSampleStyleSheet styleSheet = getSampleStyleSheet() if haveImages: _GIF = os.path.join(testsFolder, 'pythonpowered.gif') if not rl_isfile(_GIF): _GIF = None _GAPNG = os.path.join(testsFolder, 'gray-alpha.png') if not rl_isfile(_GAPNG): _GAPNG = None else: _GIF = None if _GIF: _GIFFSEnc = fileName2FSEnc(_GIF) if _GAPNG: _GAPNGFSEnc = fileName2FSEnc(_GAPNG) _JPG = os.path.join(testsFolder, '..', 'docs', 'images', 'lj8100.jpg') if not rl_isfile(_JPG): _JPG = None doc = SimpleDocTemplate(outputfile('test_platypus_images.pdf')) story = [ FrameBG(color=toColor('lightblue'), start='frame-permanent'), ] if _GIF: story.append( Paragraph( "Here is an Image flowable obtained from a string GIF filename.", styleSheet['Italic'])) story.append(Image(_GIF)) story.append( Paragraph( "Here is an Image flowable obtained from a utf8 GIF filename.", styleSheet['Italic'])) #story.append(Image(fileName2FSEnc(_GIF))) story.append( Paragraph( "Here is an Image flowable obtained from a string GIF file url.", styleSheet['Italic'])) story.append(Image(getFurl(_GIF))) story.append( Paragraph( "Here is an Image flowable obtained from an open GIF file.", styleSheet['Italic'])) story.append(Image(open_for_read(_GIF, 'b'))) story.append(FrameBreak()) try: img = Image('http://www.reportlab.com/rsrc/encryption.gif') story.append( Paragraph( "Here is an Image flowable obtained from a string GIF http url.", styleSheet['Italic'])) story.append(img) except: story.append( Paragraph( "The image could not be obtained from a string http GIF url.", styleSheet['Italic'])) story.append(FrameBreak()) if _GAPNG: story.append( Paragraph( "Here is an Image flowable obtained from a string PNGA filename.", styleSheet['Italic'])) story.append(Image('rltw-icon-tr.png')) story.append( Paragraph( "Here is an Image flowable obtained from a string PNG filename.", styleSheet['Italic'])) story.append(Image(_GAPNG)) story.append( Paragraph( "Here is an Image flowable obtained from a utf8 PNG filename.", styleSheet['Italic'])) #story.append(Image(fileName2FSEnc(_GAPNG))) story.append( Paragraph( "Here is an Image flowable obtained from a string file PNG url.", styleSheet['Italic'])) story.append(Image(getFurl(_GAPNG))) story.append( Paragraph( "Here is an Image flowable obtained from an open PNG file.", styleSheet['Italic'])) story.append(Image(open_for_read(_GAPNG, 'b'))) story.append(FrameBreak()) if _JPG: img = Image(_JPG) story.append( Paragraph( "Here is an JPEG Image flowable obtained from a JPEG filename.", styleSheet['Italic'])) story.append(img) story.append( Paragraph( "Here is an JPEG Image flowable obtained from an open JPEG file.", styleSheet['Italic'])) img = Image(open_for_read(_JPG, 'b')) story.append(img) story.append(FrameBreak()) doc.build(story)
def image(self, chapter, path, margW=None, margH=None, bMaintainAspect=True, caption="", bFigure=True, outlinelabel="", fontname='', fontsize='', fontcolor=''): caption, outlinelabel = GetUnicode([caption, outlinelabel]) I = Image(path) imageW, imageH = I.drawWidth, I.drawHeight maxW, maxH = self.getReportChActiveTemplateFrameSize(chapter) if bFigure or caption: maxH *= 0.85 # 85% fudge factor on page height in an effort to prevent blank pages due to excessive length from <image>+<caption> (+<"Feature Images"> handled in PSSObject.CreateFeatureReport) # determine "marginalized" image frame width & height--as per user-specified; otherwise, image size not-to-exceed max page size if margW or margH: try: # marginalize width margW *= inch if margW > maxW: margW = maxW bMaintainAspect = True # if invalid marginalized size, force maintain aspect except: margW = min(imageW, maxW) bMaintainAspect = True # if no marginalized size, force maintain aspect try: # marginalize height margH *= inch if margH > maxH: margH = maxH bMaintainAspect = True # ibid. except: margH = min(imageH, maxH) bMaintainAspect = True # ibid. else: margW, margH = min(imageW, maxW), min(imageH, maxH) bImageTooBig = (imageW > maxW) or (imageH > maxH) if bMaintainAspect: aratio = float(imageH) / imageW arect = float(margH) / margW if aratio > arect: I.drawWidth, I.drawHeight = margH / aratio, margH else: I.drawWidth, I.drawHeight = margW, margW * aratio else: I.drawWidth, I.drawHeight = margW, margH if bFigure or caption: s = self.startKeep(chapter) self.report[chapter].append(I) if bFigure: # note: may or may not have "caption"; nonetheless, want autolabel & outline entry self.figcaption( chapter, 'Figure %d.%d.' % self.getChapterNoAndSectionNo(chapter) + '<seq template="%(Figure+)s"/>' + ' %s' % caption, outlinelabel, fontname, fontsize, fontcolor) else: # i.e. no autolabel & outline entry if caption: self.cdisc(chapter, caption, style=self._PC) if bFigure or caption: self.endKeep(chapter, s)
def main(file, output, page_size, unit, debug, h_cut_lines, v_cut_lines): ''' Generates the pdfstack from a given XML FILE. This command uses large amounts of pictures and text messages, declared and organised in the XML document, to create a multi paged PDF document. The front and back of the cards are organised automatically. If you dont know how to write the XML file, just run the command without any arguments. This will generate a modifiable example file. ''' pdfmetrics.registerFont(TTFont('Varta-Regular', r'fonts\Varta-Regular.ttf')) # Some default values DEFAULTS = { 'width': 8.5*unit, 'height': 11*unit, 'font': 'Varta-Regular', 'font-size': 21, } if (file == None): print('No file given') return tree = ET.parse(file.name) root = tree.getroot() # Parsing the xml file page_config = root.find(Tags.PAGECONFIG.value) if (page_config): for element in page_config: if (element.tag == Tags.PAGEWIDTH.value): if (is_float(element.text)): DEFAULTS['width'] = float(element.text)*unit elif (element.tag == Tags.PAGEHEIGHT.value): if (is_float(element.text)): DEFAULTS['height'] = float(element.text)*unit elif (element.tag == Tags.FONT.value): DEFAULTS['font'] = element.text elif (element.tag == Tags.FONTSIZE.value): if (is_float(element.text)): DEFAULTS['font-size'] = float(element.text) if (page_size != (0, 0)): DEFAULTS['width'], DEFAULTS['height'] = tuple(unit * el for el in page_size) pdf = canvas.Canvas(output, pagesize=(DEFAULTS['width'], DEFAULTS['height'])) frameStyle = { 'width': 3.5*inch, 'height': 3.5*inch, 'topPadding': 0, 'bottomPadding': 0, 'leftPadding': 0, 'rightPadding': 0, 'margin': 0.25*inch } styles = getSampleStyleSheet() my_style = ParagraphStyle('OwnStyle', parent=styles['Title']) my_style.leftIndent = 10 my_style.rightIndent = 10 my_style.fontName = DEFAULTS['font'] my_style.fontSize = DEFAULTS['font-size'] # Centering the frame group on the paper frame_fit_row = math.floor(DEFAULTS['width'] / (frameStyle['width'] + 2*frameStyle['margin'])) frame_fit_column = math.floor(DEFAULTS['height'] / (frameStyle['height'] + 2*frameStyle['margin'])) paper_xPadding = ((DEFAULTS['width'] - (frame_fit_row * (frameStyle['width'] + 2*frameStyle['margin']))) / 2) paper_yPadding = ((DEFAULTS['height'] - (frame_fit_column * (frameStyle['height'] + 2*frameStyle['margin']))) / 2) next_x = frameStyle['margin'] + paper_xPadding next_y = DEFAULTS['height'] - frameStyle['height'] - frameStyle['margin'] - paper_yPadding maxframes_on_page = frame_fit_column * frame_fit_row if (maxframes_on_page <= 0): click.echo('Cannot fit frames on page with given dimensions') return page_index = 0 frame_index = 0 page_content = root.find(Tags.CONTENT.value) if (page_content): page_cards = page_content.findall(Tags.CARD.value) if (page_cards): frame_contents = [ [] for i in range(math.ceil(len(page_cards)/maxframes_on_page)*2) ] for card in page_cards: if (frame_index >= maxframes_on_page): page_index += 2 frame_index = 0 card_content = card.getchildren() if (len(card_content) == 0): frame_contents[page_index].append(None) frame_contents[page_index+1].append(None) elif (len(card_content) > 0): index = 0 for element in card_content: if (element.tag == Tags.TEXT.value): # TODO: Some error handleing with the text and missing attrib text = element.attrib.get('text', None) if (text == None): click.echo('Error on TEXT attribute (TEXT) at card ' + str(page_cards.index(card)+1)) return frame_contents[page_index+index].append(Paragraph(text, style=my_style)) elif (element.tag == Tags.IMAGE.value): # TODO: Some error handleing with the path and missing attrib file_path = element.attrib.get('path', None) if (file_path == None): click.echo('Error on PATH attribute (IMAGE) at card ' + str(page_cards.index(card)+1)) return import os.path from os import path if (os.path.isfile(file_path) == False): click.echo('Invalid path <' + file_path + '> (IMAGE) at card ' + str(page_cards.index(card)+1)) return frame_contents[page_index+index].append(Image( file_path, width=frameStyle['width'], height=frameStyle['height'])) index += 1 if (index >= 2): break if (index == 1): frame_contents[page_index+1].append(None) frame_index += 1 for page in frame_contents: for content in page: if (next_x + frameStyle['width'] + frameStyle['margin'] > DEFAULTS['width']): next_x = frameStyle['margin'] + paper_xPadding next_y = next_y - 2*frameStyle['margin'] - frameStyle['height'] if (isinstance(content, Paragraph)): free_space = frameStyle['height'] - frameStyle['topPadding'] - frameStyle['bottomPadding'] free_space -= content.wrap( frameStyle['width'] - frameStyle['leftPadding'] - frameStyle['rightPadding'] \ + 2 * content.style.borderPadding, \ frameStyle['height'] - frameStyle['topPadding'] - frameStyle['bottomPadding'])[1] \ + content.style.borderPadding * 2 + 1 free_space += content.style.borderPadding * 2 frameStyle['topPadding'] = free_space / 2 frame = Frame( next_x, next_y, frameStyle['width'], frameStyle['height'], showBoundary=int(debug), topPadding=frameStyle['topPadding'], bottomPadding=frameStyle['bottomPadding'], leftPadding=frameStyle['leftPadding'], rightPadding=frameStyle['rightPadding']) if (content == None): frame.addFromList([], pdf) else: frame.addFromList([content], pdf) frameStyle['topPadding'] = 0 next_x = next_x + frameStyle['width'] + 2*frameStyle['margin'] if (debug): pdf.drawCentredString(DEFAULTS['width']/2, 20, str(pdf.getPageNumber()) + (pdf.getPageNumber() % 2 == 0 and ' (Back)' or ' (Front)')) if (v_cut_lines): # cut line length line_length = paper_yPadding-5 pdf.setLineWidth(0.1) # vertical cut lines next_line = paper_xPadding for i in range(0, frame_fit_row+1): pdf.line(next_line, 0, next_line, line_length) pdf.line(next_line, DEFAULTS['height'], next_line, DEFAULTS['height']-line_length) next_line += frameStyle['margin']*2 + frameStyle['width'] if (h_cut_lines): # cut line length line_length = paper_xPadding-5 pdf.setLineWidth(0.1) # horizontal cut lines next_line = paper_yPadding for i in range(0, frame_fit_column+1): pdf.line(0, next_line, line_length, next_line) pdf.line(DEFAULTS['width'], next_line, DEFAULTS['width']-line_length, next_line) next_line += frameStyle['margin']*2 + frameStyle['width'] pdf.showPage() next_x = frameStyle['margin'] + paper_xPadding next_y = DEFAULTS['height'] - frameStyle['height'] - frameStyle['margin'] - paper_yPadding pdf.save()
from reportlab.platypus import Paragraph, Image, SimpleDocTemplate, Spacer follaEstilo = getSampleStyleSheet() guion = [] cabecera = follaEstilo['Heading4'] cabecera.pageBreakBefore = 1 cabecera.keepWithNext = 3 cabecera.backColor = colors.lightgrey parrafo = Paragraph("Cabecera de doc", cabecera) guion.append(parrafo) cadena = "Cadena de texto para ampliar el contenido. " * 400 estilo = follaEstilo["BodyText"] parrafo2 = Paragraph(cadena, estilo) guion.append(parrafo2) guion.append(Spacer(0, 20)) fich_imagen = "/home/local/DANIELCASTELAO/fsancheztemprano/Imágenes/triforce.jpg" imagen_logo = Image(os.path.realpath(fich_imagen), width=400) guion.append(imagen_logo) doc = SimpleDocTemplate("ejemploInformePlatypus.pdf", pagesize=A4, showBoundary=0) doc.build(guion)
def export_pdf(element_eval_sobject): parser = SafeConfigParser() config_path = os.path.abspath(os.path.dirname(__file__)) parser.read(config_path + '/config.ini') file_name = element_eval_sobject.get('name') + '.pdf' save_location = parser.get('save', 'element_directory') saved_file_path = os.path.join(save_location, file_name) elements = [] image = Image( os.path.dirname(os.path.realpath(__file__)) + '/2g_logo.png') image.drawHeight = 1.25 * inch * image.drawHeight / image.drawWidth image.drawWidth = 1.25 * inch top_address_paragraph = get_paragraph( '<strong>2G Digital Post, Inc.</strong>') address_table_data = [[top_address_paragraph], ['280 E. Magnolia Blvd.'], ['Burbank, CA 91502'], ['310 - 840 - 0600'], ['www.2gdigitalpost.com']] address_table = Table(address_table_data) approved_rejected_status = element_eval_sobject.get('status') # Get the numeric code in the Element Evaluation code (the code with ELEMENT_EVALUATION replaced with the '#' # sign element_evaluation_numeric_code = element_eval_sobject.get_code( ).replace('ELEMENT_EVALUATION', '#') approved_rejected_table_data = [ [ get_paragraph('{0}'.format(element_evaluation_numeric_code), 'Italic') ], [], [], [], [ get_paragraph('Status: <strong>{0}</strong>'.format( approved_rejected_status)) ] ] approved_rejected_table = Table(approved_rejected_table_data) client_name = get_name_from_code( element_eval_sobject.get('client_code'), 'twog/client') # If a client name is not specified, just put 'Element Evaluation' at the top of the report in its place if not client_name: client_name = "Element Evaluation" client_paragraph = get_paragraph( '<strong>{0}</strong>'.format(client_name), "Heading2") header_table = Table( [[image, address_table, client_paragraph, approved_rejected_table]]) elements.append(header_table) program_format_header = get_paragraph('Program Format', 'Heading3') video_measurements_header = get_paragraph('Video Measurements', 'Heading3') element_profile_header = get_paragraph('Element Profile', 'Heading3') audio_configuration_header = get_paragraph('Audio Configuration', 'Heading3') general_comments_text = element_eval_sobject.get('general_comments') # For some reason, ampersands get a semicolon added on to the letter following them. Escaping them seems to # solve the problem if general_comments_text: general_comments_text = general_comments_text.replace('&', '&') general_comments_header = get_paragraph('General Comments', 'Heading3') general_comments = get_paragraph(general_comments_text) top_table = get_top_table(element_eval_sobject) title_table = get_title_table(element_eval_sobject) file_path_table = get_file_path_table(element_eval_sobject) program_format_table = get_program_format_table(element_eval_sobject) video_measurements_table = get_video_measurements_table( element_eval_sobject) element_profile_table = get_element_profile_table(element_eval_sobject) program_format_video_measurements_header_table = Table( [[program_format_header, video_measurements_header]], hAlign='LEFT') program_format_video_measurements_table = Table( [[program_format_table, video_measurements_table]], hAlign='LEFT') audio_configuration_table = get_audio_configuration_table( element_eval_sobject) element_eval_lines_table = get_element_eval_lines_table( element_eval_sobject) # Now apply some styling to all the tables (except the bottom one, which is styled separately since it needs # special styling to fit on the page). Only include audio_configuration_table if it exists tables_to_style = [ program_format_table, video_measurements_table, element_profile_table ] if audio_configuration_table: tables_to_style.append(audio_configuration_table) map( lambda x: x.setStyle([('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]), tables_to_style) hr_flowable = HRFlowable(color=colors.gray, width='100%') # Add the segments to the report, regardless of whether or not there is data in the tables elements.append(top_table) elements.append(title_table) elements.append(file_path_table) elements.append(hr_flowable) elements.append(program_format_video_measurements_header_table) elements.append(program_format_video_measurements_table) elements.append(element_profile_header) elements.append(element_profile_table) # Only include the next few segments if they have data if audio_configuration_table: elements.append(audio_configuration_header) elements.append(audio_configuration_table) if element_eval_sobject.get('general_comments'): elements.append(general_comments_header) elements.append(general_comments) if element_eval_lines_table: elements.append(element_eval_lines_table) doc = SimpleDocTemplate(saved_file_path, leftMargin=10, rightMargin=10, topMargin=15, bottomMargin=40) doc.build(elements, canvasmaker=NumberedCanvas)
def create_aadhar_enrollment(full_name,gender,father_name,mother_name,dob,birthplace,ph_no,email,res_addr,city,dist, state, country, pincode, eid, etime = time.ctime()): logo = "assets/images/aadhartop.jpg" doc = SimpleDocTemplate(str(eid)+".pdf",pagesize=letter, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) Story=[] styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) # ptext = '<font size=24><b><center>Aadhar Enroollment Form</center></b></font>' # Story.append(Paragraph(ptext, styles["Normal"])) # Story.append(Spacer(1, 12)) im = Image(logo, 7*inch, 1*inch) Story.append(im) Story.append(Spacer(2, 0)) ptext = "<font size=16><br /><b><u>Enroll Details</u></b>: </font>" Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = '<font size=12><b>Enrollment ID</b>: </font><font size=10>%s</font>' % eid Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = '<font size=12><b>Enrollment Time</b>: </font><font size=10>%s</font>' % etime Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=16><br /><b><u>Personal Details</u></b>: </font>" Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = '<font size=12><b>Name</b>: </font><font size=10>%s</font>' % full_name Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Father's name</b>: </font><font size=10>%s</font>" % father_name Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Mother's name</b>: </font><font size=10>%s</font>" % mother_name Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Birth place</b>: </font><font size=10>%s</font>" % birthplace Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Date of birth</b>: </font><font size=10>%s</font>" % dob Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=16><br /><b><u>Contact Details</u></b>: </font>" Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Phone Number</b>: </font><font size=10>%s</font>" % ph_no Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Email</b>: </font><font size=10>%s</font>" % email Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Address</b>: </font><font size=10>%s</font>" % res_addr Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>City</b>: </font><font size=10>%s</font>" % city Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>District</b>: </font><font size=10>%s</font>" % dist Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>State</b>: </font><font size=10>%s</font>" % state Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Country</b>: </font><font size=10>%s</font>" % country Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) ptext = "<font size=12><b>Pincode</b>: </font><font size=10>%s</font>" % pincode Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(0, 12)) doc.build(Story)
""") bullet(""" $kor$ = Korean: '$HYSMyeongJoStd-Medium$','$HYGothic-Medium$' """) bullet(""" $jpn$ = Japanese: '$HeiseiMin-W3$', '$HeiseiKakuGo-W5$' """) disc("""Since many users will not have the font packs installed, we have included a rather grainy ^bitmap^ of some Japanese characters. We will discuss below what is needed to generate them.""") # include a bitmap of some Asian text I=os.path.join(os.path.dirname(reportlab.__file__),'docs','images','jpnchars.jpg') try: getStory().append(Image(I)) except: disc("""An image should have appeared here.""") disc("""Prior to Version 2.0, you had to specify one of many native encodings when registering a CID Font. In version 2.0 you should a new UnicodeCIDFont class.""") eg(""" from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3')) canvas.setFont('HeiseiMin-W3', 16) # the two unicode characters below are "Tokyo" msg = u'\u6771\u4EAC : Unicode font, unicode input'
eixo_x = """Este eixo se refere a características comportamentais ou habilidades possíveis de serem administradas através de gerenciamento.<br/><br/> Alguns teóricos fazem referência a estas características chamando-as de atitudes, outros de habilidade e outros de aptidão.""" eixo_y = """Este eixo se refere a aspectos não comportamentais, tais como formação acadêmica, experiência dos profissionais sempre correlacionadas as demandas do cargo. Representa oportunidades de treinamento.""" story.append(Paragraph("Missão", styles["Titulo"])) story.append(Paragraph(missao, styles["Justificado"])) story.append(Paragraph("Ciclo", styles["Titulo"])) story.append(Paragraph(ciclo, styles["Justificado"])) story.append(Paragraph("Eixo X", styles["Titulo"])) story.append(Paragraph(eixo_x, styles["Justificado"])) story.append(Paragraph("Eixo Y", styles["Titulo"])) story.append(Paragraph(eixo_y, styles["Justificado"])) story.append(PageBreak()) # Gráfico story.append(Image('static/grafico_linear.png', 240, 280)) story.append(PageBreak()) # Fatores from fatores import Fatores fatores = Fatores() for fator in fatores.retornar_fatores(): story.append(Paragraph(fator['titulo'], styles["Titulo"])) story.append( Paragraph("<b>" + fator['alto'] + "</b>", styles["JustificadoBold"])) doc.build(story, onFirstPage=capa, onLaterPages=cabecalho)
def generation_rapport(dernierIdx): # Fonction permettant de récupérer les résultats de la table matlab et de les intégrer dans un rapport qualité pdf #dernierIdx =130 # Import des modules externes import scipy.io as sio import numpy as np from datetime import datetime import textwrap import argparse import os.path from sys import exit, path, version from reportlab.lib.enums import TA_JUSTIFY, TA_CENTER, TA_LEFT, TA_RIGHT from reportlab.lib.pagesizes import A4, landscape, portrait from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import mm from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle, PageBreak import math import glob from pickle import load, dump from os import mkdir, system, environ, remove from os.path import isfile, isdir from shutil import copyfile from collections import OrderedDict from IRMAGE_reporting import PageNumCanvas, ReportLine Path = '/media/cmaggia/Mesfichiers/MATLAB/' NomTraiteur = 'MAGGIA Christophe' # os.chdir(Path) test = sio.loadmat(Path + 'Basedonneesv4.mat') tableau = test['BaseDonnees'] dernierIdx = dernierIdx - 1 # for dernierIdx in range(len(tableau)): centre = tableau[dernierIdx]['Centre'][0][0].encode('utf-8') MarqueMachine = tableau[dernierIdx]['MarqueMachine'][0][0].encode('utf-8') ChampMachine = str(tableau[dernierIdx]['ChampMachine'][0][0][0]) date_now = datetime.now() SeuilVol = 0.15 SeuilCoupe = 0.1 dGen = OrderedDict() dGen.update( {'Code Sujet': tableau[dernierIdx]['NomSujet'][0][0].encode('utf-8')}) sujet = dGen['Code Sujet'] print(sujet) age = tableau[dernierIdx]['Age'][0][0][0] if age < 2 or age > 100: dGen.update({'Age': 'Inconnu'}) else: dGen.update({'Age': str(age)}) if tableau[dernierIdx]['Sexe'][0].size > 0 and 'M' in tableau[dernierIdx][ 'Sexe'][0] or 'F' in tableau[dernierIdx]['Sexe'][0]: dGen.update( {'Sexe': tableau[dernierIdx]['Sexe'][0][0].encode('utf-8')}) else: dGen.update({'Sexe': 'Non renseigné'}) dGen.update( {'Date de l"examen': str(tableau[dernierIdx]['DateExam'][0][0][0])}) if 'V' in sujet: dGen.update({'Etiologie': 'Volontaire sain'}) elif 'T' in sujet: dGen.update({'Etiologie': 'Patient TC test'}) elif 'P' in sujet: dGen.update({'Etiologie': 'Patient TC'}) Cheminsave = Path + centre + '/Sujets/' + sujet + '/' logo_OxyTC = Image(Path + 'Programmes/logoOxyTC.jpg', 30.0 * mm, 30.0 * mm) logo_CHU = Image(Path + 'Programmes/logoCHU.png', 25.0 * mm, 25.0 * mm) logo_Gin = Image(Path + 'Programmes/logo-GIN.png', 50.0 * mm, 25.0 * mm) logo_Irmage = Image(Path + 'Programmes/logoIrmage.jpg', 25.0 * mm, 25.0 * mm) logo_OK = Image(Path + 'Programmes/ok-button.png', 8.0 * mm, 8.0 * mm) logo_refus = Image(Path + 'Programmes/Refus.jpg', 7.0 * mm, 7.0 * mm) page = SimpleDocTemplate( Cheminsave + sujet + '.pdf', pagesize=portrait(A4), rightMargin=20 * mm, leftMargin=20 * mm, topMargin=10 * mm, bottomMargin=10 * mm ) # Output document template definition for page; margins and pagessize. styles = getSampleStyleSheet( ) # Initialises stylesheet with few basic heading and text styles, return a stylesheet object. styles.add( ParagraphStyle(name='Center', alignment=TA_CENTER) ) # ParagraphStyle gives all the attributes available for formatting paragraphs. styles.add( ParagraphStyle(name='CenterRed', alignment=TA_CENTER, textColor=colors.red)) styles.add(ParagraphStyle(name='Center2', alignment=TA_CENTER)) styles['Center2'].leading = 24 # If more than 1 line. styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT)) styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT)) styles.add( ParagraphStyle(name='Bullet1', leftIndent=30, bulletOffsetY=2, bulletIndent=20, bulletFontSize=6, bulletColor='black', bulletText=u'●')) styles.add( ParagraphStyle(name='Bullet2', leftIndent=60, bulletOffsetY=1, bulletIndent=50, bulletFontSize=6, bulletColor='black', bulletText=u'❍')) styles.add(ParagraphStyle(name='Indent', leftIndent=30)) styles.add(ParagraphStyle(name='Indent2', leftIndent=60)) styles.add( ParagraphStyle(name='Indent2Red', leftIndent=60, textColor=colors.red)) rapport = [] logo_OxyTC.hAlign = 'LEFT' logo_CHU.hAlign = 'LEFT' logo_Gin.hAlign = 'LEFT' logo_Irmage.hAlign = 'LEFT' listeSeq = ['T1', 'FLAIR', 'T2ETOILE', 'T2HR', 'B0', 'DTI'] dSeq = OrderedDict() didSeq = OrderedDict() #dlisteNoire = OrderedDict() #dCQstatut = OrderedDict() for seq in listeSeq: dSeq.update({seq: []}) didSeq.update({seq: []}) #dCQstatut.update({seq: []}) #dlisteNoire.update({seq: []}) [ didSeq.update({seq: s}) for s in range(len(tableau[dernierIdx]['Fichier'][0]['NomSeq'][0])) if len(tableau[dernierIdx]['Fichier'][0]['NomSeq'][0][s][0]) > 0 and seq == tableau[dernierIdx]['Fichier'][0]['NomSeq'][0][s] [0].encode('utf-8') ] [ dSeq.update({ seq: tableau[dernierIdx]['Fichier'][0]['Chemin'][0][s][0].encode( 'utf-8') }) for s in range(len(tableau[dernierIdx]['Fichier'][0]['NomSeq'][0])) if len(tableau[dernierIdx]['Fichier'][0]['NomSeq'][0][s][0]) > 0 and seq == tableau[dernierIdx]['Fichier'][0]['NomSeq'][0][s] [0].encode('utf-8') ] #[dCQstatut.update({seq: tableau[dernierIdx]['CQ'][0]['Statut'][0][s][0].encode('utf-8')}) for s in range(len(tableau[dernierIdx]['CQ'][0]['NomSeq'][0])) if len(tableau[dernierIdx]['CQ'][0]['NomSeq'][0][s]) > 0 and seq == tableau[dernierIdx]['CQ'][0]['NomSeq'][0][s][0].encode('utf-8')] #[dlisteNoire.update({seq: tableau[dernierIdx]['CQ'][0]['Anomalie'][0][s]}) for s in range(len(tableau[dernierIdx]['CQ'][0]['NomSeq'][0])) if len(tableau[dernierIdx]['CQ'][0]['NomSeq'][0][s]) > 0 and seq == tableau[dernierIdx]['CQ'][0]['NomSeq'][0][s][0].encode('utf-8')] and tableau[dernierIdx]['CQ'][0]['Statut'][0][s][0].encode('utf-8') == 'Invalide'] for seq in dSeq.iterkeys(): if len(dSeq[seq]) > 0: Chemin = dSeq[seq].split('/') Chemin.pop() Chemin = "/".join(Chemin) dSeq.update({seq: Chemin}) del Chemin ############################################ En-tete #################################################### entete_logo = [[logo_OxyTC, logo_CHU, logo_Gin, logo_Irmage]] entete = Table(entete_logo) entete.hAlign = 'CENTER' rapport.append(entete) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append(Paragraph(100 * '=', styles['Center'])) rapport.append(Spacer(0 * mm, 5 * mm)) # (width, height) rapport.append( Paragraph('Localisation du centre : ' + centre, styles['Center'])) rapport.append( Paragraph('Date du rapport : ' + date_now.strftime("%Y/%m/%d"), styles['Center'])) rapport.append( Paragraph('Nom du traiteur d"image : ' + NomTraiteur, styles['Center'])) rapport.append(Spacer(0 * mm, 18 * mm)) # (width, height) ########################################### Résumé ##################################################" rapport.append(Paragraph('<b><u>Résumé :', styles['Left'])) rapport.append(Paragraph(140 * '-', styles['Center'])) # Informations générales rapport.append(Paragraph('<u>Informations générales :', styles['Indent'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) for cle, info in dGen.iteritems(): rapport.append( Table([[ Paragraph(cle + ' : ', styles['Indent2']), Paragraph(info, styles['Left']) ]])) rapport.append( Table([[ Paragraph('Machine IRM :', styles['Indent2']), Paragraph(MarqueMachine + ' ' + ChampMachine + 'T', styles['Left']) ]])) if 'Patient' in dGen['Etiologie']: rapport.append( Table([[ Paragraph('Date du traumatisme : ', styles['Indent2']), Paragraph('Inconnu', styles['Left']) ]])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append(Paragraph(140 * '-', styles['Center'])) # Résultat du controle qualité rapport.append(Paragraph('<u>Controle qualité :', styles['Indent'])) for seq, chemin in dSeq.iteritems(): if len(chemin) > 0 and tableau[dernierIdx]['CQ'][0]['Statut'][0][ didSeq[seq]][0].encode('utf-8') == 'OK': resultat_protocol = Table([[ Paragraph('Respect du protocole ' + seq + ' : ', styles['Indent2']), logo_OK ]]) resultat_protocol.hAlign = 'CENTER' rapport.append(resultat_protocol) else: if len(chemin) > 0: resultat_protocol = Table([[ Paragraph('Respect du protocole ' + seq + ' : ', styles['Indent2']), logo_refus, tableau[dernierIdx]['CQ'][0]['Statut'][0][ didSeq[seq]][0].encode('utf-8') ]]) else: resultat_protocol = Table([[ Paragraph('Respect du protocole ' + seq + ' : ', styles['Indent2']), logo_refus ]]) resultat_protocol.hAlign = 'CENTER' rapport.append(resultat_protocol) if tableau[dernierIdx]['Statut'][0][0].encode('utf-8') == 'OK': resultat_qualite = Table([[ Paragraph('<b>Avis final sur le volontaire : ', styles['Indent2']), logo_OK ]]) else: resultat_qualite = Table([[ Paragraph('<b>Avis final sur le volontaire : ', styles['Indent2']), logo_refus ]]) resultat_qualite.hAlign = 'CENTER' rapport.append(resultat_qualite) ligneresult = rapport.index(resultat_qualite) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append(Paragraph(80 * '=', styles['Center'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append(PageBreak()) ########################################### Analyse des champs DICOM ################################# rapport.append(Paragraph('<b><u>Analyse des champs DICOM:', styles['Left'])) rapport.append(Paragraph(140 * '-', styles['Center'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) # Paramètres for seq, Chemin in dSeq.iteritems(): rapport.append(Paragraph('<u>' + seq, styles['Indent'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) if len(Chemin) > 0 and len( glob.glob(Path + Chemin + "/Différences_Champs_Dicom*")) > 0: Dicomdiff = sio.loadmat( glob.glob(Path + Chemin + "/Différences_Champs_Dicom*")[0]) #Dicomdifbis = Dicomdiff['Differencebis'] rapport.append( Paragraph( str(Dicomdiff['NbC'][0][0]) + ' champs DICOM comparés', styles['Indent2'])) NBmanquename = Dicomdiff['NBmanquename'] if len(NBmanquename) > 0 and len(NBmanquename[0]) > 10: NBmanquename = NBmanquename[0] rapport.append( Paragraph( str(len(NBmanquename)) + ' champs DICOM mineurs, manquants par rapport à la référence du centre', styles['Indent2'])) ListeChampsManquant = [] for champs in NBmanquename: ListeChampsManquant.append( Paragraph('-' + champs[0].encode('utf-8'), styles['Center'])) if len(ListeChampsManquant) > 2: NomChampsManquant = Table([ListeChampsManquant]) rapport.append(NomChampsManquant) ListeChampsManquant = [] rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) # rapport.append(Paragraph(140*'-',styles['Center'])) # rapport.append(Spacer(0*mm, 2*mm)) # (width, height) # #Alertes Liste Noire if len(tableau[dernierIdx]['CQ'][0]['Anomalie'][0][didSeq[seq]] ) > 0 and tableau[dernierIdx]['CQ'][0]['Statut'][0][ didSeq[seq]][0].encode('utf-8') != 'OK': rapport.append(Paragraph('<u>Alertes :', styles['Indent2Red'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) TabEntete = Table([[ Paragraph('<b>Champs DICOM', styles['Center']), Paragraph('<b>Référence', styles['Center']), Paragraph('<b>Sujet', styles['Center']) ]]) rapport.append(TabEntete) for i in range( len(tableau[dernierIdx]['CQ'][0]['Anomalie'][0][ didSeq[seq]])): try: tab2 = tableau[dernierIdx]['CQ'][0]['Anomalie'][0][ didSeq[seq]][i][1][0].encode('utf-8') except AttributeError: tab2 = str(tableau[dernierIdx]['CQ'][0]['Anomalie'][0][ didSeq[seq]][i][1][0][0]) try: tab3 = tableau[dernierIdx]['CQ'][0]['Anomalie'][0][ didSeq[seq]][i][2][0].encode('utf-8') except AttributeError: tab3 = str(tableau[dernierIdx]['CQ'][0]['Anomalie'][0][ didSeq[seq]][i][2][0][0]) ListeNoire = Table([[ Paragraph( tableau[dernierIdx]['CQ'][0]['Anomalie'][0][ didSeq[seq]][i][0][0].encode('utf-8'), styles['Center']), Paragraph(tab2, styles['Center']), Paragraph(tab3, styles['CenterRed']) ]]) rapport.append(ListeNoire) ListeNoire = [] del tab2, tab3 if len(tableau[dernierIdx]['CQ'][0]['DirEncPhase'][0][didSeq[seq]] [0]) > 0 and tableau[dernierIdx]['CQ'][0]['DirEncPhase'][0][ didSeq[seq]][0].encode('utf-8') == 'Erreur' and tableau[ dernierIdx]['CQ'][0]['Statut'][0][ didSeq[seq]][0].encode('utf-8') != 'OK': rapport.append( Paragraph( 'La direction d"encodage de phase de cette séquence de diffusion ne correspond pas au protocole demandé', styles['Indent2Red'])) if tableau[dernierIdx]['CQ'][0]['Statut'][0][ didSeq[seq]][0].encode('utf-8') == 'OK': rapport.append( Paragraph( 'Pas de différences éliminatoires par rapport au protocole demandé', styles['Indent2'])) else: rapport.append( Paragraph('Pas d"analyse de champs DICOM disponible', styles['Indent2'])) if len(Chemin) == 0: rapport.append( Paragraph('Sujet référence ou données manquantes', styles['Indent2'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append(Paragraph(140 * '-', styles['Center'])) rapport.append(PageBreak()) # Critères qualité if os.path.exists(Path + centre + '/Sujets/' + sujet + '/QC_crit.png'): rapport.append(PageBreak()) rapport.append(Paragraph(80 * '=', styles['Center'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) QCcrit = Image(Path + centre + '/Sujets/' + sujet + '/QC_crit.png', 200 * mm, 175 * mm) QCcrit.hAlign = 'CENTER' rapport.append( Paragraph('<b>Critères qualité inter-sujets & intra-centre', styles['Left'])) rapport.append(Paragraph(140 * '-', styles['Center'])) rapport.append(Spacer(0 * mm, 1 * mm)) # (width, height) rapport.append(QCcrit) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append( Paragraph( '<b>SNR</b> : Valeur moyenne de l"image dans le cerveau divisée par l"écart type de l"image dans l"air (hors de la tete). <u>Les valeurs hautes sont préférables</u>.', styles['Left'])) rapport.append( Paragraph( '<b>CNR</b> : Différence d"intensité moyenne entre la matière grise et la matière blanche divisée par l"ecart type de l"image dans l"air. <u>Les valeurs hautes sont préférables</u>.', styles['Left'])) rapport.append( Paragraph( '<b>EFC</b> : L"EFC utilise l"entropie de Shannon de l"intensités des voxels comme une indication du ghosting et du flou induit par les mouvements de la tete. <u>Les valeurs faibles sont préférables</u>.[Atkinson 1997]', styles['Left'])) rapport.append( Paragraph( '<b>FBER</b> : Définit comme l"énergie moyenne des valeurs à l"intérieur de la tete par rapport à l"extérieur de la tete. <u>Les valeurs hautes sont préférables</u>.', styles['Left'])) #######################################################Analyse DTI######################################################################## if len(tableau[dernierIdx]['EddyCorr'][0]['Statut'][0] [0]) > 0 and 'OK' in tableau[dernierIdx]['EddyCorr'][0]['Statut'][ 0][0][0].encode('utf-8'): rapport.append(PageBreak()) rapport.append(Paragraph(80 * '=', styles['Center'])) rapport.append(Paragraph('<b><u>Qualité des données:', styles['Left'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append(Paragraph(140 * '-', styles['Center'])) # Mesures globales if os.path.exists(Path + centre + '/Sujets/' + sujet + '/DTI_Pretrt/MesureQualite.mat'): test2 = sio.loadmat(Path + centre + '/Sujets/' + sujet + '/DTI_Pretrt/MesureQualite.mat') Mesures = test2['Mesures'] if Mesures[5][0] < pow(Mesures[8][0], 1.0 / 3.0): meanmvmtimresult = logo_OK else: meanmvmtimresult = logo_refus #rapport.remove(resultat_qualite) #resultat_qualite = Table([[Paragraph('<b>Qualités des données : ', styles['Indent2']), logo_refus]]) #resultat_qualite.hAlign = 'CENTER' #rapport.insert(ligneresult, resultat_qualite) if Mesures[6][0] < 1.5 * pow(Mesures[8][0], 1.0 / 3.0): maxmvmtimresult = logo_OK else: maxmvmtimresult = logo_refus #rapport.remove(resultat_qualite) #resultat_qualite = Table([[Paragraph('<b>Qualités des données : ', styles['Indent2']), logo_refus]]) #resultat_qualite.hAlign = 'CENTER' #rapport.insert(ligneresult, resultat_qualite) meanmvmtimresult.hAlign = 'CENTER' maxmvmtimresult.hAlign = 'CENTER' TabMesures = [ [ Paragraph('<b>Paramètre : ', styles['Left']), Paragraph('<b>Valeur', styles['Left']), Paragraph('<b>Normes', styles['Center']), Paragraph('<b>Résultat', styles['Left']) ], [ Paragraph('Volume cérébral : ', styles['Left']), Paragraph('{:.2e} mm<sup>3'.format(int(Mesures[4][0])), styles['Left']), Paragraph('', styles['Center']), Paragraph('', styles['Center']) ], [ Paragraph('MD Matière grise : ', styles['Left']), Paragraph('{:.2e} mm<sup>2</sup>/s'.format(Mesures[0][0]), styles['Left']), Paragraph('', styles['Center']), Paragraph('', styles['Center']) ], [ Paragraph('MD Matière blanche : ', styles['Left']), Paragraph('{:.2e} mm<sup>2</sup>/s'.format(Mesures[1][0]), styles['Left']), Paragraph('', styles['Center']), Paragraph('', styles['Center']) ], [ Paragraph('FA Matière grise : ', styles['Left']), Paragraph('{:.2e}'.format(Mesures[2][0]), styles['Left']), Paragraph('', styles['Center']), Paragraph('', styles['Center']) ], [ Paragraph('FA Matière blanche : ', styles['Left']), Paragraph('{:.2e}'.format(Mesures[3][0]), styles['Left']), Paragraph('', styles['Center']), Paragraph('', styles['Center']) ], [ Paragraph('Mouvement moyen dans la diffusion :', styles['Left']), Paragraph('{:.3f}'.format(Mesures[5][0]), styles['Left']), Paragraph('< {:.1f}'.format(pow(Mesures[8][0], 1.0 / 3.0)), styles['Center']), meanmvmtimresult ], [ Paragraph('Mouvement maximal dans la diffusion :', styles['Left']), Paragraph('{:.3f}'.format(Mesures[6][0]), styles['Left']), Paragraph( '< {:.1f}'.format(1.5 * pow(Mesures[8][0], 1.0 / 3.0)), styles['Center']), maxmvmtimresult ] ] Tabmesures = Table(TabMesures) rapport.append(Tabmesures) else: rapport.append( Paragraph( '<b>Informations sur les mesures globales manquantes', styles['Indent2'])) if len(tableau[dernierIdx]['CQ'][0][0][didSeq['DTI']] ['NbCorrCoupe']) > 0: NbCCoupe = tableau[dernierIdx]['CQ'][0][0][ didSeq['DTI']]['NbCorrCoupe'][0][0] else: NbCCoupe = 0 NbCoupe = tableau[dernierIdx]['CQ'][0][0][ didSeq['DTI']]['NbCoupe'][0][0] NbVol = tableau[dernierIdx]['CQ'][0][0][didSeq['DTI']]['NbVol'][0][0] NbVolSupp = tableau[dernierIdx]['CQ'][0][0][didSeq['DTI']]['VolSupp'] n = 0 if os.path.exists(Path + centre + '/Sujets/' + sujet + '/DTI_Pretrt/DTI_esc.nii.eddy_outlier_report'): n = sum( 1 for _ in open(Path + centre + '/Sujets/' + sujet + '/DTI_Pretrt/DTI_esc.nii.eddy_outlier_report')) NbCorrCoupe = n # pour la version suivante ou on force la correction eddy #NbCorrCoupe = NbCCoupe + n else: NbCorrCoupe = NbCCoupe TxCoupe = NbCorrCoupe / float(int(NbCoupe) * int(NbVol)) TxVol = len(NbVolSupp) / float(int(NbVol)) if TxCoupe < SeuilCoupe: txcoupeimresult = logo_OK else: txcoupeimresult = logo_refus #rapport.remove(resultat_qualite) #resultat_qualite = Table([[Paragraph('<b>Qualités des données : ', styles['Indent2']), logo_refus]]) #resultat_qualite.hAlign = 'CENTER' #rapport.insert(ligneresult, resultat_qualite) if TxVol < SeuilVol: txvolimresult = logo_OK else: txvolimresult = logo_refus #rapport.remove(resultat_qualite) #resultat_qualite = Table([[Paragraph('<b>Qualités des données : ', styles['Indent2']), logo_refus]]) #resultat_qualite.hAlign = 'CENTER' #rapport.insert(ligneresult, resultat_qualite) txcoupeimresult.hAlign = 'CENTER' txvolimresult.hAlign = 'CENTER' rapport.append(Spacer(0 * mm, 1 * mm)) # (width, height) TabCorr = [[ Paragraph('Taux de coupes corrigées : ', styles['Left']), Paragraph( str(TxCoupe) + ' (' + str(NbCorrCoupe) + '/' + str(int(NbCoupe) * int(NbVol)) + ')', styles['Left']), Paragraph(str(SeuilCoupe), styles['Center']), txcoupeimresult ], [ Paragraph('Taux de directions supprimées : ', styles['Left']), Paragraph( str(TxVol) + ' (' + str(len(NbVolSupp)) + '/' + str(int(NbVol)) + ')', styles['Left']), Paragraph(str(SeuilVol), styles['Center']), txvolimresult ]] Tabcorr = Table(TabCorr) rapport.append(Tabcorr) rapport.append(PageBreak()) #Figure récapitulative QC rapport.append(Paragraph(140 * '-', styles['Center'])) rapport.append(Spacer(0 * mm, 1 * mm)) # (width, height) if os.path.exists(Path + centre + '/Sujets/' + sujet + '/DTI_Pretrt/QC.png'): QC = Image( Path + centre + '/Sujets/' + sujet + '/DTI_Pretrt/QC.png', 195 * mm, 190 * mm) QC.hAlign = 'CENTER' rapport.append(QC) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append( Paragraph( '<b>Signal moyen des coupes axiales</b> : Intensité moyenne des voxels intra-cérébraux de chaque coupe pour chaque direction. Les barres d"erreur bleues et vertes correspondent respectivement à 3 et 5 fois l"écart types calculé sur toutes les directions.', styles['Left'])) rapport.append( Paragraph( '<b>Direction gradients de diffusion</b> : Directions des gradients de diffusion sur une sphère. Les directions supprimées sont affichées en rouge.', styles['Left'])) rapport.append( Paragraph( '<b>Résidu du modèle de tenseur</b> Différence cumulée des intensités de voxels intra-cérébraux entre l"image de diffusion et l"estimation réalisée à partir du tenseur de diffusion pour chaque coupe et chaque direction.', styles['Left'])) rapport.append( Paragraph( '<b>Le mouvement total</b> : Mesure du mouvement dans chaque volume calculée à partir du déplacement de chaque voxel, en moyennant les carrés de ces déplacements à travers les voxels intracérébraux et en calculant la racine carrée de ce résultat. Le mouvement absolu représente le mouvement(Root Mean Squared) par rapport à la première direction. Le mouvement relatif représente le mouvement par rapport à la direction précédente', styles['Left'])) rapport.append( Paragraph( '<b>Rotation et Translation</b> : Paramètres de translation et de rotations utilisés dans la coregistration des différentes directions sur la première direction.', styles['Left'])) if os.path.exists(Path + centre + '/Sujets/' + sujet + '/DTI_Pretrt/QC.png'): rapport.append(PageBreak()) rapport.append(Paragraph(140 * '-', styles['Center'])) rapport.append(Spacer(0 * mm, 1 * mm)) # (width, height) QC2 = Image( Path + centre + '/Sujets/' + sujet + '/DTI_Pretrt/QC2.png', 200 * mm, 150 * mm) QC2.hAlign = 'CENTER' rapport.append(QC2) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) rapport.append( Paragraph( '<b>Intensité moyenne des coupes paires et impaires</b> : Distribution des intensités moyennes pour les coupes paires et les coupes impaires.', styles['Left'])) rapport.append( Paragraph( '<b>Histogramme sphérique de la direction de la V1 pour tous les voxels du cerveau</b> : Le nombre de voxel partageant la même direction principale V1 est représenté sur une sphére', styles['Left'])) # Figure récapitulative par centre FAMDROI if os.path.exists(Path + centre + '/Sujets/' + sujet + '/FAMDROI.png'): rapport.append(PageBreak()) rapport.append(Paragraph(80 * '=', styles['Center'])) rapport.append(Spacer(0 * mm, 2 * mm)) # (width, height) FAMDROI = Image( Path + centre + '/Sujets/' + sujet + '/FAMDROI.png', 215 * mm, 215 * mm) FAMDROI.hAlign = 'CENTER' rapport.append( Paragraph('<b>Mesures inter-sujets & intra-centre', styles['Left'])) rapport.append(Paragraph(140 * '-', styles['Center'])) rapport.append(Spacer(0 * mm, 1 * mm)) # (width, height) rapport.append(FAMDROI) # rapport.append(Spacer(0*mm, 2*mm)) # (width, height) ## rapport.append(PageBreak()) ## rapport.append(Paragraph('<b>Index des ROI',styles['Center'])) ## labelAtlas= sio.loadmat(Path + "ROIsAtlas2.mat") ## Tablabel=[[Paragraph('<b>Matière Grise',styles['Right']),Paragraph('',styles['Center']),Paragraph('<b>Matière Blanche',styles['Right'])], ## [Paragraph('<b>N° de la ROI',styles['Left']),Paragraph('<b>Nom de la ROI',styles['Left']),Paragraph('<b>N° de la ROI',styles['Left']),Paragraph('<b>Nom de la ROI',styles['Left'])]] ## rapport.append(Table(Tablabel)) ## for i in range(len(labelAtlas['ROIMG'])): ## try: ## labelROIMB=labelAtlas['ROIMB'][i][0][0].encode('utf-8') ## numlabelMB= i+ 1 + len(labelAtlas['ROIMG']) ## except: ## labelROIMB='' ## numlabelMB='' ## Tablabel=[[Paragraph(str(i+1),styles['Left']),Paragraph(labelAtlas['ROIMG'][i][0][0].encode('utf-8'),styles['Left']),Paragraph(str(numlabelMB),styles['Left']),Paragraph(labelROIMB,styles['Left'])]] ## rapport.append(Table(Tablabel)) page.build(rapport, canvasmaker=PageNumCanvas)
def pdfmaker(sectorname, date): doc = SimpleDocTemplate("C:/storyboards/" + sectorname + " - " + date + "-email.pdf", rightMargin=10, leftMargin=10, topMargin=10, bottomMargin=10, pagesize=(A4[1], A4[0])) # initialise empty list (will become our report) main_pdf = [] # this lets us alter para styles to prevent code duplication styles = getSampleStyleSheet() styles.add( ParagraphStyle(name="header", fontSize=24, textColor='#003087', vAlign='MIDDLE')) styles.add(ParagraphStyle(name='table', fontSize=8)) styles.add( ParagraphStyle(name='tablehead', fontSize=8, textColor='#FFFFFF', vAlign='MIDDLE')) styles.add( ParagraphStyle(name='execsum', fontSize=14, textColor='#003087', borderColor=colors.HexColor('#003087'), leading=14)) styles.add( ParagraphStyle(name='bottomText', fontSize=14, textColor='#003087', leading=14, borderColor=colors.HexColor('#003087'), linkUnderline=1, alignment=TA_CENTER)) logo = Image('ggclogo.jpg', 0.5 * inch * 1.5, 0.45 * inch * 1.5) header = Paragraph(sectorname + " - " + date + " Storyboard", styles['header']) headertable = Table([[logo, header]]) headertable.setStyle([('VALIGN', (1, 0), (1, 0), 'TOP'), ('FONTSIZE', (1, 0), (1, 0), 24), ('TEXTCOLOR', (1, 0), (1, 0), colors.HexColor('#003087')), ('FONTNAME', (1, 0), (1, 0), 'Arial'), ('ALIGN', (0, 0), (0, -1), 'LEFT'), ('ALIGN', (1, 0), (1, 0), 'RIGHT')]) main_pdf.append(headertable) exec_summary = "<b>Executive Summary</b>: " tabledata = [] with open('C:/storyboards/template.txt') as template: for line in template: if "*" in line: continue if "[Exec Summary]" in line: line = line.strip().split(" = ") exec_summary += line[1] continue line = line.strip().split(",") line[0] = "<i>" + line[0] + "</i>" line[5] = "<b>" + line[5] + "</b>" print(line) tabledata.append(line) print(tabledata) exec_text = Paragraph(exec_summary, styles['execsum']) exec_summary = Table([[exec_text]]) exec_summary.setStyle([('BOX', (0, 0), (0, 0), 0.006 * inch, (0, 0, 0)), ('BOTTOMPADDING', (0, 0), (0, 0), 12)]) main_pdf.append(Spacer(0, 3)) main_pdf.append(exec_summary) main_pdf.append(Spacer(0, 3)) blue_line = HRFlowable(width="100%", thickness=1, lineCap='round', color=colors.HexColor('#003087'), spaceBefore=1, spaceAfter=1, hAlign='CENTER', vAlign='BOTTOM', dash=None) main_pdf.append(blue_line) main_pdf.append(Spacer(0, 3)) tableheaders = [ 'Date', 'Action', 'Timeframe', 'Responsible Person', 'Update', 'Status' ] tableheaders = [Paragraph(x, styles['tablehead']) for x in tableheaders] print(tableheaders) tabledata = [[Paragraph(x, styles['table']) for x in item] for item in tabledata] tabledata.insert(0, tableheaders) target_table = Table(tabledata, colWidths=2.45 * cm) q = (len(tabledata[0]) - 1, len(tabledata) - 1) target_table.setStyle([ ('BACKGROUND', (0, 0), (q[0], 0), colors.HexColor("#003087")), ('TEXTCOLOR', (0, 0), (q[0], 0), colors.HexColor("#E8EDEE")), ('FONTSIZE', (0, 1), (q[0], 1), 8), ('ALIGN', (0, 0), (q[0], q[1]), 'CENTER'), ('VALIGN', (0, 0), (q[0], q[1]), 'MIDDLE'), ('BOX', (0, 1), (q[0], q[1]), 0.006 * inch, colors.HexColor("#003087")), ('BOX', (0, 0), (q[0], 0), 0.006 * inch, colors.HexColor("#003087")) ]) w, h = target_table.wrap(0, 0) print(w / inch, h / inch) statmand_graph = Image('C:/storyboards/graph1.jpg', w - 55, h) wrapperTable1 = Table([[statmand_graph, target_table]]) wrapperTable1.setStyle([('LEFTPADDING', (1, 0), (1, 0), 5), ('LEFTPADDING', (0, 0), (0, 0), 5), ('RIGHTPADDING', (0, 0), (0, 0), 0), ('BOX', (0, 0), (0, 0), 0.006 * inch, colors.HexColor("#003087"))]) main_pdf.append(wrapperTable1) main_pdf.append(Spacer(0, 6)) table_dataset = build_table() data_table = Table(np.vstack( (list(table_dataset), np.array(table_dataset))).tolist(), colWidths=(3.68 * cm)) q = (len(table_dataset.columns) - 1, len(table_dataset)) print(table_dataset) data_table.setStyle( TableStyle([ ('BACKGROUND', (0, 0), (q[0], 0), colors.HexColor("#003087")), ('TEXTCOLOR', (0, 0), (q[0], 0), colors.HexColor("#E8EDEE")), ('FONTSIZE', (0, 1), (q[0], q[1]), 8), ('ALIGN', (1, 0), (q[0], q[1]), 'CENTER'), ('BOX', (0, 1), (q[0], q[1]), 0.006 * inch, colors.HexColor("#003087")), ('BOX', (0, 0), (q[0], 0), 0.006 * inch, colors.HexColor("#003087")) ])) w, h = data_table.wrap(0, 0) absence_graph = Image('C:/storyboards/graph2.jpg', w - 41, h) wrapperTable2 = Table([[absence_graph, data_table]]) wrapperTable2.setStyle([('LEFTPADDING', (1, 0), (1, 0), 5), ('LEFTPADDING', (0, 0), (0, 0), 5), ('BOX', (0, 0), (0, 0), 0.006 * inch, colors.HexColor("#003087")), ('RIGHTPADDING', (0, 0), (0, 0), 0)]) main_pdf.append(wrapperTable2) main_pdf.append(Spacer(0, 6)) w, h = wrapperTable2.wrap(0, 0) workforce_text = Paragraph( "This document was produced by the NHS GGC Workforce Planning & Analytics team. " '<br/>For more information or for ad-hoc data requests, please email ' '<a href = "mailto:[email protected]">Steven Munce</a>.', styles['bottomText']) workforce_blurb = Table([[workforce_text]], colWidths=w) workforce_blurb.setStyle([ ('BOX', (0, 0), (0, 0), 0.006 * inch, colors.HexColor("#003087")), ('BOTTOMPADDING', (0, 0), (0, 0), 12), ]) main_pdf.append(workforce_blurb) doc.build(main_pdf) print(q)
def create_pdf(user_id: int, title: str, table: list, technical_specific: list, page_orientation: str = 'portrait', technical_specific_is_standard: bool = True): directory = (os.getcwd()).replace('\\', '/') + '/users_files/' + f'{user_id}/' page_orientation, page_width, page_height = get_page_sizes(page_orientation) set_time_in_pdf_page = get_time_on_user(user_id) # создаем объект документа с размером страницы A4 title2: str = title.replace(':', ', ') file_name = f'{title2}.pdf' doc = SimpleDocTemplate(directory + file_name, pagesize=page_orientation, title='Испытание зернового состава', author='LabyLab Inc', leftMargin=20, rightMargin=20, topMargin=5, bottomMargin=5) elements_on_pdf_page = [] # заглавие main_title = 'Испытание зернового состава' elements_on_pdf_page.append(Paragraph(main_title, paragraph_styles['FontBold'])) second_title = zaglavie[title] elements_on_pdf_page.append(Paragraph(second_title, paragraph_styles['FontBoldSimple'])) # дата и время time_in_document = set_time_in_pdf_page.strftime('%d.%m.%Y, время %H:%M') elements_on_pdf_page.append(Paragraph(time_in_document, paragraph_styles['FontRegularRIGHT'])) # таблица kol_vo_elements = len(table[0]) column_width = page_width / kol_vo_elements main_table = Table(table, colWidths=column_width, rowHeights=36, style=main_table_style) elements_on_pdf_page.append(main_table) # тех условия elements_on_pdf_page.append(Paragraph('Тех. условия', paragraph_styles['FontBoldSimple'])) if technical_specific_is_standard: technical_specific = update_technical_specific(technical_specific) technical_specific_in_pdf = Table(technical_specific, colWidths=page_width / 2, rowHeights=26, style=technical_specific_style) else: technical_specific_in_pdf = Table(technical_specific, colWidths=page_width, rowHeights=36, style=technical_specific_style) elements_on_pdf_page.append(technical_specific_in_pdf) elements_on_pdf_page.append(Paragraph('_', paragraph_styles['FontBoldSimple'])) # картинка for file in os.scandir(directory): if file.name.endswith(".png"): graphic = Image(directory + file.name, width=page_width, height=page_height) elements_on_pdf_page.append(graphic) # ссылка на бота link_to_this_bot = '<link href="' + bot_url + '">' + f'Создано в телеграм боте @{bot_name}' + '</link>' elements_on_pdf_page.append(Paragraph(link_to_this_bot, paragraph_styles['FontRegularRIGHTsimple'])) doc.build(elements_on_pdf_page) return file_name
def render_workout_day(day, nr_of_weeks=7, images=False, comments=False, only_table=False): ''' Render a table with reportlab with the contents of the training day :param day: a workout day object :param nr_of_weeks: the numbrer of weeks to render, default is 7 :param images: boolean indicating whether to also draw exercise images in the PDF (actually only the main image) :param comments: boolean indicathing whether the exercise comments will be rendered as well :param only_table: boolean indicating whether to draw a table with space for weight logs or just a list of the exercises ''' # If rendering only the table, reset the nr of weeks, since these columns # will not be rendered anyway. if only_table: nr_of_weeks = 0 data = [] # Init some counters and markers, this will be used after the iteration to # set different borders and colours day_markers = [] group_exercise_marker = {} # Background colour for days # Reportlab doesn't use the HTML hexadecimal format, but has a range of # 0 till 1, so we have to convert here. header_colour = colors.Color(int('73', 16) / 255.0, int('8a', 16) / 255.0, int('5f', 16) / 255.0) set_count = 1 day_markers.append(len(data)) p = Paragraph(u'<para align="center">%(days)s: %(description)s</para>' % {'days': day['days_of_week']['text'], 'description': day['obj'].description}, styleSheet["Bold"]) data.append([p]) # Note: the _('Date') will be on the 3rd cell, but since we make a span # over 3 cells, the value has to be on the 1st one data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks) data.append([_('Nr.'), _('Exercise'), _('Reps')] + [_('Weight')] * nr_of_weeks) # Sets exercise_start = len(data) for set in day['set_list']: group_exercise_marker[set['obj'].id] = {'start': len(data), 'end': len(data)} # Exercises for exercise in set['exercise_list']: group_exercise_marker[set['obj'].id]['end'] = len(data) # Process the settings if exercise['has_weight']: setting_out = [] for i in exercise['setting_text'].split(u'–'): setting_out.append(Paragraph(i, styleSheet["Small"], bulletText='')) else: setting_out = Paragraph(exercise['setting_text'], styleSheet["Small"]) # Collect a list of the exercise comments item_list = [Paragraph('', styleSheet["Small"])] if comments: item_list = [ListItem(Paragraph(i, style=styleSheet["ExerciseComments"])) for i in exercise['comment_list']] # Add the exercise's main image image = Paragraph('', styleSheet["Small"]) if images: if exercise['obj'].main_image: # Make the images somewhat larger when printing only the workout and not # also the columns for weight logs if only_table: image_size = 2 else: image_size = 1.5 image = Image(exercise['obj'].main_image.image) image.drawHeight = image_size * cm * image.drawHeight / image.drawWidth image.drawWidth = image_size * cm # Put the name and images and comments together exercise_content = [Paragraph(exercise['obj'].name, styleSheet["Small"]), image, ListFlowable(item_list, bulletType='bullet', leftIndent=5, spaceBefore=7, bulletOffsetY=-3, bulletFontSize=3, start='square')] data.append([set_count, exercise_content, setting_out] + [''] * nr_of_weeks) set_count += 1 table_style = [('FONT', (0, 0), (-1, -1), 'OpenSans'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (-1, -1), 2), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 3), ('BOTTOMPADDING', (0, 0), (-1, -1), 2), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), # Header ('BACKGROUND', (0, 0), (-1, 0), header_colour), ('BOX', (0, 0), (-1, -1), 1.25, colors.black), ('BOX', (0, 1), (-1, -1), 1.25, colors.black), ('SPAN', (0, 0), (-1, 0)), # Cell with 'date' ('SPAN', (0, 1), (2, 1)), ('ALIGN', (0, 1), (2, 1), 'RIGHT')] # Combine the cells for exercises on the same superset for marker in group_exercise_marker: start_marker = group_exercise_marker[marker]['start'] end_marker = group_exercise_marker[marker]['end'] table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE')) table_style.append(('SPAN', (0, start_marker), (0, end_marker))) # Set an alternating background colour for rows with exercises. # The rows with exercises range from exercise_start till the end of the data # list for i in range(exercise_start, len(data) + 1): if not i % 2: table_style.append(('BACKGROUND', (1, i - 1), (-1, i - 1), colors.lavender)) # Put everything together and manually set some of the widths t = Table(data, style=table_style) if len(t._argW) > 1: if only_table: t._argW[0] = 0.6 * cm # Numbering t._argW[1] = 8 * cm # Exercise t._argW[2] = 3.5 * cm # Repetitions else: t._argW[0] = 0.6 * cm # Numbering t._argW[1] = 4 * cm # Exercise t._argW[2] = 3 * cm # Repetitions return KeepTogether(t)
def pdf(): file = request.files['uploadfile'] target = os.path.join(app_ROOT, 'static/pdfs/') doc = SimpleDocTemplate(target + "form_letter.pdf", pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) Story = [] logo = "static/image/file" magName = "Pythonista" issueNum = 12 subPrice = "99.00" limitedDate = "03/05/2010" freeGift = "tin foil hat" formatted_time = time.ctime() full_name = "Mike Driscoll" address_parts = ["411 State St.", "Marshalltown, IA 50158"] im = Image(logo, 2 * inch, 2 * inch) Story.append(im) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # Create return address ptext = '<font size=12>%s</font>' % full_name Story.append(Paragraph(ptext, styles["Normal"])) for part in address_parts: ptext = '<font size=12>%s</font>' % part.strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size=12>Dear %s:</font>' % full_name.split()[0].strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size=12>We would like to welcome you to our subscriber base for %s Magazine! \ You will receive %s issues at the excellent introductory price of $%s. Please respond by\ %s to start receiving your subscription and get the following free gift: %s.</font>' % ( magName, issueNum, subPrice, limitedDate, freeGift) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) ptext = '<font size=12>Thank you very much and we look forward to serving you.</font>' Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) ptext = '<font size=12>Sincerely,</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 48)) ptext = '<font size=12>Ima Sucker</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) doc.build(Story) return send_file(mimetype='application/pdf')
def printTopdf(name,course): fileName="../Course_completion_Certificate_"+name+".pdf" doc = SimpleDocTemplate(fileName,pagesize=landscape(letter)) pdfmetrics.registerFont(TTFont('chsFont', 'ALGER.TTF')) pdfmetrics.registerFont(TTFont('conFont', 'BRADHITC.TTF')) #pdfmetrics.registerFont(TTFont('tnFont', 'times.TTF')) Story=[] logo = "logo.jpg" im = Image(logo, 4*inch, 2*inch) Story.append(im) line1="CERTIFICATE OF COMPLETION" Story.append(Spacer(1,12)) styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) pltext = '<font size=34>%s</font>' % line1 ptext = '<font name="chsFont">%s</font>' % pltext Story.append(Paragraph(ptext, styles["Center"])) Story.append(Spacer(1,72)) firstLine="This Certificate is Presented to "+" \""+name.upper()+"\"" if (len(firstLine)<72): for i in range(72-len(firstLine)): firstLine+=" " styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) pltext = '<font size=16>%s</font>' % firstLine ptext = '<font name="conFont">%s</font>' % pltext Story.append(Paragraph(ptext, styles["Center"])) Story.append(Spacer(1,42)) secondLine="For Sucessfully Completing the "+" \""+course.upper()+"\"" if (len(secondLine)<72): for i in range(72-len(secondLine)): secondLine+=" " styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) pltext = '<font size=16>%s</font>' % secondLine ptext = '<font name="conFont">%s</font>' % pltext Story.append(Paragraph(ptext, styles["Center"])) Story.append(Spacer(1,42)) Story.append(Spacer(1,42)) d=str(datetime.datetime.now()) date="Date: "+d[:10] styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_LEFT)) pltext = '<font size=14>%s</font>' % date ptext = '<font name="conFont">%s</font>' % pltext Story.append(Paragraph(ptext, styles["Center"])) styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_RIGHT)) pltext = '<font size=14>%s</font>' % "Signature" ptext = '<font name="conFont">%s</font>' % pltext Story.append(Paragraph(ptext, styles["Center"])) doc.build(Story)
def get_image(path, width=1 * mm): img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) return Image(path, width=width, height=(width * aspect))
rightMargin=1 * cm, topMargin=1 * cm, bottomMargin=1 * cm) styles = define_paragraph_styles() # container for the 'Flowable' objects elements = [] elements.append(Paragraph("Load balancer statistics", styles["table_title"])) elements.append(Spacer(1, 1 * cm)) target_table = generate_target_table(styles, target_addresses, chart_data) chart_handle = open(target_chart_filename, 'rb') img = Image(chart_handle, width=(7 * cm) * 2, height=(4 * cm) * 2) hour_chart_handle = open(hour_chart_filename, 'rb') img_hour = Image(hour_chart_handle, width=(7 * cm) * 2, height=(4 * cm) * 2) page_table = Table([[target_table, img], ["", img_hour]]) page_table.setStyle(define_page_table_style()) elements.append(page_table) elements.append(PageBreak()) elements.append( Paragraph("Top 10 requests by total request count", styles["table_title"])) elements.append(Spacer(1, 0.5 * cm)) totals_table = generate_totals_table(styles, day_totals)
def washinglabel(product): ''' Return washinglabel pdf for a product with width: 3cm, length: 10cm Washinglabel contains: - barcode ean - umbrella_product name - colour - size - sku ''' product_title = str(product.umbrella_product) product_colour = 'Colour: {}'.format(product.umbrella_product.colour) product_size = 'Size: {}'.format(product.product_model.size) product_sku = product.sku product_ean = product.ean_code buffer = BytesIO() margin = 1 * mm doc = SimpleDocTemplate(buffer, rightMargin=margin, leftMargin=margin, topMargin=margin, bottomMargin=margin, pagesize=(30 * mm, 100 * mm)) elements = [] styles = stylesheet_washinglabels() ## Hack to add horizontal line style = TableStyle([ ("LINEABOVE", (0, 0), (-1, -1), 1, colors.black), ]) table = Table(['']) table.setStyle(style) elements.append(table) if product.umbrella_product.custom_label_logo is None: elements.append(Spacer(30 * mm, 15 * mm)) else: elements.append(Spacer(30 * mm, 12 * mm)) elements.append(BarCode(value=product_ean, ratio=0.9)) elements.append(Spacer(30 * mm, 10 * mm)) if product.umbrella_product.custom_label_logo is None: elements.append(Paragraph(product_title, styles['Bold'])) elements.append(Paragraph(product_colour, styles['NormalSmall'])) else: logo = product.umbrella_product.custom_label_logo.custom_label_logo_optimised logo_path = logo.path aspect = get_aspect_ratio_from_image_object(logo) elements.append(Image(logo_path, 25 * mm, 25 * mm * aspect)) elements.append(Paragraph(product_title, styles['Bold'])) elements.append(Paragraph(product_size, styles['NormalSmall'])) elements.append(Paragraph(product_sku, styles['NormalSmall'])) doc.build(elements) pdf = buffer.getvalue() buffer.close() return pdf
xSize = 3 ySize = 3 # Give report a title ptext = '<font size=12>%s</font>' % reportTitle Story.append(Paragraph(ptext, styles["Normal"])) # Print time of report creation styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) #Load images and accompanying text information to report for dataPair in dataFilledList: plotImgs = [] # Collect all image paths into variables, lists plotImg = dataFilePath + '/' + dataPair + '_plot' + '.' + plotExt pairImgs = glob.glob(dataFilePath + '/' + dataPair + '*.jpg') pairImgs[:0] = [plotImg] for image in pairImgs: im = Image(image, xSize*inch, ySize*inch) Story.append(im) #Space between each array's data Story.append(Spacer(1, 75)) # Make file and move to project directory doc.build(Story) os.rename(os.getcwd() + '/' + reportTitle + '.pdf', dataFilePath + '/' + reportTitle + '.pdf')
def printClueLogHeaderFooter(canvas, doc, printParams: argparse.Namespace, opPeriod=""): canvas.saveState() styles = getSampleStyleSheet() logoImage = None if os.path.isfile(printParams.printLogoFileName): imgReader = utils.ImageReader(printParams.printLogoFileName) imgW, imgH = imgReader.getSize() imgAspect = imgH / float(imgW) logoImage = Image(printParams.printLogoFileName, width=0.54 * inch / float(imgAspect), height=0.54 * inch) headerTable = [ [ logoImage, printParams.agencyNameForPrint, "Incident: " + printParams.incidentName, "Clue Log - Page " + str(canvas.getPageNumber()) ], [ "", "", "Operational Period: " + str(opPeriod), "Printed: " + time.strftime("%a %b %d, %Y %H:%M") ], ] t = Table(headerTable, colWidths=[x * inch for x in [0.8, 4.2, 2.5, 2.5]], rowHeights=[x * inch for x in [0.3, 0.3]]) t.setStyle( TableStyle([ ("FONT", (1, 0), (1, 1), "Helvetica-Bold"), ("FONTSIZE", (1, 0), (1, 1), 18), ("SPAN", (0, 0), (0, 1)), ("SPAN", (1, 0), (1, 1)), ("LEADING", (1, 0), (1, 1), 20), ("TOPADDING", (1, 0), (1, 0), 0), ("BOTTOMPADDING", (1, 1), (1, 1), 4), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("ALIGN", (1, 0), (1, -1), "CENTER"), ("ALIGN", (0, 0), (0, 1), "CENTER"), ("BOX", (0, 0), (-1, -1), 2, colors.black), ("BOX", (2, 0), (-1, -1), 2, colors.black), ("INNERGRID", (2, 0), (3, 1), 0.5, colors.black), ])) else: headerTable = [ [ logoImage, printParams.agencyNameForPrint, "Incident: " + printParams.incidentName, "Clue Log - Page " + str(canvas.getPageNumber()) ], [ "", "", "Operational Period: " + str(opPeriod), "Printed: " + time.strftime("%a %b %d, %Y %H:%M") ], ] t = Table(headerTable, colWidths=[x * inch for x in [0.0, 5, 2.5, 2.5]], rowHeights=[x * inch for x in [0.3, 0.3]]) t.setStyle( TableStyle([ ("FONT", (1, 0), (1, 1), "Helvetica-Bold"), ("FONTSIZE", (1, 0), (1, 1), 18), ("SPAN", (0, 0), (0, 1)), ("SPAN", (1, 0), (1, 1)), ("LEADING", (1, 0), (1, 1), 20), ("VALIGN", (1, 0), (-1, -1), "MIDDLE"), ("ALIGN", (1, 0), (1, -1), "CENTER"), ("BOX", (0, 0), (-1, -1), 2, colors.black), ("BOX", (2, 0), (-1, -1), 2, colors.black), ("INNERGRID", (2, 0), (3, 1), 0.5, colors.black), ])) w, h = t.wrapOn(canvas, doc.width, doc.height) # self.clueLogMsgBox.setInformativeText("Generating page "+str(canvas.getPageNumber())) QCoreApplication.processEvents() LOG.debug("Page number:" + str(canvas.getPageNumber())) LOG.debug("Height:" + str(h)) LOG.debug("Pagesize:" + str(doc.pagesize)) t.drawOn( canvas, doc.leftMargin, doc.pagesize[1] - h - 0.5 * inch) # enforce a 0.5 inch top margin regardless of paper size LOG.trace("done drawing printClueLogHeaderFooter canvas") canvas.restoreState() LOG.trace("end of printClueLogHeaderFooter")
def consultations(request): queryset = CalendarEvent.objects.all().order_by('start') f = ConsultationFilter(request.GET, queryset=queryset) all_consultations = ConsultationTable(f.qs) RequestConfig(request, paginate={'per_page': 15}).configure(all_consultations) if 'pdf' in request.GET: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="list_of_consultations.pdf"' doc = SimpleDocTemplate(response, rightMargin=2*cm, leftMargin=2*cm, topMargin=0*cm, bottomMargin=0) styles = getSampleStyleSheet() styles.add(ParagraphStyle( name="TableHeader", fontSize=11, alignment=TA_CENTER, fontName="Helvetica")) styles.add(ParagraphStyle( name="ParagraphTitle", fontSize=11, alignment=TA_JUSTIFY, fontName="FreeSansBold")) styles.add(ParagraphStyle( name="Justify", alignment=TA_JUSTIFY, fontName="FreeSans")) ########elements container######## elements = [] ###########header############### UNSWLogo = Image('report/images/pdfheader.PNG') UNSWLogo.drawHeight = 4*cm UNSWLogo.drawWidth = 21 *cm elements.append(UNSWLogo) s = Spacer(1, 0.2*cm) elements.append(s) #########title############ title = """Reports by Consultations""" elements.append(Paragraph(title, styles['Heading2'])) s = Spacer(1, 0.2*cm) elements.append(s) #p = Paragraph('''<para align=center spaceb=3> TITLE''') ############table header############ header_Data = [[" Student ","Title","Staff", "Time"]] t1 = Table(header_Data,[6*cm, 7*cm, 2.25*cm, 3*cm]) t1.setStyle(TableStyle([('LINEABOVE',(0,0),(-1,-1),1, colors.black), ('LINEBELOW',(0,0),(-1,-1),1, colors.black), ('FONTSIZE', (0,0), (-1,-1), 8), ('BACKGROUND',(0,0),(-1,-1), HexColor('#50A6C2'))])) elements.append(t1) s1 = Spacer(1, 0.1*cm) elements.append(s1) ######table data ################## table_data = [[ str(my_data.zID), str(my_data.title), str(my_data.ugc), str(my_data.start) ] for my_data in f] #'''str(my_data.apptType)''' t = Table(table_data,[6*cm, 7*cm, 2.25*cm, 3*cm]) t.setStyle(TableStyle([('LINEABOVE',(0,0),(-1,-1),2, colors.white), ('LINEBELOW', (0,0), (-1,-1), 2, colors.white), ('ROWBACKGROUNDS', (0,0), (-1,-1), [HexColor('#e6f2ff'), HexColor('#c1e0ff')]), ('FONTSIZE', (0,0), (-1,-1), 8)])) elements.append(t) ############footer################## '''pdffooter = Image('report/images/pdffooter.PNG') pdffooter.drawHeight = 1.5*cm pdffooter.drawWidth = 22 *cm s1 = Spacer(1, 20*cm) elements.append(s1) elements.append(pdffooter)''' # elements.append(t) doc.build(elements) return response #data = [[str(my_data.title), str(my_data.zID), str(my_data.ugc), str(my_data.apptType)] for my_data in f] #data.append return render(request, 'consultationReport.html', {'all_consultations': all_consultations, 'filter':f })
def get_pdf_match_schedule(ladder_round): # Header Table with the logos franklin_logo = os.path.join(settings.MEDIA_ROOT, 'images/franklin_logo.png') squash_auckland_logo = os.path.join(settings.MEDIA_ROOT, 'images/squash_auckland.png') franklin_logo_image = Image(franklin_logo) franklin_logo_image.drawWidth = 100 franklin_logo_image.drawHeight = 55 squash_auckland_logo_image = Image(squash_auckland_logo) squash_auckland_logo_image.drawWidth = 100 squash_auckland_logo_image.drawHeight = 30 document_title = "Franklin Squash Club Ladder" header_table = Table( [[franklin_logo_image, document_title, squash_auckland_logo_image]]) # Header Table Style header_table_style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (1, 0), (1, 0), colors.HexColor('#CD6620')), ('FONTSIZE', (1, 0), (1, 0), 20), ('FONTNAME', (1, 0), (1, 0), 'Times-BoldItalic') ]) header_table.setStyle(header_table_style) spacer = Spacer(1, 10) # Round Schedule and Match Schedule scheduled_matches = MatchSchedule.objects.filter( ladder_round=ladder_round, match__isnull=False).order_by('time_grid_location') round_match_schedule = ladder_round.match_schedule data_list = [] # Day Table match_days = round_match_schedule.match_days.split(',') time_slots = round_match_schedule.number_of_timeslots number_of_courts = round_match_schedule.number_of_courts for idx, day in enumerate(match_days, start=1): date_of_day = date_for_day_of_the_year(day, ladder_round.start_date.year) print(date_of_day) time_slot_table_list = [] for time_slot in range(time_slots): time_slot_time = add_minutes( round_match_schedule.start_time, time_slot * round_match_schedule.time_interval) matches_in_slot = [] for court in range(number_of_courts): grid_location = get_match_schedule_grid_location( idx, time_slot + 1, court + 1, number_of_courts, time_slots) match = [ x for x in scheduled_matches if x.time_grid_location == grid_location ] if match: match_in_slot_table = Table([ [ f'{match[0].match.player1.first_name} {match[0].match.player1.last_name}' ], ['vs'], [ f'{match[0].match.player2.first_name} {match[0].match.player2.last_name}' ] ], colWidths=(45 * mm), rowHeights=None) match_in_slot_table_style = TableStyle([ ('BACKGROUND', (0, 0), (-1, -1), colors.green), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('BOX', (0, 0), (-1, -1), 0.5, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.white), ('FONTSIZE', (0, 0), (-1, -1), 8), ]) match_in_slot_table.setStyle(match_in_slot_table_style) matches_in_slot.append(match_in_slot_table) time_slot_table = Table( [[time_slot_time.strftime('%H:%M')], matches_in_slot], rowHeights=None) time_slot_table_style = TableStyle([ ('BACKGROUND', (0, 0), (-1, -1), colors.HexColor('#FFAE78')), ('BOX', (0, 0), (-1, -1), 0.5, colors.black) ]) time_slot_table.setStyle(time_slot_table_style) time_slot_table_list.append(time_slot_table) print(time_slot_time) day_table = Table([[date_of_day.strftime('%A %-d %b, %Y')], [time_slot_table_list]]) data_list.append(day_table) data = Table([data_list]) page_elements = [header_table, spacer, data] doc = io.BytesIO() pdf = SimpleDocTemplate(doc, pagesize=A4) pdf.build(page_elements) doc.seek(0) return doc