Example #1
0
    def _header_footer(canvas,doc):
        #guardamos el estado de nuestro canvas , para poder dibujar en el 
        canvas.saveState()
        canvas.setTitle("Cotizacion Cliente")
        styles = getSampleStyleSheet()

        #header
        header = Image('/home/borbolla/metrology/static_media/assets/images/borbolla_metrology_logo.jpg' )
        header.drawHeight = 60
        header.drawWidth = 424
        header.hAlign = 'RIGHT'
        w , h = header.wrap(doc.width , doc.topMargin)
        header.drawOn(canvas , doc.leftMargin , 700)
        
        marcas = Image('/home/borbolla/metrology/static_media/assets/images/marcas.png' )
        marcas.drawWidth = 90
        marcas.drawHeight = 477
        marcas.drawOn(canvas , 20,200) 
        
        marcas2 = Image('/home/borbolla/metrology/static_media/assets/images/logo.png' )
        marcas2.drawWidth = 116
        marcas2.drawHeight = 34
        marcas2.drawOn(canvas , 20,150) 

        # Footer
        footer = Paragraph('www.borbollametrology.com', styles['Normal'])
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, h)
 
        # Release the canvas
        canvas.restoreState()
Example #2
0
    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)
Example #3
0
 def parse_image(self, xmlimage, current_x, current_y, current_w, current_h):
     if xmlimage.text is not None:
         from PIL import ImageFile
         ImageFile.LOAD_TRUNCATED_IMAGES = True
         img_content = xmlimage.text.strip()
         is_base64 = img_content[:len(BASE64_PREFIX)] == BASE64_PREFIX
         if is_base64:
             img_file = open_from_base64(img_content)
         else:
             img_file = open(img_content, "rb")
         try:
             img = Image(img_file)
             if current_h is not None:
                 img.drawHeight = current_h
                 img.drawWidth = current_w
             else:
                 current_h = img.drawHeight
                 current_w = img.drawWidth
             _, new_current_h = img.wrapOn(self.pdf, current_w, current_h)
             img.drawOn(self.pdf, current_x, self.height - current_y - current_h)
             self.position_y = current_y + max(new_current_h, current_h)
             return img
         finally:
             if img_file is not None:
                 img_file.close()
     else:
         return None
Example #4
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)
Example #5
0
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
Example #6
0
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 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)
Example #8
0
def create_pdf(file_location, no_of_people_need_assistance):
    doc = SimpleDocTemplate(file_location+'reem3.pdf')
    Story = []
    styleN = styles["Normal"]
    styleH = styles['Heading1']

    I_fire = Image(file_location+'fire.png')
    I_fire.drawHeight = 0.5 * inch * I_fire.drawHeight / I_fire.drawWidth
    I_fire.drawWidth = 0.5 * inch

    I_people = Image(file_location+'cross.png')
    I_people.drawHeight = 0.5 * inch * I_people.drawHeight / I_people.drawWidth
    I_people.drawWidth = 0.5 * inch

    im = Image(file_location+"logo.png")
    im_map = Image(file_location + "map_with_cross.png")

    im_map.drawHeight = 3*inch*im_map.drawHeight/im_map.drawWidth
    im_map.drawWidth=3*inch

    text1 = ("This report is prepared by REEM.")
    text2 = ("Legend")
    text3 = ("Total number of people who need assistance: "+str(no_of_people_need_assistance)+". Approximate locations marked on the map.")
    text4 = ("Description of fire: Smoke detected in kitchen. Approximate location is marked on the map.")

    data = [['Fire', [I_fire]], ['People that need assistance', [I_people]]]

    t = Table(data, style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black), ('ALIGN', (0, -1), (-1, -1), 'CENTER')])

    p1 = Paragraph(text1, styleH)
    p2 = Paragraph(text2, styleN)
    p3 = Paragraph(text3, styleN)
    p4 = Paragraph(text4, styleN)

    Story.append(im)
    Story.append(Spacer(1, 20))
    Story.append(p1)
    Story.append(Spacer(1, 20))
    Story.append(im_map)
    Story.append(Spacer(1, 0.5*inch))
    Story.append(p4)
    Story.append(Spacer(1, 20))
    Story.append(p3)
    Story.append(Spacer(1, 0.5*inch))
    Story.append(p2)
    Story.append(t)
    doc.build(Story)
    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)
Example #10
0
  def add_table(self, graphName, yAxisTitle, labels, values):
    # container for the 'Flowable' objects
    self.tableCount += 1
    graphNameImg = Image(graphName)
    width=7.5*inch
    graphNameImg.drawHeight = width*graphNameImg.drawHeight / graphNameImg.drawWidth
    graphNameImg.drawWidth = width
      
    self.elements.append(graphNameImg)       
   
    yAxisTitleImg = Image(yAxisTitle)
    width=7.5*inch
    yAxisTitleImg.drawHeight = width*yAxisTitleImg.drawHeight / yAxisTitleImg.drawWidth
    yAxisTitleImg.drawWidth = width
      
    self.elements.append(yAxisTitleImg)       
   
    styleSheet = getSampleStyleSheet()
    
    finalLabels=[]
    noOfCols=len(labels)
    for label in labels:
      I = Image(label)
      width=7*inch/noOfCols
      I.drawHeight = width*I.drawHeight / I.drawWidth
      I.drawWidth = width
      finalLabels.append(I)

    noOfRows=len(values)
    data=[finalLabels]
    for x in values:
      data.append(x)
    
    t=Table(data, style=[('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
      ('BOX', (0,0), (-1,-1), 0.25, colors.black),])
    
    self.elements.append(t)
    
    if self.csv != None:
      csvFile = self.exportAsCsv(values)
      ptext = '<font size=24>CSV exported to %s</font>' % csvFile
      self.elements.append(Paragraph(ptext, styleSheet["Normal"]))
    
    self.elements.append(PageBreak())
Example #11
0
    def createDocument(self):
        """"""
        for page in self.e.findall("page"):
            for image in page.findall("image"):
                logo = Image(image.get("src"))
                logo.drawHeight = int(image.get("height"))
                logo.drawWidth = int(image.get("width"))
                logo.wrapOn(self.c, self.width, self.height)
                logo.drawOn(self.c, *self.coord(int(image.get("left")),int(image.get("top"))+int(image.get("height")) ))
            for text in page.findall("text"):
                if len(text.getchildren())==0:
                    font = self.fonts[text.get("font")]
                    style = ParagraphStyle(
                        'default',
                        fontName="Arial",
                        leading=int(font["size"])+7,
                        fontSize=font["size"],
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )
                    self.createParagraph(text.text, int(text.get("left")), (int(text.get("top"))+int(text.get("height"))),style)
                else:
                    innerText = ElementTree.tostring(text.getchildren()[0])
                    font = self.fonts[text.get("font")]
                    style = ParagraphStyle(
                        'default',
                        fontName="Arial",
                        leading=int(font["size"])+7,
                        fontSize=font["size"],
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )
                    self.createParagraph(innerText, int(text.get("left")), (int(text.get("top"))+int(text.get("height"))),style)
            for line in page.findall("line"):
                self.c.setDash(int(line.get("on")),int(line.get("off")))
                self.c.setStrokeColor(line.get("color"))
                self.c.line(int(line.get("x1")),self.height-int(line.get("y1")),int(line.get("x2")),self.height-int(line.get("y2")))
            for table in page.findall("table"):
                self.c.setDash(1,0)
                tabDat = dataDictionary[table.get("data")]
                if table.get("widths"):
                    colWidths = [float(width) for width in table.get("widths").split(",")]
                else:
                    colWidths = float(table.get("width"))/len(tabDat[0])
                if table.get("heights"):
                    rowHeights = [float(height) for height in table.get("heights").split(",")]
                else:
                    rowHeights = float(table.get("height"))/len(tabDat)
                t = Table(tabDat,colWidths,rowHeights,style=tableStyles[table.get("data")])
                t.wrapOn(self.c, self.width, self.height)
                t.drawOn(self.c, *self.coord(int(table.get("left")), int(table.get("top"))+int(table.get("height"))))

            self.c.showPage()
def cabecera(canvas, datos_de_la_empresa):
    """
    Escribe el texto «CERTIFICADO DE CALIDAD», el logotipo de la empresa, una 
    imagen de geotextiles y un par de rayajos de adorno.
    """
    fuente = "Helvetica-Bold"
    tamanno = 12
    canvas.saveState()
    canvas.setFont(fuente, tamanno)
    canvas.drawCentredString(PAGE_WIDTH / 2.0 + 1*cm, 
                             PAGE_HEIGHT - 2 * cm, 
                             escribe("CERTIFICADO DE CALIDAD"))
    canvas.restoreState()
    rutalogo = datos_de_la_empresa.logo
    if rutalogo:
        rutalogo = os.path.join("..", "imagenes", rutalogo)
        logo = Image(rutalogo)
        logo.drawHeight = 2*cm * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 2*cm
        logo.drawOn(canvas, 2.75*cm, PAGE_HEIGHT - 1*cm - 2*cm)
    # OJO: Foto de geotextiles HARCODED.
    rutafoto = os.path.join("..", "imagenes", "foto_geotextiles.jpg")
    foto = Image(rutafoto)
    foto.drawHeight = 2*cm * foto.drawHeight / foto.drawWidth
    foto.drawWidth = 2*cm
    foto.drawOn(canvas, PAGE_WIDTH - 5*cm, PAGE_HEIGHT - 2.75*cm - 2*cm)
    canvas.saveState()
    canvas.setStrokeColor(colors.green)
    canvas.rect(PAGE_WIDTH - 5*cm, PAGE_HEIGHT - 2.75*cm - 2*cm, 2*cm, 2*cm)
    ## XXX: Esto de ahora es un poco chapuza, y como cambie algún margen se va 
    ## al carajo este trocito de línea que se supone que debería ser parte de 
    ## la sección Denominación.
    canvas.line(PAGE_WIDTH - 5*cm + 2*cm, PAGE_HEIGHT - 3.25*cm, 
                PAGE_WIDTH - 5*cm + 2.25*cm, PAGE_HEIGHT - 3.25*cm)
    ## XXX: EOChapuza
    canvas.restoreState()
    canvas.line(5*cm, PAGE_HEIGHT - 1*cm, # (x1, y1)
                5*cm, PAGE_HEIGHT - 2.5*cm) # (x2, y2)
    canvas.line(PAGE_WIDTH - 3*cm, PAGE_HEIGHT - 1*cm, # (x1, y1)
                PAGE_WIDTH - 3*cm, PAGE_HEIGHT - 2.5*cm) # (x2, y2)
    # En la primera página también debe ir el pie
    pie(canvas, datos_de_la_empresa)
Example #13
0
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
Example #14
0
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
Example #15
0
 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
Example #16
0
  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 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)
Example #18
0
    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 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 build_index_Campioni(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 CAMPIONI</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data), styH1))

		table_data = []
		for i in range(len(records)):
			exp_index = Campioni_index_pdf_sheet(records[i])
			table_data.append(exp_index.getTable())
		
		styles = exp_index.makeStyles()
		colWidths=[60,150,60, 60,60, 250, 60]

		table_data_formatted = Table(table_data, colWidths, style=styles)
		table_data_formatted.hAlign = "LEFT"

		lst.append(table_data_formatted)
		#lst.append(Spacer(0,2))

		filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_campioni.pdf')
		f = open(filename, "wb")

		doc = SimpleDocTemplate(f, pagesize=(29*cm, 21*cm), showBoundary=0)
		doc.build(lst, canvasmaker=NumberedCanvas_Campioniindex)

		f.close()
Example #21
0
def create_pdf(file_location):
    doc = SimpleDocTemplate(file_location + "reem3.pdf")
    Story = []
    styleN = styles["Normal"]
    styleH = styles["Heading1"]

    # I_fire = Image(file_location+'fire.png')
    # I_fire.drawHeight = 0.5 * inch * I_fire.drawHeight / I_fire.drawWidth
    # I_fire.drawWidth = 0.5 * inch

    # I_people = Image(file_location+'cross.png')
    # I_people.drawHeight = 0.5 * inch * I_people.drawHeight / I_people.drawWidth
    # I_people.drawWidth = 0.5 * inch

    im = Image(file_location + "logo.png")
    img_person = Image(file_location + "camera_image.png")

    im_map = Image(file_location + "map_with_cross.png")

    im_map.drawHeight = 3 * inch * im_map.drawHeight / im_map.drawWidth
    im_map.drawWidth = 3 * inch

    text1 = "This report is prepared by REEM and REEM@LaSalle."
    text2 = "Legend"
    text3 = "The Emergency location is described approximately below:"
    text4 = "Description of Emergency: Person in bad condition."

    p1 = Paragraph(text1, styleH)
    p2 = Paragraph(text2, styleN)
    p3 = Paragraph(text3, styleN)
    p4 = Paragraph(text4, styleN)

    Story.append(im)
    Story.append(Spacer(1, 20))
    Story.append(p1)
    Story.append(Spacer(1, 20))
    Story.append(im_map)
    Story.append(Spacer(1, 0.5 * inch))
    Story.append(p4)
    Story.append(Spacer(1, 20))
    Story.append(p3)
    Story.append(Spacer(1, 0.5 * inch))
    Story.append(p2)
    Story.append(img_person)
    doc.build(Story)
Example #22
0
    def header(self):
        img = Image("http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png")
        img.drawHeight = 1.25*inch*img.drawHeight / img.drawWidth
        img.drawWidth = 1.25*inch
        title = Paragraph("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PDF Sample", self.styles["Heading2"])

        img_title_data = [
            [img, title]
        ]

        img_title_table_style = TableStyle([('ALIGN', (0, 0), (0, 0), 'LEFT'),
                                          ('ALIGN', (-1, -1), (-1, -1), 'CENTER'),
                                          ('LINEBELOW', (0, 0), (-1, -1), 1, colors.black),
                                          ])

        img_title_table = Table(img_title_data)
        img_title_table.setStyle(img_title_table_style)

        self.elements.append(img_title_table)
        self.elements.append(Paragraph("Generated on %s" % timezone.now(), self.styles["Normal"]))
        self.elements.append(Paragraph("<b>&nbsp;</b>", self.styles["Heading1"]))
Example #23
0
    def createDocument(self):
        """"""
        voffset = 65
 
        # create return address
        address = """<font size="9">
        Jack Spratt<br/>
        222 Ioway Blvd, Suite 100<br/>
        Galls, TX 75081-4016</font>
        """
        p = Paragraph(address, self.styles["Normal"])        
 
        # add a logo and size it
        logo = Image("logo.png")
        logo.drawHeight = 2*inch
        logo.drawWidth = 2*inch
##        logo.wrapOn(self.c, self.width, self.height)
##        logo.drawOn(self.c, *self.coord(140, 60, mm))
##        
 
        data = [[p, logo]]
        table = Table(data, colWidths=4*inch)
        table.setStyle([("VALIGN", (0,0), (0,0), "TOP")])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(18, 60, mm))
 
        # insert body of letter
        ptext = "Dear Sir or Madam:"
        self.createParagraph(ptext, 20, voffset+35)
 
        ptext = """
        The document you are holding is a set of requirements for your next mission, should you
        choose to accept it. In any event, this document will self-destruct <b>%s</b> seconds after you
        read it. Yes, <b>%s</b> can tell when you're done...usually.
        """ % (self.seconds, self.organization)
        p = Paragraph(ptext, self.styles["Normal"])
        p.wrapOn(self.c, self.width-70, self.height)
        p.drawOn(self.c, *self.coord(20, voffset+48, mm))
Example #24
0
    def _header_factura(canvas,doc):
        #guardamos el estado de nuestro canvas , para poder dibujar en el 
        canvas.saveState()
        canvas.setTitle("Factura")
        styles = getSampleStyleSheet()

        #header
        header = Image('/home/borbolla/metrology/static_media/assets/images/logo_servicio.png' )
        header.drawHeight = 70
        header.drawWidth = 399
        header.hAlign = 'RIGHT'
        w , h = header.wrap(doc.width , doc.topMargin)
        header.drawOn(canvas , doc.leftMargin , 700)
        
        

        # Footer
        footer = Paragraph('www.borbollametrology.com', styles['Normal'])
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, h)
 
        # Release the canvas
        canvas.restoreState()
def build_texto(datos_de_la_empresa):
    """
    Construye el texto genérico de la carta de portes.
    """
    estilo_texto = ParagraphStyle("Texto", 
                                  parent = estilos["Normal"])
    estilo_texto.alignment = enums.TA_JUSTIFY
    estilo_texto.firstLineIndent = 24
    estilo_texto.fontSize = 8
    estilo_texto.leading = 9
    texto = """Norma UNE EN 13249:2001 y UNE EN 13249:2001/A1:2005, Norma UNE EN 13250:2001 y UNE EN 13250:2001/A1:2005, Norma UNE EN 13251:2001 y UNE EN 13251:2001/A1:2005, Norma UNE EN 13252:2001, UNE EN 13252/Erratum:2002 y UNE EN 13252:2001/A1:2005, Norma UNE EN 13253:2001 y UNE EN 13253:2001/A1:2005, Norma UNE EN 13254:2001, UNE EN 13254/AC:2003 y UNE EN 13254:2001/A1:2005, Norma UNE EN 13255:2001, UNE EN 13255/AC:2003 y UNE EN 13255:2001/A1:2005, Norma UNE EN 13256:2001, UNE EN 13256/AC:2003 y UNE EN 13256:2001/A1:2005,Norma UNE EN 13257:2001, UNE EN 13257/AC:2003 y UNE EN 13257:2001/A1:2005, Norma UNE EN 13265:2001, UNE EN 13265/AC:2003 y UNE EN 13265:2001/A1:2005.

Geotextil no tejido formado por fibras vírgenes <b>100% de polipropileno</b>, unidas mecánicamente por un proceso de agujado con posterior termofijado. Campo de aplicación: en carreteras y otras zonas de tráfico, construcciones ferroviarias, movimientos de tierras, cimentaciones y estructuras de contención, sistemas de drenaje, control de la erosión (protección costera y revestimiento de taludes), construcción de embalses y presas, construcción de canales, construcción de túneles y estructuras subterráneas, vertederos de residuos sólidos, proyectos de contenedores de residuos sólidos.
    """ 
    p = [Paragraph(escribe(t), estilo_texto) for t in texto.split("\n") if t]
    p.insert(1, Spacer(1, 0.25*cm))
    logo_ce = Image(os.path.join("..", "imagenes", "CE.png"))
    logo_ce.drawHeight = 0.75*cm
    logo_ce.drawWidth = 1*cm
    p.insert(0, logo_ce)
    p.insert(1, Spacer(1, 0.15*cm))
    estilo_numero_marcado = ParagraphStyle("NumeroMarcado", 
                                           parent = estilos["Normal"])
    estilo_numero_marcado.alignment = enums.TA_CENTER
    estilo_numero_marcado.fontSize = 7
    estilo_numero_marcado.fontName = "Courier"
    p.insert(2, Paragraph(escribe("1035-CPD-ES033858"), estilo_numero_marcado))
    estilo_nombre_empresa = ParagraphStyle("NombreEmpresa", 
                                           parent = estilos["Normal"])
    estilo_nombre_empresa.alignment = enums.TA_CENTER
    estilo_nombre_empresa.fontSize = 7
    estilo_nombre_empresa.fontName = "Courier-Bold"
    nombre_empresa = datos_de_la_empresa.nombre
    p.insert(3, Paragraph(escribe(nombre_empresa.upper()), 
                          estilo_nombre_empresa))
    p.insert(4, Spacer(1, 0.15*cm))
    return KeepTogether(p)
Example #26
0
def rgpd_eleve_pdf(request, eleve_id):
    try:
        eleve = Eleve.objects.filter(pk=eleve_id).select_related('user','classe','groupe','lv1','lv2')[0]
    except Exception:
        raise Http404
    nomfichier="RGPD_eleve-{}.pdf".format(eleve.pk)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename={}".format(nomfichier)
    marge_y = 40
    pdfformat = A4
    titre = "Données personnelles de l'étudiant {}".format(eleve)

    def myFirstPage(canvas, doc):
        canvas.saveState()
        x=pdfformat[0]/2
        y=pdfformat[1]-marge_y
        canvas.setFont("Helvetica-Bold",12)
        canvas.drawCentredString(x,y,titre)
        y-=20
        canvas.drawCentredString(x,y,Config.objects.get_config().nom_etablissement)
        x=pdfformat[0]/2
        y=marge_y
        canvas.setFont("Helvetica-Oblique",8)
        canvas.drawCentredString(x,y,"page n°{}".format(canvas.getPageNumber()))
        canvas.restoreState()

    pdfbuffer = BytesIO()
    doc = SimpleDocTemplate(pdfbuffer)
    doc.leftMargin = doc.rightMargin = 20
    style = ParagraphStyle(name='soustitre',
        fontSize=12,
        alignment = TA_CENTER,
        fontName="Helvetica-Bold",
        borderColor='black',
        borderPadding=(2,0,6,0),
        borderWidth=0,
        backColor='#DDDDDD',
        spaceBefore=0,
        spaceAfter=20)
    stylebis = ParagraphStyle(name='commentaire',
        fontSize=9,
        alignment = TA_LEFT,
        borderColor='black',
        borderPadding=(0,2,0,2),
        borderWidth = 1,
        fontName="Helvetica-Bold")
    par1 = Paragraph("Données utilisateur", style)
    LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),1,(0,0,0))
                                        ,('VALIGN',(0,0),(-1,-1),'MIDDLE')
                                        ,('ALIGN',(0,0),(-1,-1),'CENTRE')
                                        ,('FACE',(0,0),(-1,-1),"Helvetica-Bold")
                                        ,('SIZE',(0,0),(-1,-1),9)])
    data = [("Nom:", eleve.user.last_name.upper()),
    ("Prénom:", eleve.user.first_name.title()),
    ("Identifiant:", eleve.user.username)]
    if eleve.user.email:
        data.append(('Email:', eleve.user.email))
    if eleve.user.date_joined:
        data.append(('ajouté le:', eleve.user.date_joined.strftime("%d/%m/%Y à %Hh%M")))
    if eleve.user.last_login:
        data.append(('Dernière connexion le:', eleve.user.last_login.strftime("%d/%m/%Y à %Hh%M")))
    if eleve.ine:
        data.append(('Numéro INE:', eleve.ine))
    if eleve.ddn:
        data.append(('Date de naissance:', eleve.ddn.strftime("%d/%m/%Y")))
    if eleve.ldn:
        data.append(('Lieu de naissance:', eleve.ldn))
    if eleve.classe:
        data.append(('Classe:', eleve.classe.nom))
    if eleve.groupe:
        data.append(('Groupe:', eleve.groupe.nom))
    if eleve.lv1:
        data.append(('LV1:', eleve.lv1.nom.title()))
    if eleve.lv2:
        data.append(('LV2', eleve.lv2.nom.title()))
    if eleve.photo:
        image = Image(join(MEDIA_ROOT, str(eleve.photo)))
        image.drawHeight = 80
        image.drawWidth = 60
        data.append(('Photo', image))
    t=Table(data, colWidths=200, repeatRows = 1)
    t.setStyle(LIST_STYLE)
    story = [par1, t, PageBreak()]
    if Note.objects.filter(eleve = eleve).exists(): # si l'élève a des notes:
        par2 = Paragraph("Notes de colle", style)
        story.append(par2)
        notes = Note.objects.filter(eleve = eleve).select_related('eleve__user','matiere','colleur__user').order_by('-date_colle', '-heure')
        LISTE_NOTES = list(range(21)) + ["n.n", "abs."]
        for note in notes:
            data = [(note.date_colle.strftime('%d/%m/%Y'), "{}h{:02d}".format(note.heure//60, note.heure%60), str(note.colleur), str(note.matiere), str(LISTE_NOTES[note.note]))]
            t=Table(data, colWidths=(80, 60, 170, 170, 60))
            t.setStyle(LIST_STYLE)
            story.append(t)
            if note.commentaire:
                par = Paragraph("<u>commentaire:</u> " + note.commentaire.replace("\n", "<br/>"), stylebis)
                story.append(par)
        story.append(PageBreak())
    if NoteECTS.objects.filter(eleve = eleve).exists(): # si l'élève a des notes ECTS
        par2 = Paragraph("Notes ECTS", style)
        story.append(par2)
        LISTE_NOTES_ECTS = "ABCDEF"
        notesECTS = NoteECTS.objects.filter(eleve = eleve).select_related('matiereECTS').order_by('semestre','matiereECTS__nom')
        data = [("semestre", "matière", "note")]
        data += [(note.semestre, note.matiere.nom, LISTE_NOTES_ECTS[note.note]) for note in notesECTS]
        t=Table(data, colWidths=(50, 200, 50), repeatRows = 1)
        t.setStyle(LIST_STYLE)
        story.append(t)
        story.append(PageBreak())
    if Message.objects.filter(auteur = eleve.user).exists(): # si l'élève a envoyé des messages
        par2 = Paragraph("Messages envoyés", style)
        story.append(par2)
        messages = Message.objects.filter(auteur = eleve.user)
        for message in messages:
            texte = "<u>Envoyé le</u> {} <br/> <u>à</u>: {} <br/> <u>sujet</u>: {} <br/> {}".format(message.date.strftime("%d/%m/%Y à %Hh%M"),
                message.listedestinataires, message.titre, message.corps.replace("\n", "<br/>"))
            par = Paragraph(texte, stylebis)
            story.append(par)
    doc.build(story, onFirstPage=myFirstPage, onLaterPages=myFirstPage)
    fichier = pdfbuffer.getvalue()
    pdfbuffer.close()
    response.write(fichier)
    return response
	def create_sheet(self):
		styleSheet = getSampleStyleSheet()
		styNormal = styleSheet['Normal']
		styNormal.spaceBefore = 20
		styNormal.spaceAfter = 20
		styNormal.alignment = 0 #LEFT

		styleSheet = getSampleStyleSheet()
		styDescrizione = styleSheet['Normal']
		styDescrizione.spaceBefore = 20
		styDescrizione.spaceAfter = 20
		styDescrizione.alignment = 4 #Justified
		
		"""
		#format labels
		self.id_scheda_ind = data[0]
		self.sito = data[1]
		self.area = data[2]
		self.us = data[3]
		self.nr_individuo = data[4]
		self.data_schedatura = data[5]
		self.schedatore = data[6]
		self.sesso = data[7]
		self.eta_min = data[8]
		self.eta_max =  data[9]
		self.classi_eta = data[10]
		self.osservazioni = data[11]
		"""
		#0 row
		intestazione = Paragraph("<b>SCHEDA INDIVIDUI<br/>" + unicode(self.datestrfdate()) + "</b>", styNormal)
		#intestazione2 = Paragraph("<b>pyArchInit</b>", styNormal)


		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)

		##		if test_image.drawWidth < 800:

		logo.drawHeight = 1.5*inch*logo.drawHeight / logo.drawWidth
		logo.drawWidth = 1.5*inch


		#1 row
		sito = Paragraph("<b>Sito</b><br/>"  + unicode(self.sito), styNormal)
		area = Paragraph("<b>Area</b><br/>"  + unicode(self.area), styNormal)
		us = Paragraph("<b>US</b><br/>"  + unicode(self.us), styNormal)
		nr_inventario = Paragraph("<b>Nr. Individuo</b><br/>"  + unicode(self.nr_individuo), styNormal)

		#2 row
		sesso = Paragraph("<b>Sesso</b><br/>"  + self.sesso, styNormal)

		if  str(self.eta_min) == "None":
			eta_min = Paragraph("<b>Eta' Minima</b><br/>", styNormal)
		else:
			eta_min = Paragraph("<b>Eta' Minima</b><br/>" + unicode(self.eta_min), styNormal)

		if  str(self.eta_max) == "None":
			eta_max = Paragraph("<b>Eta' massima</b><br/>", styNormal)
		else:
			eta_max = Paragraph("<b>Eta' massima</b><br/>" + unicode(self.eta_max), styNormal)

		#3 row
		classi_eta_string = unicode(self.classi_eta).replace("<", "&lt;")
		#classi_eta = Paragraph(classi_eta_string, styNormal)
		classi_eta = Paragraph("<b>Classi di eta'</b><br/>"  + classi_eta_string, styNormal)

		#4 row
		osservazioni = ''
		try:
			osservazioni = Paragraph("<b>Osservazioni</b><br/>" + str(self.osservazioni), styDescrizione)
		except:
			pass
		
		"""
		#5 row
		elementi_reperto = ''
		if eval(self.elementi_reperto) > 0 :
			for i in eval(self.elementi_reperto):
				if elementi_reperto == '':
					try:
						elementi_reperto += ("Elemento rinvenuto: %s, Unita' di musura: %s, Quantita': %s") % (str(i[0]), str(i[1]), str(i[2]))
					except:
						pass
				else:
					try:
						elementi_reperto += ("<br/>Elemento rinvenuto: %s, Unita' di musura: %s, Quantita': %s") % (str(i[0]), str(i[1]), str(i[2]))
					except:
						pass

		elementi_reperto = Paragraph("<b>Elementi reperto</b><br/>"  + elementi_reperto, styNormal)

		#6 row
		misurazioni = ''
		if eval(self.misurazioni) > 0:
			for i in eval(self.misurazioni):
				if misurazioni == '':
					try:
						misurazioni += ("<b>Tipo di misura: %s, Unita' di musura: %s, Quantita': %s") % (str(i[0]), str(i[2]), str(i[1]))
					except:
						pass
				else:
					try:
						misurazioni += ("<br/><b>Tipo di misura: %s, Unita' di musura: %s, Quantita': %s") % (str(i[0]), str(i[2]), str(i[1]))
					except:
						pass
		misurazioni = Paragraph("<b>Misurazioni</b><br/>"  + misurazioni, styNormal)

		#7 row
		tecnologie = ''
		if eval(self.tecnologie) > 0:
			for i in eval(self.tecnologie):
				if tecnologie == '':
					try:
						tecnologie += ("<b>Tipo tecnologia: %s, Posizione: %s, Tipo quantita': %s, Unita' di musura: %s, Quantita': %s") % (str(i[0]), str(i[1]), str(i[2]), str(i[3]),str(i[4]))
					except:
						pass
				else:
					try:
						tecnologie += ("<br/><b>Tipo tecnologia: %s, Posizione: %s, Tipo quantita': %s, Unita' di musura: %s, Quantita': %s") % (str(i[0]), str(i[1]), str(i[2]), str(i[3]),str(i[4]))
					except:
						pass
		tecnologie = Paragraph("<b>Tecnologie</b><br/>"  + tecnologie, styNormal)

		#8 row
		rif_biblio = ''
		if eval(self.rif_biblio) > 0:
			for i in eval(self.rif_biblio): #gigi
				if rif_biblio == '':
					try:
						rif_biblio += ("<b>Autore: %s, Anno: %s, Titolo: %s, Pag.: %s, Fig.: %s") % (str(i[0]), str(i[1]), str(i[2]), str(i[3]),str(i[4]))
					except:
						pass
				else:
					try:
						rif_biblio += ("<br/><b>Tipo tecnologia: %s, Posizione: %s, Tipo quantita': %s, Unita' di musura: %s, Quantita': %s") % (str(i[0]), str(i[1]), str(i[2]), str(i[3]),str(i[4]))
					except:
						pass

		rif_biblio = Paragraph("<b>Riferimenti bibliografici</b><br/>"  + rif_biblio, styNormal)
		"""

		#12 row
		data_schedatura  = Paragraph("<b>Data schedatura</b><br/>" + self.data_schedatura,styNormal)
		schedatore = Paragraph("<b>Schedatore</b><br/>" + self.schedatore,styNormal)

		#schema
		cell_schema =  [ #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
						[intestazione, '01', '02', '03', '04','05', '06', logo, '08', '09'],
						[sito, '01', '02', area, '04', us,'06', '07', nr_inventario, '09'], #1 row ok
						[sesso, '01', '02', eta_min,'04', '05',eta_max, '07', '08', '09'], #2 row ok
						[classi_eta, '01', '02', '03', '04', '05', '06', '07', '08', '09'], #3 row ok
						[osservazioni, '01','02', '03', '04', '05','06', '07', '08', '09'], #4 row ok
						[data_schedatura, '01', '02', '03', '04', '05', schedatore, '07', '08', '09'] #5 row ok
						#['https://sites.google.com/site/pyarchinit/', '01', '02', '03', '04','05', '06', '07','08', '09'] #6 row
						]


		#table style
		table_style=[

					('GRID',(0,0),(-1,-1),0.5,colors.black),
					#0 row
					('SPAN', (0,0),(6,0)),  #intestazione
					('SPAN', (7,0),(9,0)), #intestazione2

					#1 row
					('SPAN', (0,1),(2,1)),  #sito
					('SPAN', (3,1),(4,1)),  #area
					('SPAN', (5,1),(7,1)),  #us
					('SPAN', (8,1),(9,1)),  #nr_inventario

					#2 row
					('SPAN', (0,2),(2,2)),  #sesso
					('SPAN', (3,2),(5,2)),  #eta_min
					('SPAN', (6,2),(9,2)),  #eta_max
					('VALIGN',(0,2),(9,2),'TOP'), 

					#3 row
					('SPAN', (0,3),(9,3)), #classi_eta
					
					#4 row
					('SPAN', (0,4),(9,4)),  #osservazioni

					#5 row
					('SPAN', (0,5),(5,5)),  #data_schedatura
					('SPAN', (6,5),(9,5)),  #schedatore

					('VALIGN',(0,0),(-1,-1),'TOP')
					]

		t=Table(cell_schema, colWidths=50, rowHeights=None,style= table_style)

		return t
Example #28
0
def F2s_CrearPDF(factura, detalle, AIU):
    ##from f2scodigo import ObjCode128
    import f2s_cod128
    import uuid
    import os
    import f2s_funciones
    from reportlab.graphics import renderPDF
    from reportlab.lib.utils import ImageReader
    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.platypus import Paragraph, Image
    from reportlab.lib.styles import ParagraphStyle
    ##from reportlab.lib.styles import getSampleStyleSheet

    #factura
    rutaimgs = os.path.join(
        request.folder,
        "uploads",
        "{}".format(factura.created_on.year),
        "{}".format(factura.created_on.month),
    )
    #factura.arch_siesa)
    #Letras Definidas
    rutafont = os.path.join(request.folder, "static", "fonts")
    pdfmetrics.registerFont(
        TTFont('Ubuntu', os.path.join(rutafont, 'Ubuntu-R.ttf')))
    pdfmetrics.registerFont(
        TTFont('Ubuntu-Bold', os.path.join(rutafont, 'Ubuntu-B.ttf')))
    pdfmetrics.registerFont(
        TTFont('Ubuntu-Cond', os.path.join(rutafont, 'Ubuntu-C.ttf')))
    pdfmetrics.registerFont(
        TTFont('Cod128', os.path.join(rutafont, 'Codigo128.ttf')))
    #Creacion del archivo de datos factura posicionado
    datos_pdf = os.path.join("/tmp", "{}{}.pdf".format(uuid.uuid4(),
                                                       factura.nrofac))
    pdf_f2s = canvas.Canvas(datos_pdf, pagesize=letter)
    #Resoluucion Dian
    angulo = 90
    pdf_f2s.rotate(angulo)
    pdf_f2s.setFont("Ubuntu", 6)
    pdf_f2s.drawString(215, -512, factura.resolucion.decode('cp437').strip())
    pdf_f2s.rotate(angulo * -1)

    #encabezado
    pdf_f2s.setFont("Ubuntu-Bold", 15)
    posy = 629
    posx = 525
    pdf_f2s.drawRightString(
        posx - 5, posy, "{}-".format(factura.prefijo.decode('cp437').strip()))
    pdf_f2s.drawString(posx, posy, "{}".format(factura.nrofac))
    posx = 30
    pdf_f2s.setFont("Ubuntu-Bold", 9)
    posy = 670
    pdf_f2s.drawString(posx, posy, factura.empresa.decode('cp437').strip())
    pdf_f2s.setFont("Ubuntu", 8)
    posy = 660
    pdf_f2s.drawString(posx, posy,
                       factura.representante.decode('cp437').strip())
    pdf_f2s.drawString(posx, posy - 9, factura.nitfac.decode('cp437').strip())
    pdf_f2s.drawString(
        posx + 160, posy - 9,
        "Tel:{}".format(factura.telefono.decode('cp437')).strip())
    pdf_f2s.drawString(posx, posy - 18,
                       factura.direccion.decode('cp437').strip())
    pdf_f2s.drawString(posx, posy - 27, factura.ciudad.decode('cp437').strip())
    pdf_f2s.drawString(posx, posy - 36, factura.barrio.decode('cp437').strip())
    #Fecha Factura
    posy = 664
    posx = 345
    pdf_f2s.drawString(posx, posy, factura.fecfac[8:10].strip())
    pdf_f2s.drawString(posx + 30, posy, factura.fecfac[5:7].strip())
    pdf_f2s.drawString(posx + 70, posy, factura.fecfac[:4].strip())
    #Fecha Vencimiento
    posy = 625
    pdf_f2s.drawString(posx, posy, factura.fecfac[8:10].strip())
    pdf_f2s.drawString(posx + 30, posy, factura.fecfac[5:7].strip())
    pdf_f2s.drawString(posx + 70, posy, factura.fecfac[:4].strip())

    #Detalle:
    posy = 590
    posx = 30
    for item in detalle:
        pdf_f2s.drawString(posx, posy, item.item.decode('cp437').strip())
        pdf_f2s.drawString(posx + 65, posy,
                           item.detalle.decode('cp437').strip())
        pdf_f2s.drawString(posx + 65, posy - 9,
                           item.detalle1.decode('cp437').strip())
        pdf_f2s.drawRightString(posx + 310, posy,
                                "{:,.0f}".format(item.cantidad))
        pdf_f2s.drawRightString(posx + 385, posy,
                                "{:,.0f}".format(item.unitario))
        pdf_f2s.drawRightString(posx + 470, posy,
                                "{:,.0f}".format(item.valortotal))
        posy -= 22
    #pie
    posy = 295
    posx = 30
    #pdf_f2s.drawString(posx, posy,factura.son.decode('cp437').strip() )
    style = ParagraphStyle(
        name='Normal',
        fontName='Ubuntu',
        fontSize=8,
        leading=10,
    )
    p = Paragraph(factura.son.decode('cp437').strip(), style)
    w, h = p.wrapOn(pdf_f2s, 464, 100)
    p.drawOn(pdf_f2s, posx, posy - h)

    posy = 260
    posx = 30
    style = ParagraphStyle(
        name='Normal',
        fontName='Ubuntu',
        fontSize=8,
        leading=9,
    )
    p = Paragraph(factura.observaciones.decode('cp437').strip(), style)
    w, h = p.wrapOn(pdf_f2s, 280, 100)
    p.drawOn(pdf_f2s, posx, posy - h)

    posy = 264
    posx = 320
    pdf_f2s.setFont("Ubuntu", 7)
    pdf_f2s.drawString(posx, posy,
                       "cufe:{}".format(factura.cufe.decode('cp437').strip()))
    pdf_f2s.setFont("Ubuntu", 8)
    posy = 250
    posx = 490
    pdf_f2s.drawRightString(posx, posy, "{:,.0f}".format(factura.valfac))
    pdf_f2s.drawRightString(posx, posy - 10, "{:,.0f}".format(factura.valiva))
    pdf_f2s.setFont("Ubuntu-Bold", 10)
    pdf_f2s.drawRightString(posx, posy - 32, "{:,.0f}".format(factura.valtot))

    posy = 116
    posx = 30
    pdf_f2s.setFont("Ubuntu", 7)
    pdf_f2s.drawString(posx, posy, factura.empresa.decode('cp437').strip())
    pdf_f2s.drawString(posx + 150, posy, "{}".format(factura.nrofac))
    pdf_f2s.drawString(posx + 230, posy,
                       factura.nitfac.decode('cp437').strip())
    pdf_f2s.drawString(posx + 307, posy, "{:,.0f}".format(factura.valtot))
    pdf_f2s.drawString(posx + 358, posy, factura.fecfac[8:10].strip())
    pdf_f2s.drawString(posx + 385, posy, factura.fecfac[5:7].strip())
    pdf_f2s.drawString(posx + 412, posy, factura.fecfac[:4].strip())

    #codigo de barras
    posy = 15
    posx = 75
    pdf_f2s.setFont("Ubuntu", 7)
    codigo = "(415)7709998015937(8020){:06d}{:018d}(3900){:010d}(96){}{}{}".format(
        factura.nrofac, int(factura.nitfac.strip()), int(factura.valtot),
        factura.fecfac[8:10], factura.fecfac[5:7], factura.fecfac[:4])
    pdf_f2s.drawString(posx, posy, codigo)
    posy = 25
    posx = 10
    codigobar = f2s_cod128.code128_image(chr(102) + codigo)
    pdf_f2s.drawImage(ImageReader(codigobar), posx, posy, width=450, height=35)

    #qr
    posy = 670
    posx = 503
    rutaimagenes = os.path.join(request.folder, "uploads",
                                str(factura.created_on.year),
                                str(factura.created_on.month), factura.arch_qr)
    logo = Image(rutaimagenes)
    logo.drawHeight = logo.drawHeight - 32
    logo.drawWidth = logo.drawWidth - 32
    logo.wrapOn(pdf_f2s, logo.drawWidth, logo.drawHeight)
    logo.drawOn(pdf_f2s, posx, posy)

    #Activar aui
    if AIU:
        posy = 300
        posx = 30
        pdf_f2s.setFont("Ubuntu", 7)
        pdf_f2s.drawString(
            posx, posy, "AIU 10%:{:,.0f} Tomado desde Subtotal".format(
                factura.valfac * .1))

    #Fin
    pdf_f2s.showPage()
    pdf_f2s.save()
    return datos_pdf
Example #29
0
def createpdf(team1, team2, date, refteam, time):
    print("Confeccionando PDF...")
    w, h = A4  #595.2 puntos de ancho (width) y 841.8 puntos de alto (height).
    global newh  #Auxiliar height
    global newh2  #Auxiliar height 2
    group1 = get_group(team1)
    group2 = get_group(team2)
    if group1 != group2:
        group = '?'
    else:
        group = group1

    temporadalocal = fileToModel(group1)  #Current season
    temporadavisitante = fileToModel(group2)
    city = get_city(team1)

    c = canvas.Canvas("previa.pdf", pagesize=A4)
    c.setFont("Helvetica", 12)

    #Título de documento.
    c.drawString(235, h - 50, "PREVIA DE PARTIDO")

    #Tabla de equipos
    data = [[team1.upper(), team2.upper()]]
    t = Table(data, colWidths=[255, 255], rowHeights=[70])
    t.setStyle(
        TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.lavender),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold')]))
    t.wrapOn(c, w, h)
    t.drawOn(c, 45, h - 170)

    #Grid de datos principales.
    xl1 = [45, 150, 280, 350, 450, 555]
    xl2 = [45, 297, 555]
    yl1 = [h - 65, h - 100]
    yl2 = [h - 100, h - 170]

    c.grid(xl1, yl1)
    c.drawString(60, h - 87, date)
    c.drawString(178, h - 80, "CATEGORÍA")
    c.drawString(155, h - 93, "PREFERENTE, GR. " + group)
    c.drawString(300, h - 87, time)

    journey = str(temporadalocal.get_njornadas() + 1)
    iv = "Vuelta (Ida: 0-2)"
    c.drawString(370, h - 80, "Jornada " + journey)
    c.drawString(358, h - 93, iv)

    tipocampo = "(HA)"
    campo = "Román Valero " + tipocampo
    tc = c.beginText(455, h - 80)
    tc.textLines(splitString(15, campo))
    c.drawText(tc)

    #Equipo Arbitral
    arbitro = "D. " + refteam[0]
    aa1 = "D. " + refteam[1]
    aa2 = "D. " + refteam[2]
    dp = "D. " + refteam[3]
    comite = "COMITÉ MADRILEÑO"

    eqa = c.beginText(45, h - 195)
    eqa.setFont("Helvetica-Bold", 12)
    eqa.textLine("EQUIPO ARBITRAL:")
    c.drawText(eqa)

    c.drawString(75, h - 220, "Árbitro: ")
    c.drawString(75, h - 240, "Asistente 1: ")
    c.drawString(75, h - 260, "Asistente 2: ")
    c.drawString(75, h - 280, "Delegado de partido: ")

    eqa.setFont("Helvetica", 12)
    c.drawText(eqa)

    c.drawString(125, h - 220, arbitro + " - " + comite)
    c.drawString(149, h - 240, aa1 + " - " + comite)
    c.drawString(149, h - 260, aa2 + " - " + comite)
    c.drawString(199, h - 280, dp + " - " + comite)

    #Tablas de estadísitcas numéricas
    lm1 = process_matchs(temporadalocal, team1)
    lm2 = process_matchs(temporadavisitante, team2)
    draw1, won1, lost1, localdraw1, localwon1, locallost1, visdraw1, viswon1, vislost1 = process_dwl(
        temporadalocal, team1)
    draw2, won2, lost2, localdraw2, localwon2, locallost2, visdraw2, viswon2, vislost2 = process_dwl(
        temporadavisitante, team2)
    against1, favor1, local_against1, local_favor1, vis_against1, vis_favor1 = process_goals(
        temporadalocal, team1)
    against2, favor2, local_against2, local_favor2, vis_against2, vis_favor2 = process_goals(
        temporadavisitante, team2)

    data1 = [['', 'PG', 'PE', 'PP', 'GF', 'GC'],
             ['Tot', won1, draw1, lost1, favor1, against1],
             [
                 'Loc', localwon1, localdraw1, locallost1, local_favor1,
                 local_against1
             ], ['Últ', lm1[0][0], lm1[1][0], lm1[2][0], lm1[3][0], lm1[4][0]]]
    data2 = [['PG', 'PE', 'PP', 'GF', 'GC', ''],
             [won2, draw2, lost2, favor2, against2, 'Tot'],
             [viswon2, visdraw2, vislost2, vis_favor2, vis_against2, 'Vis'],
             [lm2[0][0], lm2[1][0], lm2[2][0], lm2[3][0], lm2[4][0], 'Últ']]
    t1 = Table(data1)
    t2 = Table(data2)

    t1.setStyle(
        TableStyle([('BACKGROUND', (1, 0), (1, 0), colors.green),
                    ('BACKGROUND', (2, 0), (2, 0), colors.orange),
                    ('BACKGROUND', (3, 0), (3, 0), colors.red),
                    ('BACKGROUND', (1, 3), (1, 3), lm1[0][1]),
                    ('BACKGROUND', (2, 3), (2, 3), lm1[1][1]),
                    ('BACKGROUND', (3, 3), (3, 3), lm1[2][1]),
                    ('BACKGROUND', (4, 3), (4, 3), lm1[3][1]),
                    ('BACKGROUND', (5, 3), (5, 3), lm1[4][1]),
                    ('TEXTCOLOR', (1, 1), (1, 2), colors.green),
                    ('TEXTCOLOR', (2, 1), (2, 2), colors.orange),
                    ('TEXTCOLOR', (3, 1), (3, 2), colors.red),
                    ('FONTNAME', (1, 0), (5, 0), 'Helvetica-Bold'),
                    ('INNERGRID', (1, 0), (-1, -1), 0.25, colors.black),
                    ('BOX', (1, 0), (-1, -1), 0.25, colors.black)]))

    t2.setStyle(
        TableStyle([('BACKGROUND', (0, 0), (0, 0), colors.green),
                    ('BACKGROUND', (1, 0), (1, 0), colors.orange),
                    ('BACKGROUND', (2, 0), (2, 0), colors.red),
                    ('BACKGROUND', (0, 3), (0, 3), lm2[0][1]),
                    ('BACKGROUND', (1, 3), (1, 3), lm2[1][1]),
                    ('BACKGROUND', (2, 3), (2, 3), lm2[2][1]),
                    ('BACKGROUND', (3, 3), (3, 3), lm2[3][1]),
                    ('BACKGROUND', (4, 3), (4, 3), lm2[4][1]),
                    ('TEXTCOLOR', (0, 1), (0, 2), colors.green),
                    ('TEXTCOLOR', (1, 1), (1, 2), colors.orange),
                    ('TEXTCOLOR', (2, 1), (2, 2), colors.red),
                    ('FONTNAME', (0, 0), (5, 0), 'Helvetica-Bold'),
                    ('INNERGRID', (0, 0), (-2, -1), 0.25, colors.black),
                    ('BOX', (0, 0), (-2, -1), 0.25, colors.black)]))

    t1.wrapOn(c, w, h)
    t1.drawOn(c, 40, h - 390)
    t2.wrapOn(c, w, h)
    t2.drawOn(c, 400, h - 390)

    #Header de las tablas, PUNTOS.
    puntos1 = '13º - 38 PUNTOS'
    puntos2 = '20º - 2 PUNTOS'

    data3 = [[puntos1]]
    data4 = [[puntos2]]
    h1 = Table(data3, colWidths=[130.02])
    h2 = Table(data4, colWidths=[130.02])

    h1.setStyle(
        TableStyle([('BACKGROUND', (0, 0), (0, 0), colors.lavender),
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                    ('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold')]))

    h2.setStyle(
        TableStyle([('BACKGROUND', (0, 0), (0, 0), colors.lavender),
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                    ('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold')]))

    h1.wrapOn(c, w, h)
    h1.drawOn(c, 68.12, h - 318)
    h2.wrapOn(c, w, h)
    h2.drawOn(c, 400, h - 318)

    #El tiempo: prob_precipitacion, estado_cielo, vientodir, vientovel, tmax, tmin
    eqa.setFont("Helvetica", 10)
    c.drawText(eqa)

    #tiempo = {'prob_precipitacion': '0', 'estado_cielo': '11', 'vientodir': 'O', 'vientovel': '5', 'tmax': '38', 'tmin': '22'}
    #date: 2020-07-21
    if date == None:
        path = pathIcon(None)
        tiempo = get_forecast(city, None, None, None)
    else:
        date = date.split('-')
        tiempo = get_forecast(city, date[0], date[1], date[2])
        path = pathIcon(tiempo['estado_cielo'])
    I = Image(path)
    I.drawHeight = 0.6 * inch * I.drawHeight / I.drawWidth
    I.drawWidth = 0.6 * inch
    dfor = [
        [city.upper()], [I], ['Lluvia: ' + tiempo['prob_precipitacion'] + '%'],
        ['Viento: ' + tiempo['vientovel'] + ' km/h ' + tiempo['vientodir']]
    ]
    tfor = Table(dfor)
    tfor.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]))
    tfor.wrapOn(c, w, h)
    tfor.drawOn(c, 252, h - 398)
    c.drawString(245, h - 342, tiempo['tmax'] + 'ºC')
    c.drawString(323, h - 342, tiempo['tmin'] + 'ºC')

    #Equipamiento1
    plfirstkit = get_player_first_kit(team1)
    shirt1 = transform_color(plfirstkit['shirt1'])
    shirt2 = transform_color(plfirstkit['shirt2'])
    shorts1 = transform_color(plfirstkit['shorts1'])
    shorts2 = transform_color(plfirstkit['shorts2'])
    shocks1 = transform_color(plfirstkit['shocks1'])
    shocks2 = transform_color(plfirstkit['shocks2'])
    customColor1 = colors.Color(red=shirt1[0], green=shirt1[1], blue=shirt1[2])
    customColor2 = colors.Color(red=shirt2[0], green=shirt2[1], blue=shirt2[2])
    customColor3 = colors.Color(red=shorts1[0],
                                green=shorts1[1],
                                blue=shorts1[2])
    customColor4 = colors.Color(red=shorts2[0],
                                green=shorts2[1],
                                blue=shorts2[2])
    customColor5 = colors.Color(red=shocks1[0],
                                green=shocks1[1],
                                blue=shocks1[2])
    customColor6 = colors.Color(red=shocks2[0],
                                green=shocks2[1],
                                blue=shocks2[2])

    deq1 = [['Camiseta', '', ''], ['Pantalón', '', ''], ['Medias', '', '']]
    teq1 = Table(deq1, colWidths=[90, 75, 75])
    teq1.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('INNERGRID', (1, 0), (-1, -1), 1, colors.black),
            ('BACKGROUND', (1, 0), (1, 0), customColor1),  #camiseta1
            ('BACKGROUND', (2, 0), (2, 0), customColor2),  #camiseta2
            ('BACKGROUND', (1, 1), (1, 1), customColor3),  #pantalón1
            ('BACKGROUND', (2, 1), (2, 1), customColor4),  #pantalón2
            ('BACKGROUND', (1, 2), (1, 2), customColor5),  #medias1
            ('BACKGROUND', (-1, -1), (-1, -1), customColor6),  #medias2
        ]))
    teq1.wrapOn(c, w, h)
    teq1.drawOn(c, 45, h - 470)

    #Equipamiento2
    plfirstkit = get_player_first_kit(team2)
    shirt1 = transform_color(plfirstkit['shirt1'])
    shirt2 = transform_color(plfirstkit['shirt2'])
    shorts1 = transform_color(plfirstkit['shorts1'])
    shorts2 = transform_color(plfirstkit['shorts2'])
    shocks1 = transform_color(plfirstkit['shocks1'])
    shocks2 = transform_color(plfirstkit['shocks2'])
    customColor1 = colors.Color(red=shirt1[0], green=shirt1[1], blue=shirt1[2])
    customColor2 = colors.Color(red=shirt2[0], green=shirt2[1], blue=shirt2[2])
    customColor3 = colors.Color(red=shorts1[0],
                                green=shorts1[1],
                                blue=shorts1[2])
    customColor4 = colors.Color(red=shorts2[0],
                                green=shorts2[1],
                                blue=shorts2[2])
    customColor5 = colors.Color(red=shocks1[0],
                                green=shocks1[1],
                                blue=shocks1[2])
    customColor6 = colors.Color(red=shocks2[0],
                                green=shocks2[1],
                                blue=shocks2[2])

    deq2 = [['Camiseta', '', ''], ['Pantalón', '', ''], ['Medias', '', '']]
    teq2 = Table(deq2, colWidths=[90, 75, 75])
    teq2.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('INNERGRID', (1, 0), (-1, -1), 1, colors.black),
            ('BACKGROUND', (1, 0), (1, 0), customColor1),  #camiseta1
            ('BACKGROUND', (2, 0), (2, 0), customColor2),  #camiseta2
            ('BACKGROUND', (1, 1), (1, 1), customColor3),  #pantalón1
            ('BACKGROUND', (2, 1), (2, 1), customColor4),  #pantalón2
            ('BACKGROUND', (1, 2), (1, 2), customColor5),  #medias1
            ('BACKGROUND', (-1, -1), (-1, -1), customColor6)  #medias2
        ]))
    teq2.wrapOn(c, w, h)
    teq2.drawOn(c, 310, h - 470)

    #Portero1
    plfirstkit = get_gk_first_kit(team1)
    shirt1 = transform_color(plfirstkit['shirt1'])
    shirt2 = transform_color(plfirstkit['shirt2'])
    shorts1 = transform_color(plfirstkit['shorts1'])
    shorts2 = transform_color(plfirstkit['shorts2'])
    shocks1 = transform_color(plfirstkit['shocks1'])
    shocks2 = transform_color(plfirstkit['shocks2'])
    customColor1 = colors.Color(red=shirt1[0], green=shirt1[1], blue=shirt1[2])
    customColor2 = colors.Color(red=shirt2[0], green=shirt2[1], blue=shirt2[2])
    customColor3 = colors.Color(red=shorts1[0],
                                green=shorts1[1],
                                blue=shorts1[2])
    customColor4 = colors.Color(red=shorts2[0],
                                green=shorts2[1],
                                blue=shorts2[2])
    customColor5 = colors.Color(red=shocks1[0],
                                green=shocks1[1],
                                blue=shocks1[2])
    customColor6 = colors.Color(red=shocks2[0],
                                green=shocks2[1],
                                blue=shocks2[2])

    dp1 = [['Camiseta portero', '', ''], ['Pantalón portero', '', ''],
           ['Medias portero', '', '']]
    tp1 = Table(dp1, colWidths=[90, 75, 75])
    tp1.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('INNERGRID', (1, 0), (-1, -1), 1, colors.black),
            ('BACKGROUND', (1, 0), (1, 0), customColor1),  #camiseta1
            ('BACKGROUND', (2, 0), (2, 0), customColor2),  #camiseta2
            ('BACKGROUND', (1, 1), (1, 1), customColor3),  #pantalón1
            ('BACKGROUND', (2, 1), (2, 1), customColor4),  #pantalón2
            ('BACKGROUND', (1, 2), (1, 2), customColor5),  #medias1
            ('BACKGROUND', (-1, -1), (-1, -1), customColor6)  #medias2
        ]))
    tp1.wrapOn(c, w, h)
    tp1.drawOn(c, 45, h - 540)

    #Portero2
    plfirstkit = get_gk_first_kit(team2)
    shirt1 = transform_color(plfirstkit['shirt1'])
    shirt2 = transform_color(plfirstkit['shirt2'])
    shorts1 = transform_color(plfirstkit['shorts1'])
    shorts2 = transform_color(plfirstkit['shorts2'])
    shocks1 = transform_color(plfirstkit['shocks1'])
    shocks2 = transform_color(plfirstkit['shocks2'])
    customColor1 = colors.Color(red=shirt1[0], green=shirt1[1], blue=shirt1[2])
    customColor2 = colors.Color(red=shirt2[0], green=shirt2[1], blue=shirt2[2])
    customColor3 = colors.Color(red=shorts1[0],
                                green=shorts1[1],
                                blue=shorts1[2])
    customColor4 = colors.Color(red=shorts2[0],
                                green=shorts2[1],
                                blue=shorts2[2])
    customColor5 = colors.Color(red=shocks1[0],
                                green=shocks1[1],
                                blue=shocks1[2])
    customColor6 = colors.Color(red=shocks2[0],
                                green=shocks2[1],
                                blue=shocks2[2])

    dp2 = [['Camiseta portero', '', ''], ['Pantalón portero', '', ''],
           ['Medias portero', '', '']]
    tp2 = Table(dp2, colWidths=[90, 75, 75])
    tp2.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('INNERGRID', (1, 0), (-1, -1), 1, colors.black),
            ('BACKGROUND', (1, 0), (1, 0), customColor1),  #camiseta1
            ('BACKGROUND', (2, 0), (2, 0), customColor2),  #camiseta2
            ('BACKGROUND', (1, 1), (1, 1), customColor3),  #pantalón1
            ('BACKGROUND', (2, 1), (2, 1), customColor4),  #pantalón2
            ('BACKGROUND', (1, 2), (1, 2), customColor5),  #medias1
            ('BACKGROUND', (-1, -1), (-1, -1), customColor6)  #medias2
        ]))
    tp2.wrapOn(c, w, h)
    tp2.drawOn(c, 310, h - 540)

    #Petos1
    dpe1 = [['Petos', 'Color']]
    tpe1 = Table(dpe1, colWidths=[90, 150])
    tpe1.setStyle(
        TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black)]))
    tpe1.wrapOn(c, w, h)
    tpe1.drawOn(c, 45, h - 575)

    #Petos2
    dpe2 = [['Petos', 'Color']]
    tpe2 = Table(dpe2, colWidths=[90, 150])
    tpe2.setStyle(
        TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black)]))
    tpe2.wrapOn(c, w, h)
    tpe2.drawOn(c, 310, h - 575)

    #Otros datos 1
    dod1 = [['Suplentes: 5', 'Recogepelotas: ¿?'],
            ['Oficiales: 5', 'Fotógrafo: ¿?']]
    tod1 = Table(dod1, colWidths=[90, 150])
    tod1.setStyle(
        TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black)]))
    tod1.wrapOn(c, w, h)
    tod1.drawOn(c, 45, h - 628)

    #Otros datos 2
    dod2 = [['Suplentes: 5', 'Recogepelotas: ¿?'],
            ['Oficiales: 5', 'Fotógrafo: ¿?']]
    tod2 = Table(dod2, colWidths=[90, 150])
    tod2.setStyle(
        TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black)]))
    tod2.wrapOn(c, w, h)
    tod2.drawOn(c, 310, h - 628)

    #Equipo técnico 1
    eqa.setFont("Helvetica", 10)
    c.drawText(eqa)
    oficiales1 = get_coachs(team1)
    oficiales2 = get_coachs(team2)
    drawCt(c, oficiales1, 45, h - 196.8, len(oficiales1))
    drawCt(c, oficiales2, 310, h - 196.8, len(oficiales2))

    #A partir de aquí, la altura es variable. Usaremos newh en vez de h.
    nsancionados1 = 1
    nsancionados2 = 2
    sancionados1 = [("tipo", "nombre"), ("tipo", "nombre2"),
                    ("tipo3.", "nombre3")]
    sancionados2 = [("tipo", "nombre"), ("tipo", "nombre2"),
                    ("tipo3.", "nombre3")]
    drawJs(c, sancionados1, 45, h - newh + 17, nsancionados1)
    drawJs(c, sancionados2, 310, h - newh + 17, nsancionados2)

    #Delegado de campo
    eqa.setFont("Helvetica-Bold", 10)
    c.drawText(eqa)
    c.drawString(45, newh2 - 20, "Delegado de campo:")
    eqa.setFont("Helvetica", 10)
    c.drawText(eqa)
    c.drawString(147, newh2 - 20, "Juan Hernández Maeso")

    c.showPage()
    c.save()

    print("PDF confeccionado.")
Example #30
0
def LATTE_DV(tic,
             indir,
             syspath,
             transit_list,
             sectors_all,
             target_ra,
             target_dec,
             tessmag,
             teff,
             srad,
             bls_stats1,
             bls_stats2,
             tpf_corrupt,
             astroquery_corrupt,
             FFI,
             bls=False,
             model=False,
             mpi=False,
             test='no'):
    '''
	funtion that makes compiles all of the information and figures into a comprehensive pdf summary document.

    Parameters
    ----------
    tic  :   str
        target TIC ID
    indir  :  str
        path to directory where all the plots and data will be saved. 
    sectors_all  :   list
        all the sectors in which the target has been/ will be observed
    target_ra   :  float
        the right ascension of the target
    target_dec   :  float
        the declination of the target
    tessmag  :  float
        TESS magnitude of the target star
    teff  :  float
        effective temperature of the tagret star (K)
    srad  :  float
        radius of the target star (solar radii)
	bls_stats1  :  list
		list of the returned stats of the initial bls search
	bls_stats2  :  list
		list of the returned stats of the second bls search
	FFI  :  bool
		whether the input data is from FFIs (True = from FFIs)
	bls  :  bool  (false)
		whether the bls search was run 
	model  :  bool  (false)
		whether the transit was modelled (only works if payenti has sucessfully been installed)
    Returns
    -------
    LATTE Data Validation report in PDF format.

	'''

    # ---- CHECK WHETHER THE TARGET IS A TCE OR A TOI ----
    print("\n Start compiling the data validation report...")

    # TCE -----
    lc_dv = np.genfromtxt('{}/data/tesscurl_sector_all_dv.sh'.format(indir),
                          dtype=str)

    TCE_links = []

    for i in lc_dv:
        if str(tic) in str(i[6]):
            TCE_links.append(i[6])

    if len(TCE_links) == 0:
        TCE = " - "

    else:
        TCE_links = np.sort(TCE_links)
        TCE_link = TCE_links[
            0]  # this link should allow you to acess the MAST DV report
        TCE = 'Yes **'
        TCE_link = '<link href="%s" color="blue">here</link>' % TCE_link

    # TOI -----
    TOI_planets = pd.read_csv('{}/data/TOI_list.txt'.format(indir),
                              comment="#")

    TOIpl = TOI_planets.loc[TOI_planets['TIC'] == float(tic)]

    if len(TOIpl) == 0:
        TOI = ' -  '
    else:
        TOI = (float(TOIpl["Full TOI ID"]))

    # ------ PARAMS ------
    ra = float(target_ra)
    dec = float(target_dec)

    def addPageNumber(canvas, doc):
        """
		Add the page numbers to the document
		"""
        width, height = A4  # this is useful when defining where to plot something on the page

        page_num = canvas.getPageNumber()
        text = "%s" % page_num
        header = "TIC {}".format(tic)

        canvas.setFont('Helvetica', 8)
        canvas.drawString(width * 0.85, height * 0.95, header)
        canvas.drawRightString(200 * mm, 10 * mm, text)

    #------------------------------------------------------------------
    # Recall the names of all the plots that will be in the DV report
    #------------------------------------------------------------------

    # plot the full light curve, with marked sectors and marked transit - binned and unbinned

    full_LC_name = "{}/{}/{}_fullLC_md.png".format(indir, tic, tic)

    background_flux_name = '{}/{}/{}_background.png'.format(indir, tic, tic)

    centroid_positions_name = '{}/{}/{}_centroids.png'.format(indir, tic, tic)

    flux_aperture_name = '{}/{}/{}_aperture_size.png'.format(indir, tic, tic)

    tess_stars_name = '{}/{}/{}_star_field.png'.format(indir, tic, tic)

    #SDSS_stars_name = '{}/{}/{}_SDSSstar_field.png'.format(indir, tic, tic)

    nearest_neighbour_name = '{}/{}/{}_nearest_neighbours.png'.format(
        indir, tic, tic)

    pixel_LCs_name = '{}/{}/{}_individual_pixel_LCs_0.png'.format(
        indir, tic, tic)

    bls1 = '{}/{}/{}_bls_first.png'.format(indir, tic, tic)

    bls2 = '{}/{}/{}_bls_second.png'.format(indir, tic, tic)

    in_out_name = '{}/{}/{}_flux_comparison.png'.format(indir, tic, tic)

    model_name = '{}/{}/model_out/{}b_tr.png'.format(indir, tic, tic)

    phasefold_name = '{}/{}/{}_phase_folded.png'.format(indir, tic, tic)

    apertures_name = '{}/{}/{}_apertures_0.png'.format(indir, tic, tic)

    # ----- LOGOS ------
    # if this is a unittest run, find the files for the logos stored in the test folder
    if test != 'no':
        PHT_logo_name = '{}/LATTE_imgs/PHT_logo.jpg'.format(test)
        LATTE_logo_name = '{}/LATTE_imgs/LATTE_logo.png'.format(test)
        TESS_logo_name = '{}/LATTE_imgs/TESS_logo.png'.format(test)

    # otherwise they're located in the place where the program is insatlled.
    else:
        PHT_logo_name = '{}/LATTE_imgs/PHT_logo.jpg'.format(syspath)
        LATTE_logo_name = '{}/LATTE_imgs/LATTE_logo.png'.format(syspath)
        TESS_logo_name = '{}/LATTE_imgs/TESS_logo.png'.format(syspath)

    # -------------------------------------------
    # Make a PDF summary file
    # -------------------------------------------

    doc = SimpleDocTemplate("{}/{}/DV_report_{}.pdf".format(indir, tic, tic),
                            pagesize=A4,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=40,
                            bottomMargin=20)

    width, height = A4  # this is useful when defining where to plot something on the page

    Story = []

    fig_count = 0
    table_count = 0

    # title
    title = "PHT Data Validation Report"
    subheading = "TIC {}".format(tic)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='centre', alignment=TA_CENTER))
    ptext = '<font size=12><b>%s</b></font>' % title
    subtext = '<font size=12><b>%s</b></font>' % subheading

    Story.append(Paragraph(ptext, styles["centre"]))
    Story.append(Paragraph(subtext, styles["centre"]))
    Story.append(Spacer(1, 30))

    # ----- ADD THE LOGOS -------
    PHT_logo = Image(PHT_logo_name)
    PHT_logo.drawHeight = 0.5 * inch * PHT_logo.drawHeight / PHT_logo.drawWidth
    PHT_logo.drawWidth = 0.5 * inch

    LATTE_logo = Image(LATTE_logo_name)
    LATTE_logo.drawHeight = 0.5 * inch * LATTE_logo.drawHeight / LATTE_logo.drawWidth
    LATTE_logo.drawWidth = 0.5 * inch

    TESS_logo = Image(TESS_logo_name)
    TESS_logo.drawHeight = 0.8 * inch * TESS_logo.drawHeight / TESS_logo.drawWidth
    TESS_logo.drawWidth = 0.8 * inch

    logo_table = (Table([[PHT_logo, LATTE_logo, TESS_logo]],
                        colWidths=[width * 0.1],
                        rowHeights=[1 * mm]))

    logo_table.setStyle(
        TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTRE'),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')]))

    Story.append(logo_table)

    Story.append(Spacer(1, 30))
    # ----------------------------

    line = MCLine(width * 0.77)
    Story.append(line)
    Story.append(Spacer(1, 2))
    line = MCLine_color(width * 0.77)
    Story.append(line)
    Story.append(Spacer(1, 20))

    # --------------------------------------------
    # Full Image with momentum dumps
    # --------------------------------------------
    im = Image(full_LC_name)
    im._restrictSize(width * 0.8, width * 0.8)
    Story.append(im)

    fig_count += 1

    full_image_text = "Fig {}. Full lightcurve for target TIC {}. The solid red lines at the bottom of the figure indicated the \
	times of the reaction wheel momentum dumps and the dashed black line(s) show the time(s) of the marked transit event(s). Momentum dumps \
	occur around every 2 to 2.5 days and typically last around half an hour.".format(
        fig_count, tic)

    ptext = '<font size=8>%s</font>' % full_image_text
    Story.append(Paragraph(ptext, styles["Normal"]))

    # --------------------------------------
    # ------ stellar parameters table ------
    # --------------------------------------
    try:
        srad = float(srad)
    except:
        srad = -999

    try:
        teff = float(teff)
    except:
        teff = -999

    data_stellar = [
        ['Parameter', "Value", "Unit"],
        [
            'TIC ID',
            tic,
        ],
        ['RA', ra, "degrees"],
        ['Dec', dec, "degrees"],
        ['Radius', "{:.4f}".format(srad), "Solar Radii"],
        ['Tess Mag', "{:.4f}".format(tessmag), "Mag"],
        ['Teff', "{:.0f}".format(teff), "Kelvin"],
        [
            'Sectors',
            "{} *".format(str(sectors_all)[1:-1]),
        ],
        [
            'TCE',
            TCE,
        ],
        [
            'TOI',
            "{}".format(str(TOI)),
        ],
    ]

    table_stellar = Table(data_stellar)
    table_stellar = Table(data_stellar,
                          colWidths=width * 0.2,
                          style=[
                              ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black),
                              ('LINEABOVE', (0, 10), (-1, 10), 1,
                               colors.black),
                              ('FONTSIZE', (0, 0), (-1, 9), 8),
                          ])

    data_len = len(data_stellar)

    for each in range(data_len):
        if each % 2 == 0:
            bg_color = colors.whitesmoke
        else:
            bg_color = colors.white

        table_stellar.setStyle(
            TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)]))

    # ------ ADD A LINE TO SEPERATE SECTIONS -----

    Story.append(Spacer(1, 20))
    line = MCLine(width * 0.77)
    Story.append(line)

    # ------

    Story.append(Spacer(1, 20))
    ptext = '<font size=9>Target Properties</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    Story.append(table_stellar)
    Story.append(Spacer(1, 15))

    table_count += 1

    exofop_url = "https://exofop.ipac.caltech.edu/tess/target.php?id={}".format(
        tic)
    exofop_link = '<link href="%s" color="blue">TIC %s</link>' % (exofop_url,
                                                                  tic)

    if TCE == 'Yes **':
        Stellartable_text = "Table {}. Stellar properties of {}. \
			* List of the sectors in which the target will be has been \
			observed. ** Click {} for the TCE report.".format(table_count, exofop_link,
                                                     TCE_link)

    else:
        Stellartable_text = "Table {}. Stellar properties of the {}. \
			* List of the sectors in which the target will be has been \
			observed.".format(table_count, exofop_link)

    ptext = '<font size=8>%s</font>' % Stellartable_text
    Story.append(Paragraph(ptext, styles["Normal"]))

    # --------------------------------------------
    # Background
    # --------------------------------------------
    Story.append(PageBreak())  # always start a new page for this analysis
    im2 = Image(background_flux_name)

    if len(transit_list) == 1:
        im2._restrictSize(width * 0.55, width * 0.55)

    else:
        im2._restrictSize(width * 0.8, width * 0.8)

    Story.append(im2)

    fig_count += 1
    Story.append(Spacer(1, 1))
    background_text = "Fig {}. Background flux vs. time around the time of each transit-like event. \
		The vertical orange line indicates the time of the transit-like event.".format(
        fig_count)

    ptext = '<font size=8>%s</font>' % background_text
    Story.append(Paragraph(ptext, styles["Normal"]))

    # --------------------------------------------
    # Centroid Position
    # --------------------------------------------

    if FFI == False:
        Story.append(Spacer(1, 10))
        im3 = Image(centroid_positions_name)

        if len(transit_list) == 1:
            im3._restrictSize(width * 0.52, width * 0.52)
        else:
            im3._restrictSize(width * 0.7, width * 0.7)

        Story.append(im3)

        fig_count += 1
        centroid_text = "Fig {}. The x and y centroid positions around the time of each transit-like event. The black points shows the CCD column and row position of the target’s flux-weighted centroid. \
			The red shows the CCD column and row local motion differential velocity aberration (DVA), pointing drift, and thermal effects. \
			The vertical orange line indicates the time of the transit-like event".format(
            fig_count)

        ptext = '<font size=8>%s</font>' % centroid_text

        Story.append(Spacer(1, 5))

        Story.append(Paragraph(ptext, styles["Normal"]))

        Story.append(Spacer(1, 13))

        #Story.append(PageBreak()) # always start a new page for this analysis

    # the following plots will only exist if the TPF file is not corrupt - otherwise skip these.
    if tpf_corrupt == False:

        # --------------------------------------------
        # Flux Aperture
        # --------------------------------------------
        im4 = Image(flux_aperture_name)

        if len(transit_list) == 1:
            im4._restrictSize(width * 0.55, width * 0.55)
        else:
            im4._restrictSize(width * 0.7, width * 0.7)
        Story.append(im4)

        fig_count += 1
        Story.append(Spacer(1, 10))
        flux_aperture_text = "Fig {}. The lightcurve around the time of each transit-like event extracted with the SPOC pipeline \
			defined aperture (binned:blue, unbinned:grey) and the with an aperture that is 40 per cent smaller (red). The flux is extracted \
			from the target pixel files (TPFs) and has not been detrended or \
			corrected for systematics. The vertical orange line indicates the time of the transit-like event.".format(
            fig_count)

        ptext = '<font size=8>%s</font>' % flux_aperture_text
        Story.append(Paragraph(ptext, styles["Normal"]))

        # --------------------------------------------
        # Apertures Sizes
        # --------------------------------------------
        im45 = Image(apertures_name)

        im45._restrictSize(width * 0.4, width * 0.4)

        Story.append(im45)

        fig_count += 1

        Story.append(Spacer(1, 10))

        if FFI == False:
            aperture_text = "Fig {}. The apertures used to extract the lightcurves. The blue aperture on the right shows the \
			optimum aperture determined by the SPOC pipeline, which is used for the extraction of 2-minute cadence light curves shown in Figure 1. \
			The red outline on the left shows an aperture that is around 40 per cent smaller than the SPOC pipeline aperture which was used to extract the \
			red lightcurve shown in Figure {}.".format(fig_count, (fig_count - 1))
        else:
            aperture_text = "Fig {}. The larger (right hand side, blue) and the smaller (left hamd side, red) apertures used to extract the lightcurves shown in Figure {}.".format(
                fig_count, (fig_count - 1))

        ptext = '<font size=8>%s</font>' % aperture_text
        Story.append(Paragraph(ptext, styles["Normal"]))

        # --------------------------------------------
        # In and Out of Transit Comparison
        # --------------------------------------------

        Story.append(Spacer(1, 12))
        im5 = Image(in_out_name)

        im5._restrictSize(width * 0.9, width * 0.9)

        Story.append(im5)

        fig_count += 1
        Story.append(Spacer(1, 10))
        flux_aperture_text = "Fig {}. Difference images for target TIC {} for each transit like event. \
		Left: mean in-transit flux(left). Middle: mean out-of-transit flux. Right: difference between the mean out-of-transit and mean in-transit flux. \
		Ensure that the change in brightness occurs on target.".format(
            fig_count, tic)

        ptext = '<font size=8>%s</font>' % flux_aperture_text
        Story.append(Paragraph(ptext, styles["Normal"]))

        # --------------------------------------------
        # tess stars + SDSS star field
        # --------------------------------------------
        # can only put this in the report if astroquery is working.
        if astroquery_corrupt == False:

            Story.append(Spacer(1, 12))

            im6 = Image(tess_stars_name)

            # if not with mpi (two star images)
            if mpi == False:
                im6._restrictSize(width * 0.7, width * 0.5)
            else:
                im6._restrictSize(width * 0.35, width * 0.35)

            Story.append(im6)

            fig_count += 1
            tess_stars_text = "Fig {}. Left: The locations of nearby GAIA DR2 stars with mag < 15 (orange circle) within the Tess \
			Cut Out around TIC {} (red star). Only shown for one sector. Right: SDSS image of the surrounding field.".format(
                fig_count, tic)

            ptext = '<font size=8>%s</font>' % tess_stars_text
            Story.append(Paragraph(ptext, styles["Normal"]))

    # --------------------------------------------
    # nearest neighbours
    # --------------------------------------------
    #Story.append(PageBreak()) # always start a new page for this analysis
    if FFI == False:
        im7 = Image(nearest_neighbour_name)

        im7._restrictSize(width * 0.8, width * 0.8)

        Story.append(im7)
        fig_count += 1
        Story.append(Spacer(1, 10))
        nn_text = "Fig {}. Lightcurves of the five closest stars to target {} (top pannel). \
			The distances to the target star and the TESS magnitudes are shown for each star. Only ever shown for one sector.".format(
            fig_count, tic)

        ptext = '<font size=8>%s</font>' % nn_text
        Story.append(Paragraph(ptext, styles["Normal"]))

    # this plot also only exists if the TPF downloaded sucessfully
    if tpf_corrupt == False:
        # --------------------------------------------
        # pixel_LCs_name
        # --------------------------------------------
        Story.append(Spacer(1, 10))
        im8 = Image(pixel_LCs_name)

        im8._restrictSize(width * 0.65, width * 0.65)

        Story.append(im8)
        fig_count += 1
        pixLC_text = "Fig {}. Normalised flux extracted for each pixel, using the SPOC pipeline mask, around the time of the transit-like event. \
		The orange/red data points show the in-transit data. The solid red lines show the SPOC pipeline mask. Only shown for one sector.".format(
            fig_count)

        ptext = '<font size=8>%s</font>' % pixLC_text
        Story.append(Paragraph(ptext, styles["Normal"]))

    # ------ Phase Folded LC ------

    if len(transit_list) > 1:

        # --------------------------------------------
        # Phase Folded
        # --------------------------------------------
        impf = Image(phasefold_name)

        impf._restrictSize(width * 0.35, width * 0.35)

        Story.append(impf)

        fig_count += 1
        Story.append(Spacer(1, 10))
        flux_aperture_text = "Fig {}. Phase folded lightcurve where the odd and the even transits are shown in different colours. Ensure that the odd and even transits have comparabel shapes and depths.".format(
            fig_count)

        ptext = '<font size=8>%s</font>' % flux_aperture_text
        Story.append(Paragraph(ptext, styles["Normal"]))

    # ------ BLS -------
    Story.append(PageBreak())  # always start a new page for this analysis
    # ------

    if bls == True:

        Story.append(Spacer(1, 12))
        blsim1 = Image(bls1)
        blsim2 = Image(bls2)

        blsim1._restrictSize(width * 0.6, width * 0.6)
        blsim2._restrictSize(width * 0.6, width * 0.6)

        bls_table = (Table([[blsim1, blsim2]],
                           colWidths=[width * 0.45],
                           rowHeights=[width * 0.6]))

        bls_table.setStyle(
            TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTRE'),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')]))

        Story.append(bls_table)

        fig_count += 1

        if FFI == False:

            bls1_text = "Fig {}. Box Least Square fitting (BLS) for whole lightcurve binned to 10 minutes. Top left panel: log liklihood periodogram. \
							The solid red line indicates the peak period and the dashed orange lines show the integer \
							harmonics of this period. Middle left panel: Full light curve, unbinned (orange) and binned to 10 minutes (black). \
							The peak period is highlighted by the solid red lines. Bottom left Panel: Phase folded light curve where the found transit-event is fit \
							with a simple box (red line). The pannels on the right show the same diagnostics, however the diagnostic \
							was run with the highest detected signal-to-noise transits, from the initial BLS search, removed. ".format(
                fig_count)

        else:
            bls1_text = "Fig {}. Box Least Square fitting (BLS) for whole lightcurve. Top left panel: log liklihood periodogram. \
							The solid blue line indicates the peak period and the dashed red lines show the integer \
							harmonics of this period. Middle left panel: Full light curve, unbinned LC (orange) . \
							The peak period is highlighted by the solid blue lines. Bottom left Panel: Phase folded light curve where the found transit-event is fit \
							with a simple box (blue line). The pannels on the right show the same diagnostics, however the diagnostic \
							was run with the highest detected signal-to-noise transits, from the initial BLS search, removed. ".format(
                fig_count)

        ptext = '<font size=8>%s</font>' % bls1_text
        Story.append(Paragraph(ptext, styles["Normal"]))

        # --------------------
        # ---- BLS TABLE -----

        data_bls = [
            ['Parameter', "bls1", "bls2"],
            [
                'period', "{:.3f}".format(bls_stats1[0]),
                "{:.3f}".format(bls_stats2[0])
            ],
            [
                't0', "{:.2f}".format(bls_stats1[1]),
                "{:.2f}".format(bls_stats2[1])
            ],
            [
                'depth', "{:.5f} ± {:.5f}".format(bls_stats1[2][0],
                                                  bls_stats1[2][1]),
                "{:.5f} ± {:.5f}".format(bls_stats2[2][0], bls_stats2[2][1])
            ],
            [
                'depth phased',
                "{:.5f} ± {:.5f}".format(bls_stats1[3][0], bls_stats1[3][1]),
                "{:.5f} ± {:.5f}".format(bls_stats2[3][0], bls_stats2[3][1])
            ],
            [
                'depth half', "{:.5f} ± {:.5f}".format(bls_stats1[4][0],
                                                       bls_stats1[4][1]),
                "{:.5f} ± {:.5f}".format(bls_stats2[4][0], bls_stats2[4][1])
            ],
            [
                'depth odd', "{:.5f} ± {:.5f}".format(bls_stats1[5][0],
                                                      bls_stats1[5][1]),
                "{:.5f} ± {:.5f}".format(bls_stats2[5][0], bls_stats2[5][1])
            ],
            [
                'depth even', "{:.5f} ± {:.5f}".format(bls_stats1[6][0],
                                                       bls_stats1[6][1]),
                "{:.5f} ± {:.5f}".format(bls_stats2[6][0], bls_stats2[6][1])
            ],
        ]

        table_bls = Table(data_bls)
        table_bls = Table(data_bls,
                          colWidths=width * 0.2,
                          style=[
                              ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black),
                              ('LINEABOVE', (0, 8), (-1, 8), 1, colors.black),
                              ('FONTSIZE', (0, 0), (-1, 7), 8),
                          ])

        # ------ ADD A LINE TO SEPERATE SECTIONS -------

        Story.append(Spacer(1, 20))
        line = MCLine(width * 0.77)
        Story.append(line)

        # ------

        Story.append(Spacer(1, 16))
        ptext = '<font size=10>BLS parameters</font>'
        Story.append(Paragraph(ptext, styles["Normal"]))
        Story.append(Spacer(1, 15))

        data_len = len(data_bls)

        for each in range(data_len):
            if each % 2 == 0:
                bg_color = colors.whitesmoke
            else:
                bg_color = colors.white

            table_bls.setStyle(
                TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)]))

        Story.append(table_bls)
        Story.append(Spacer(1, 15))

        table_count += 1
        Stellartable_text = "Table {}. Summary of the two BLS fits. Fit one is run with the whole lightcurve and fit two is run with the highest detected signal-to-noise transits removed.".format(
            table_count)
        ptext = '<font size=8>%s</font>' % Stellartable_text
        Story.append(Paragraph(ptext, styles["Normal"]))

        Story.append(PageBreak())
        # -----------

    if model == True:

        #Story.append(PageBreak()) # always start a new page for this analysis
        pyaneti_url = 'https://academic.oup.com/mnras/article/482/1/1017/5094600'

        pyaneti_link = '<link href="%s" color="blue">Pyaneti</link>' % pyaneti_url

        model_title = "Modeling"
        model_text = "The modeling of target TIC {} using the open source {} package.".format(
            tic, pyaneti_link)

        ptext = '<font size=11><b>%s</b></font>' % model_title
        Story.append(Paragraph(ptext, styles["centre"]))
        Story.append(Spacer(1, 10))
        ptext = '<font size=11>%s</font>' % model_text
        Story.append(Paragraph(ptext, styles["centre"]))
        Story.append(Spacer(1, 15))

        line = MCLine(width * 0.77)
        Story.append(line)

        # --------------------------------------------
        # Pyaneti Modeling results
        # --------------------------------------------

        Story.append(Spacer(1, 12))
        im_model = Image(model_name)

        im_model._restrictSize(width * 0.5, width * 0.5)

        Story.append(im_model)
        fig_count += 1

        model_text = "Fig {}. The phase folded lightcurve from the the Pyaneti modeling. The solid black line shows the best fit model. See Table 2 for model parameters.".format(
            fig_count)

        ptext = '<font size=8>%s</font>' % model_text
        Story.append(Paragraph(ptext, styles["Normal"]))

        # ---------------
        # pyaneti modeling table

        # ----------------------------------------------
        # print a table of the model/pyaneti parameters
        # ----------------------------------------------

        # this can only be done if the pyaneti model has been run
        # as this takes quite a while this might not always be the case.

        if os.path.exists("{}/{}/model_out/{}_parameters.csv".format(
                indir, tic, tic)):

            Story.append(Spacer(1, 12))
            line = MCLine(width * 0.77)
            Story.append(line)
            Story.append(Spacer(1, 12))

            ptext = '<font size=10>Candidate Model Parameters</font>'
            Story.append(Paragraph(ptext, styles["Normal"]))
            Story.append(Spacer(1, 8))

            manifest_table = pd.read_csv(
                '{}/{}/model_out/{}_parameters.csv'.format(indir, tic, tic))

            #manifest_table
            params = [
                'T0', 'P', 'e', 'w', 'b', 'a/R*', 'rp/R*', 'Rp', 'Tperi', 'i',
                'a', 'Insolation', 'rho*', 'g_p', 'Teq', 'T_tot', 'T_full'
            ]
            elements = []

            param_vals = []
            param_errs = []
            param_units = []

            for st in params:
                try:
                    s = (manifest_table[manifest_table['Var'] == st])
                    param_vals.append("{:.3f}".format(s['Val'].values[0]))
                    param_errs.append("+{:.4f}  -{:.4f}".format(
                        s['Pos'].values[0], s['Neg'].values[0]))
                    param_units.append("{}".format(s['Unit'].values[0]))
                except:
                    param_vals.append(-999)
                    param_errs.append(-999)
                    param_units.append(-999)

            data_params = [['Parameters', 'Value', 'Uncertainty', 'Unit']]
            for p, v, e, u in zip(params, param_vals, param_errs, param_units):
                data_params.append([p, v, e, u])

            table_model = Table(data_params)
            table_model = Table(data_params,
                                colWidths=width * 0.2,
                                style=[
                                    ('LINEABOVE', (0, 1), (-1, 1), 1,
                                     colors.black),
                                    ('LINEABOVE', (0, 8), (-1, 8), 1,
                                     colors.black),
                                    ('LINEABOVE', (0, len(params) + 1),
                                     (-1, len(params) + 1), 1, colors.black),
                                    ('FONTSIZE', (0, 0), (-1, len(params)), 8),
                                ])

            data_len = len(data_params)

            for each in range(data_len):
                if each % 2 == 0:
                    bg_color = colors.whitesmoke
                else:
                    bg_color = colors.white

                table_model.setStyle(
                    TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)
                                ]))

            Story.append(table_model)

            table_count += 1
            Story.append(Spacer(1, 10))
            Stellartable_text = "Table {}. The candidate paramaters from the Pyaneti modeling.".format(
                table_count)
            ptext = '<font size=8>%s</font>' % Stellartable_text
            Story.append(Paragraph(ptext, styles["Normal"]))

    doc.build(Story, onFirstPage=addPageNumber, onLaterPages=addPageNumber)
Example #31
0
unique_ids = set()

for arr in marks_data:
    if arr[0] not in unique_ids:
        unique_ids.add(arr[0])
        blueprint = Canvas("./pdfs/{}_{}_{}.pdf".format(
            arr[0], arr[1], arr[2]))
        blueprint.setTitle("Mark Sheet")
        blueprint.setFont("Helvetica-Bold", 16)
        #============================= Begin: Student Details =========================================
        blueprint.drawCentredString(4 * inch, 11 * inch,
                                    "Wisdom Tests and Math Challenge")
        # print(arr[7])
        image_path = "./Pics/{}.jpg".format(int(arr[0]))
        I = Image(image_path)
        I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth
        I.drawWidth = 1.25 * inch
        I.drawOn(blueprint, 6.5 * inch, 10 * inch)
        data = [
            [Paragraph("<b>Name Of Candidate</b>"), arr[1]],
            [Paragraph("<b>Grade </b>"), arr[3]],
            [Paragraph("<b>School Name</b>"), arr[5]],
            [Paragraph("<b>City Of Residence</b>"), arr[7]],
            [Paragraph("<b>Country Of Residence</b>"), arr[9]],
        ]
        t = Table(data)
        t.wrapOn(blueprint, 4 * inch, 10 * inch)
        t.drawOn(blueprint, 1 * inch, 8.7 * inch)
        temp_date = xlrd.xldate_as_tuple(arr[6], date_convert)
        birth_date = (datetime.date(temp_date[0], temp_date[1],
                                    temp_date[2])).strftime('%Y-%m-%d')
Example #32
0
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, inch
from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Table
from reportlab.lib.styles import getSampleStyleSheet

doc = SimpleDocTemplate("complex_cell_values.pdf", pagesize=letter)
# container for the 'Flowable' objects
elements = []

styleSheet = getSampleStyleSheet()

I = Image('python_logo.png')
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),
    def build_index_Tafonomia(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']
        styNormal.fontSize = 8
        styBackground = ParagraphStyle('background',
                                       parent=styNormal,
                                       backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        ###################### ELENCO SCHEDE TAFONOMICHE ###########

        lst = []
        lst.append(logo)

        lst.append(
            Paragraph(
                "<b>ELENCO SCHEDE TAFONOMICHE</b><br/><b>Scavo: %s,  Data: %s</b>"
                % (sito, data), styH1))

        table_data = []
        for i in range(len(records)):
            exp_index = Tafonomia_index_pdf_sheet(records[i])
            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [50, 80, 80, 80, 100, 60, 50, 60, 60, 60, 60, 150]

        table_data_formatted = Table(table_data, colWidths, style=styles)
        table_data_formatted.hAlign = "LEFT"

        lst.append(table_data_formatted)
        #lst.append(Spacer(0,2))

        filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_tafonomia.pdf')
        f = open(filename, "wb")

        doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0)
        doc.build(lst, canvasmaker=NumberedCanvas_TAFONOMIAindex)

        f.close()

        ###################### ELENCO SCHEDE STRUTTURE TAFONOMICHE ###########

        lst = []
        lst.append(logo)

        lst.append(
            Paragraph(
                "<b>ELENCO SCHEDE STRUTTURE TAFONOMICHE</b><br/><b>Scavo: %s,  Data: %s</b>"
                % (sito, data), styH1))

        table_data = []
        for i in range(len(records)):
            exp_index = Tafonomia_index_II_pdf_sheet(records[i])
            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [50, 50, 40, 100, 60, 50, 50, 60, 60, 60, 80]

        table_data_formatted = Table(table_data, colWidths, style=styles)
        table_data_formatted.hAlign = "LEFT"

        lst.append(table_data_formatted)
        #lst.append(Spacer(0,2))

        filename = ('%s%s%s') % (self.PDF_path, os.sep,
                                 'elenco_strutture_tafonomia.pdf')
        f = open(filename, "wb")

        doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0)
        doc.build(lst, canvasmaker=NumberedCanvas_TAFONOMIAindex)

        f.close()
    def create_sheet(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  #LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  #Justified

        #format labels

        #0 row
        intestazione = Paragraph(
            "<b>SCHEDA TAFONOMICA<br/>" + str(self.datestrfdate()) + "</b>",
            styNormal)

        #intestazione2 = Paragraph("<b>pyArchInit</b><br/>pyarchinit", styNormal)

        #intestazione2  = Paragraph("<b>Ditta esecutrice</b><br/>", styNormal)
        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)

        ##		if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        #1 row
        sito = Paragraph("<b>Sito</b><br/>" + str(self.sito), styNormal)
        sigla_struttura = Paragraph(
            "<b>Sigla struttura</b><br/>" + str(self.sigla_struttura) +
            str(self.nr_struttura), styNormal)
        nr_individuo = Paragraph(
            "<b>Nr. Individuo</b><br/>" + str(self.nr_individuo), styNormal)
        nr_scheda = Paragraph(
            "<b>Nr. Scheda</b><br/>" + str(self.nr_scheda_taf), styNormal)

        #2 row
        periodizzazione = Paragraph(
            "<b>PERIODIZZAZIONE DEL RITO DI SEPOLTURA</b><br/>", styNormal)

        #3 row
        if str(self.periodo_iniziale) == "None":
            periodo_iniziale = Paragraph("<b>Periodo iniziale</b><br/>",
                                         styNormal)
        else:
            periodo_iniziale = Paragraph(
                "<b>Periodo iniziale</b><br/>" + str(self.periodo_iniziale),
                styNormal)

        if str(self.fase_iniziale) == "None":
            fase_iniziale = Paragraph("<b>Fase iniziale</b><br/>", styNormal)
        else:
            fase_iniziale = Paragraph(
                "<b>Fase iniziale</b><br/>" + str(self.fase_iniziale),
                styNormal)

        if str(self.periodo_finale) == "None":
            periodo_finale = Paragraph("<b>Periodo finale</b><br/>", styNormal)
        else:
            periodo_finale = Paragraph(
                "<b>Periodo finale</b><br/>" + str(self.periodo_finale),
                styNormal)

        if str(self.fase_finale) == "None":
            fase_finale = Paragraph("<b>Fase finale</b><br/>", styNormal)
        else:
            fase_finale = Paragraph(
                "<b>Fase finale</b><br/>" + str(self.fase_finale), styNormal)

        #4 row
        if str(self.datazione_estesa) == "None":
            datazione_estesa = Paragraph("<b>Datazione estesa</b><br/>",
                                         styNormal)
        else:
            datazione_estesa = Paragraph(
                "<b>Datazione estesa</b><br/>" + self.datazione_estesa,
                styNormal)

        #5 row
        elementi_strutturali = Paragraph("<b>ELEMENTI STRUTTURALI</b></b>",
                                         styNormal)

        #6row
        tipo_contenitore_resti = Paragraph(
            "<b>Tipo contenitore resti</b><br/>" + self.tipo_contenitore_resti,
            styNormal)
        tipo_copertura = Paragraph(
            "<b>Tipo copertura</b><br/>" + self.copertura_tipo, styNormal)
        segnacoli = Paragraph("<b>Segnacoli</b><br/>" + self.segnacoli,
                              styNormal)
        canale_libatorio = Paragraph(
            "<b>Canale libatorio</b><br/>" + self.canale_libatorio_si_no,
            styNormal)

        #7 row
        dati_deposizionali = Paragraph("<b>DATI DEPOSIZIONALI INUMATO<b></b>",
                                       styNormal)

        #8 row
        rito = Paragraph("<b>Rito</b><br/>" + self.rito, styNormal)
        orientamento_asse = Paragraph(
            "<b>Orientamento asse</b><br/>" + str(self.orientamento_asse),
            styNormal)
        if str(self.orientamento_azimut) == "None":
            orientamento_azimut = Paragraph("<b>Azimut</b><br/>", styNormal)
        else:
            orientamento_azimut_conv = self.PU.conversione_numeri(
                self.orientamento_azimut)
            orientamento_azimut = Paragraph(
                "<b>Azimut</b><br/>" + orientamento_azimut_conv + "°",
                styNormal)
        posizione_cranio = Paragraph(
            "<b>Posizione cranio</b><br/>" + str(self.posizione_cranio),
            styNormal)

        #9 row
        posizione_scheletro = Paragraph(
            "<b>Posizione scheletro</b><br/>" + str(self.posizione_scheletro),
            styNormal)
        if str(self.lunghezza_scheletro) == "None":
            lunghezza_scheletro = Paragraph("<b>Lunghezza scheletro</b><br/>",
                                            styNormal)
        else:
            lunghezza_scheletro_conv = self.PU.conversione_numeri(
                self.lunghezza_scheletro)
            lunghezza_scheletro = Paragraph(
                "<b>Lunghezza scheletro</b><br/>" + lunghezza_scheletro_conv +
                " m", styNormal)
        posizione_arti_superiori = Paragraph(
            "<b>Posizione arti superiori</b><br/>" +
            str(self.posizione_arti_superiori), styNormal)
        posizione_arti_inferiori = Paragraph(
            "<b>Posizione arti inferiori</b><br/>" +
            str(self.posizione_arti_inferiori), styNormal)

        #10 row
        dati_postdeposizionali = Paragraph("<b>DATI POSTDEPOSIZIONALI<b></b>",
                                           styNormal)

        #11 row
        stato_conservazione = Paragraph(
            "<b>Stato di conservazione</b><br/>" +
            str(self.stato_di_conservazione), styNormal)
        disturbato = Paragraph("<b>Disturbato</b><br/>" + str(self.segnacoli),
                               styNormal)
        completo = Paragraph(
            "<b>Completo</b><br/>" + str(self.canale_libatorio_si_no),
            styNormal)
        in_connessione = Paragraph(
            "<b>In connessione</b><br/>" + str(self.oggetti_rinvenuti_esterno),
            styNormal)

        #12 row
        caratteristiche_tafonomiche = ''
        caratteristiche_list = eval(self.caratteristiche)
        if len(caratteristiche_list) > 0:
            for i in caratteristiche_list:
                if caratteristiche_tafonomiche == '':
                    caratteristiche_tafonomiche = (
                        "Tipo caratteristica: %s, posizione: %s") % (str(
                            i[0]), str(i[1]))
                else:
                    caratteristiche_tafonomiche += (
                        "<br/>Tipo caratteristica: %s, posizione: %s") % (str(
                            i[0]), str(i[1]))

        caratteristiche_tafonomiche_txt = Paragraph(
            "<b>CARATTERISTICHE TAFONOMICHE</b><br/>" +
            caratteristiche_tafonomiche, styNormal)

        #13 row
        descrizione = ''
        try:
            descrizione = Paragraph(
                "<b>Descrizione</b><br/>" + self.descrizione_taf,
                styDescrizione)
        except:
            pass

        interpretazione = ''
        try:
            interpretazione = Paragraph(
                "<b>Interpretazione</b><br/>" + self.interpretazione_taf,
                styDescrizione)
        except:
            pass

        #14 row
        corredo = Paragraph("<b>CORREDO</b></b>", styNormal)

        #15 row
        corredo_presente = Paragraph(
            "<b>Presenza</b><br/>" + self.corredo_presenza, styDescrizione)

        #16 row
        corredo_descrizione = Paragraph(
            "<b>Descrizione</b><br/>" + self.corredo_descrizione,
            styDescrizione)

        #17 row
        corredo_tipo = ''
        if eval(self.corredo_tipo) > 0:
            for i in eval(self.corredo_tipo):
                if corredo_tipo == '':
                    try:
                        corredo_tipo += (
                            "Nr. reperto %s, tipo corredo: %s, descrizione: %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]))
                    except:
                        pass
                else:
                    try:
                        corredo_tipo += (
                            "<br/>Nr. reperto %s, tipo corredo: %s, descrizione: %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]))
                    except:
                        pass

        corredo_tipo_txt = Paragraph(
            "<b>Singoli oggetti di corredo</b><br/>" + corredo_tipo, styNormal)

        #18 row
        misure_tafonomia = ''
        if eval(self.misure_tafonomia) > 0:
            for i in eval(self.misure_tafonomia):
                if misure_tafonomia == '':
                    try:
                        misure_tafonomia += ("%s: %s %s") % (str(
                            i[0]), str(i[2]), str(i[1]))
                    except:
                        pass
                else:
                    try:
                        misure_tafonomia += ("<br/>%s: %s %s") % (str(
                            i[0]), str(i[2]), str(i[1]))
                    except:
                        pass

        misure_tafonomia_txt = Paragraph(
            "<b>Misurazioni</b><br/>" + misure_tafonomia, styNormal)

        #19 row
        quote_tafonomia = Paragraph("<b>QUOTE INDIVIDUO E STRUTTURA</b><br/>",
                                    styNormal)

        #20 row
        quota_min_ind = Paragraph(
            "<b>Quota min individuo</b><br/>" + str(self.quota_min_ind),
            styNormal)
        quota_max_ind = Paragraph(
            "<b>Quota max individuo</b><br/>" + str(self.quota_max_ind),
            styNormal)
        quota_min_strutt = Paragraph(
            "<b>Quota min struttura</b><br/>" + str(self.quota_min_strutt),
            styNormal)
        quota_max_strutt = Paragraph(
            "<b>Quota max struttura</b><br/>" + str(self.quota_max_strutt),
            styNormal)

        #schema
        cell_schema = [  #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                intestazione, '01', '02', '03', '04', '05', '06', logo, '08',
                '09'
            ],  #0 row  ok
            [sito, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  #1 row ok
            [
                sigla_struttura, '01', '02', '03', '04', nr_individuo, '06',
                '07', nr_scheda, '09'
            ],  #1 row ok
            [
                periodizzazione, '01', '02', '03', '04', '07', '06', '07',
                '08', '09'
            ],  #2 row ok
            [
                periodo_iniziale, '01', '02', fase_iniziale, '04',
                periodo_finale, '06', fase_finale, '08', '09'
            ],  #3 row ok
            [
                datazione_estesa, '01', '02', '03', '04', '07', '06', '07',
                '08', '09'
            ],  #4 row ok
            [
                elementi_strutturali, '01', '02', '03', '04', '07', '06', '07',
                '08', '09'
            ],  #5 row ok
            [
                tipo_contenitore_resti, '01', '02', tipo_copertura, '04',
                segnacoli, '06', canale_libatorio, '08'
            ],  #6 row ok
            [
                dati_deposizionali, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #7 row ok
            [
                rito, '01', '02', orientamento_asse, '04', orientamento_azimut,
                '06', posizione_cranio, '08', '09'
            ],  #8 row ok
            [
                posizione_scheletro, '01', lunghezza_scheletro, '03',
                posizione_arti_superiori, '05', '06', posizione_arti_inferiori,
                '08', '09'
            ],  #9 row ok
            [
                dati_postdeposizionali, '01', '02', '03', '04', '05', '06',
                '07', '08', '09'
            ],  #10 row ok
            [
                stato_conservazione, '01', '02', disturbato, '04', completo,
                '06', in_connessione, '08'
            ],  #11 row ok
            [
                caratteristiche_tafonomiche_txt, '01', '02', '03', '04', '05',
                '06', '07', '08', '09'
            ],  #12 row ok
            [
                descrizione, '01', '02', '03', '04', interpretazione, '06',
                '07', '08', '09'
            ],  #13 row ok
            [corredo, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  #14 row ok
            [
                corredo_presente, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #15 ow
            [
                corredo_descrizione, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #16 row
            [
                corredo_tipo_txt, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #17 row
            [
                misure_tafonomia_txt, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #18 row
            [
                quote_tafonomia, '01', '02', '03', '04', '07', '06', '07',
                '08', '09'
            ],  #19 row ok
            [
                quota_min_ind, '01', '02', quota_max_ind, '04',
                quota_min_strutt, '06', quota_max_strutt, '08', '09'
            ]  #20 row ok
        ]

        #table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            #0 row
            ('SPAN', (0, 0), (6, 0)),  #intestazione
            ('SPAN', (7, 0), (9, 0)),  #intestazione

            #1 row
            ('SPAN', (0, 1), (9, 1)),  #sito

            #2
            ('SPAN', (0, 2), (4, 2)),  #dati identificativi
            ('SPAN', (5, 2), (7, 2)),  #dati identificativi
            ('SPAN', (8, 2), (9, 2)),  #dati identificativi

            #2 row
            ('SPAN', (0, 3), (9, 3)),  #Periodizzazione

            #3 row
            ('SPAN', (0, 4), (2, 4)),  #
            ('SPAN', (3, 4), (4, 4)),  #
            ('SPAN', (5, 4), (6, 4)),  #
            ('SPAN', (7, 4), (9, 4)),  #

            #4 row
            ('SPAN', (0, 5), (9, 5)),  #datazione estesa
            ##################################
            #5 row
            ('SPAN', (0, 6), (9, 6)),  #Elementi strutturali

            #6 row
            ('SPAN', (0, 7), (2, 7)),  #
            ('SPAN', (3, 7), (4, 7)),  #
            ('SPAN', (5, 7), (6, 7)),  #
            ('SPAN', (7, 7), (9, 7)),  #

            #7 row
            ('SPAN', (0, 8), (9, 8)),  #

            #8 row
            ('SPAN', (0, 9), (2, 9)),  #
            ('SPAN', (3, 9), (4, 9)),  #
            ('SPAN', (5, 9), (6, 9)),  #
            ('SPAN', (7, 9), (9, 9)),  #

            #9 row
            ('SPAN', (0, 10), (1, 10)),  #
            ('SPAN', (2, 10), (3, 10)),  #
            ('SPAN', (4, 10), (6, 10)),  #
            ('SPAN', (7, 10), (9, 10)),  #

            #10 row
            ('SPAN', (0, 11), (9, 11)),  #

            #11 row
            ('SPAN', (0, 12), (2, 12)),  #
            ('SPAN', (3, 12), (4, 12)),  #
            ('SPAN', (5, 12), (6, 12)),  #
            ('SPAN', (7, 12), (9, 12)),  #

            #12 row
            ('SPAN', (0, 13), (9, 13)),  #

            #13 row
            ('SPAN', (0, 14), (4, 14)),  #
            ('SPAN', (5, 14), (9, 14)),  #

            #14 row
            ('SPAN', (0, 15), (9, 15)),  #

            #15 row
            ('SPAN', (0, 16), (9, 16)),  #

            #16 row
            ('SPAN', (0, 17), (9, 17)),

            #17 row
            ('SPAN', (0, 18), (9, 18)),  #

            #18 row
            ('SPAN', (0, 19), (9, 19)),  #
            ('SPAN', (0, 20), (9, 20)),  #Periodizzazione

            #3 row
            ('SPAN', (0, 21), (2, 21)),  #
            ('SPAN', (3, 21), (4, 21)),  #
            ('SPAN', (5, 21), (6, 21)),  #
            ('SPAN', (7, 21), (9, 21)),  #
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

        t = Table(cell_schema,
                  colWidths=50,
                  rowHeights=None,
                  style=table_style)

        return t
Example #35
0
    def create_sheet(self):
        styleSheet = getSampleStyleSheet()

        styleSheet.add(ParagraphStyle(name='Cassa Label'))
        styleSheet.add(ParagraphStyle(name='Sito Label'))

        styCassaLabel = styleSheet['Cassa Label']
        styCassaLabel.spaceBefore = 0
        styCassaLabel.spaceAfter = 0
        styCassaLabel.alignment = 2  #RIGHT
        styCassaLabel.leading = 25
        styCassaLabel.fontSize = 30

        stySitoLabel = styleSheet['Sito Label']
        stySitoLabel.spaceBefore = 0
        stySitoLabel.spaceAfter = 0
        stySitoLabel.alignment = 0  #LEFT
        stySitoLabel.leading = 25
        stySitoLabel.fontSize = 18
        stySitoLabel.fontStyle = 'bold'

        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 10
        styNormal.spaceAfter = 10
        styNormal.alignment = 0  #LEFT
        styNormal.fontSize = 14
        styNormal.leading = 15

        #format labels
        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)

        ##		if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        num_cassa = Paragraph("<b>N. Cassa </b>" + str(self.cassa),
                              styCassaLabel)
        sito = Paragraph("<b>Sito: </b>" + str(self.sito), stySitoLabel)

        if self.elenco_inv_tip_rep == None:
            elenco_inv_tip_rep = Paragraph(
                "<b>Elenco N. Inv. / Tipo campione</b><br/>", styNormal)
        else:
            elenco_inv_tip_rep = Paragraph(
                "<b>Elenco N. Inv. / Tipo campione</b><br/>" +
                str(self.elenco_inv_tip_rep), styNormal)

        if self.elenco_us == None:
            elenco_us = Paragraph("<b>Elenco US/(Struttura)</b>", styNormal)
        else:
            elenco_us = Paragraph(
                "<b>Elenco US/(Struttura)</b><br/>" + str(self.elenco_us),
                styNormal)

        #luogo_conservazione = Paragraph("<b>Luogo di conservazione</b><br/>" + str(self.luogo_conservazione),styNormal)

        #schema
        cell_schema = [  #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [logo, '01', '02', '03', '04', '05', num_cassa, '07', '08', '09'],
            [sito, '01', '02', '03', '04', '05', '06', '07', '08', '09'],
            [elenco_us, '01', '02', '03', '04', '05', '06', '07', '08', '09'],
            [
                elenco_inv_tip_rep, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ]
        ]

        #table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0, colors.white),  #,0.0,colors.black
            #0 row
            ('SPAN', (0, 0), (5, 0)),  #elenco US
            ('SPAN', (6, 0), (9, 0)),  #elenco US
            ('HALIGN', (0, 0), (9, 0), 'LEFT'),
            ('VALIGN', (6, 0), (9, 0), 'TOP'),
            ('HALIGN', (6, 0), (9, 0), 'RIGHT'),
            ('SPAN', (0, 1), (9, 1)),  #elenco US
            ('HALIGN', (0, 1), (9, 1), 'LEFT'),
            ('SPAN', (0, 2), (9, 2)),  #intestazione
            ('VALIGN', (0, 2), (9, 2), 'TOP'),
            #1 row
            ('SPAN', (0, 3), (9, 3)),  #elenco US
            ('VALIGN', (0, 3), (9, 3), 'TOP')
        ]

        colWidths = None
        rowHeights = None
        #colWidths=[80,80,80, 80,80, 80,80,80,80, 80]
        t = Table(cell_schema, colWidths, rowHeights, style=table_style)

        return t
Example #36
0
    def create_sheet(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  #LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  #Justified

        #format labels

        #0 row
        intestazione = Paragraph(
            "<b>SCHEDA CAMPIONI<br/>" + str(self.datestrfdate()) + "</b>",
            styNormal)

        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)

        ##		if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        #1 row
        sito = Paragraph("<b>Sito</b><br/>" + str(self.sito), styNormal)
        tipo_campione = Paragraph(
            "<b>Tipo Campione</b><br/>" + str(self.tipo_campione), styNormal)
        nr_campione = Paragraph(
            "<b>Nr. Campione</b><br/>" + str(self.numero_campione), styNormal)

        #2 row
        area = Paragraph("<b>Area</b><br/>" + str(self.area), styNormal)
        us = Paragraph("<b>US</b><br/>" + str(self.us), styNormal)
        nr_inventario = Paragraph(
            "<b>Nr. Inventario</b><br/>" + str(self.numero_inventario),
            styNormal)

        #4 row
        descrizione = Paragraph(
            "<b>Descrizione</b><br/>" + str(self.descrizione), styDescrizione)

        #4 row
        luogo_conservazione = Paragraph(
            "<b>Luogo conservazione</b><br/>" + str(self.luogo_conservazione),
            styNormal)
        nr_cassa = Paragraph("<b>Nr. Cassa</b><br/>" + str(self.nr_cassa),
                             styNormal)

        #schema
        cell_schema = [  #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                intestazione, '01', '02', '03', '04', '05', '06', logo, '08',
                '09'
            ],  #0 row ok
            [
                sito, '01', '02', '03', '04', '05', '06', '07', nr_campione,
                '09'
            ],  #1 row ok
            [
                tipo_campione, '01', '02', '03', '04', '05', '06', '07', '08'
                '09'
            ],  #2 row ok
            [
                area, '01', '02', us, '04', '05', nr_inventario, '07', '08',
                '09'
            ],  #3 row ok
            [
                descrizione, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  #4 row ok
            [
                nr_cassa, '01', '02', '03', '04', '05', luogo_conservazione,
                '07', '08', '09'
            ]  #5 row ok
        ]

        #table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            #0 row
            ('SPAN', (0, 0), (6, 0)),  #intestazione
            ('SPAN', (7, 0), (9, 0)),  #intestazione

            #1 row
            ('SPAN', (0, 1), (7, 1)),  #sito
            ('SPAN', (8, 1), (9, 1)),  #dnr campione

            #2 row
            ('SPAN', (0, 2), (9, 2)),  #sito
            ('HALIGN', (0, 2), (9, 2), 'CENTER'),

            #3 row
            ('SPAN', (0, 3), (2, 3)),  #area
            ('SPAN', (3, 3), (5, 3)),  #us
            ('SPAN', (6, 3), (9, 3)),  #inventario
            ('VALIGN', (0, 3), (9, 3), 'TOP'),

            #3 row
            ('SPAN', (0, 4), (9, 4)),  #descrizione

            #5 row
            ('SPAN', (0, 5), (5, 5)),  #elementi_reperto	
            ('SPAN', (6, 5), (9, 5)),  #elementi_reperto
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

        t = Table(cell_schema,
                  colWidths=50,
                  rowHeights=None,
                  style=table_style)

        return t
Example #37
0
def test(args):
    """
    Run Litmus ChaosEngine Experiments inside the demo environment.
    Each experiment is defined under its own yaml file under the /litmus directory. You can run
    a specific experiment by specifying a test name that matches one of the yaml file names in the directory
    but by default all '*' experiments will be run with 20 minute wait period between each experiment
    to ensure that it doesn't cluster the incidents together into one incident
    """
    startTimeStamp = time.monotonic()
    #for GKE platform
    if (f"{args.platform}" == "GKE" and (f"{args.type}" == "all")):
        experiments = sorted(os.listdir('./litmus'))

    elif (f"{args.platform}" == "GKE" and (f"{args.type}" == "pod")):
        experiments = ["container-kill.yaml","disk-fill","pod-cpu-hog","pod-delete","pod-memory-hog","pod-network-corruption","pod-network-latency","pod-network-loss"]

    elif (f"{args.platform}" == "GKE" and (f"{args.type}" == "node")):
        kind_supported = ["node-cpu-hog","node-memory-hog"]

    #for kind platform
    if ((f"{args.platform}" == "kind") and (f"{args.type}" == "all")):
        kind_supported = ["pod-delete","container-kill","node-cpu-hog","node-memory-hog"]
        experiments=[s + ".yaml" for s in kind_supported]

    elif ((f"{args.platform}" == "kind") and (f"{args.type}" == "pod")):
        experiments = ["node-cpu-hog.yaml","node-memory-hog.yaml"]

    elif ((f"{args.platform}" == "kind") and (f"{args.type}" == "node")):
        experiments = ["node-cpu-hog.yaml","node-memory-hog.yaml"]

    # for EKS platform
    if (f"{args.platform}" == "EKS" and (f"{args.type}" == "all")):
        experiments = sorted(os.listdir('./litmus'))

    elif (f"{args.platform}" == "EKS" and (f"{args.type}" == "pod")):
        experiments = ["container-kill.yaml", "disk-fill", "pod-cpu-hog", "pod-delete", "pod-memory-hog",
                       "pod-network-corruption", "pod-network-latency", "pod-network-loss"]

    elif (f"{args.platform}" == "EKS" and (f"{args.type}" == "node")):
        kind_supported = ["node-cpu-hog", "node-memory-hog"]

    experiment_results = []

    if args.test == '*':
        # Run all experiments in /litmus directory with wait time between them
        print_color(f"Running all Litmus ChaosEngine Experiments with {args.wait} mins wait time between each one...")
        lstindex = len(experiments)
        for experiment_file in experiments:
            result = run_experiment(experiment_file.replace('.yaml', ''))
            experiment_results.append(result)
            print_color(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Waiting {args.wait} mins before running next experiment...", bcolors.WARNING)
            lstindex -= 1
            if lstindex != 0:
                time.sleep(args.wait * 60)
    else:
        # Check experiment exists
        experiment_file = args.test + ".yaml"
        if experiment_file in experiments:
            result = run_experiment(args.test)
            experiment_results.append(result)
        else:
            print_color(f"ERROR: {experiment_file} not found in ./litmus directory. Please check the name and try again.", bcolors.FAIL)
            sys.exit(2)

    # Print out experiment result summary
    print_color("***************************************************************************************************", bcolors.OKBLUE)
    print_color("* Experiments Result Summary", bcolors.OKBLUE)
    print_color("***************************************************************************************************\n", bcolors.OKBLUE)
    headers = ["#", "Start Time", "Experiment", "Status"]
    row_format = "{:>25}" * (len(headers) + 1)
    print_color(row_format.format("", *headers), bcolors.OKBLUE)
    i = 1
    for result in experiment_results:
        if result.status == "Pass":
            print_color(row_format.format("", str(i), result.startTime.strftime('%Y-%m-%d %H:%M:%S'), result.name,"    "+ result.status + " 'carts-db' Service is up and Running after chaos"), bcolors.OKBLUE)
            i += 1
        else:
            print_color(row_format.format("", str(i), result.startTime.strftime('%Y-%m-%d %H:%M:%S'), result.name, result.status), bcolors.OKBLUE)
            i += 1
    print("\n")
    currentTimeStamp= time.monotonic()
    diffTimeStamp = currentTimeStamp - startTimeStamp
    ty_res = time.gmtime(diffTimeStamp)
    totalTime = time.strftime("%H:%M:%S",ty_res)

    if (f"{args.report}" == "yes"):

        print_color("Creating PDF Report", bcolors.OKBLUE)

        fileName = 'chaos-report.pdf'
        pdf = SimpleDocTemplate(fileName,pagesize=LETTER)
        styles = getSampleStyleSheet()
        data = [None]
        data[0] = ["S.No.", "Start Time", "Experiment", "Status"]

        i =1
        expPassed = 0
        expFailed = 0
        for result in experiment_results:
            if result.status == "Pass":
                data.append([str(i), result.startTime.strftime('%Y-%m-%d %H:%M:%S'), result.name,"    "+ result.status + " 'carts-db' Service is up and Running after chaos"])
                i += 1
                expPassed +=1
            else:
                data.append([str(i), result.startTime.strftime('%Y-%m-%d %H:%M:%S'), result.name,result.status])
                i += 1
                expFailed +=1

        table = Table(data)

        picture = Image("images/litmus.png")
        picture.drawWidth = 100
        picture.drawHeight = 100
        picTable = Table([[picture]],100,100)

        elems = []

        # Adding logo
        elems.append(picTable)
        # Adding title
        text = "LitmusChaos Report <br/> <br/>Experiments Result Summary"
        para = Paragraph(text, styles['Title'])
        elems.append(para)

        ## Adding result table
        elems.append(table)

        style = TableStyle([
            ('BACKGROUND',(0,0),(3,0), colors.green),
            ('TEXTCOLOR',(0,0),(-1,0), colors.whitesmoke),
            ('ALIGN',(0,0),(-1,-1), 'CENTER'),
            ('FONTNAME',(0,0),(-1,0), 'Courier'),
            ('FONTSIZE',(0,0),(-1,0), 14),
            ('BOTTOMPADDING',(0,0),(-1,0), 12),
            ('BACKGROUND',(0,1),(-1,-1), colors.beige),
        ])

        ts = TableStyle([
            ('BOX',(0,0),(-1,-1),1,colors.black)
        ])

        ## Adding table style
        table.setStyle(style)
        table.setStyle(ts)

        para1 = Paragraph("The total number of passed experiments: %s " % str(expPassed), styles['Heading3'])
        elems.append(para1)
        para2 = Paragraph("The total number of failed experiments: %s " % str(expFailed), styles['Heading3'])
        elems.append(para2)
        para3 = Paragraph("The total experiment execution time: %s (HH:MM:SS)" % str(totalTime), styles['Heading3'])
        elems.append(para3)

        pdf.build(elems)
        print_color("PDF Report Created Successfully ", bcolors.OKBLUE)
	def create_sheet(self):
		styleSheet = getSampleStyleSheet()
		styNormal = styleSheet['Normal']
		styNormal.spaceBefore = 20
		styNormal.spaceAfter = 20
		styNormal.alignment = 0 #LEFT

		styleSheet = getSampleStyleSheet()
		styDescrizione = styleSheet['Normal']
		styDescrizione.spaceBefore = 20
		styDescrizione.spaceAfter = 20
		styDescrizione.alignment = 4 #Justified


		#format labels

		#0 row
		intestazione = Paragraph("<b>SCHEDA PERIODIZZAZIONE<br/>" + str(self.datestrfdate()) + "</b>", styNormal)

		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)

		##		if test_image.drawWidth < 800:

		logo.drawHeight = 1.5*inch*logo.drawHeight / logo.drawWidth
		logo.drawWidth = 1.5*inch


		#intestazione2 = Paragraph("<b>pyArchInit</b><br/>www.pyarchinit.blogspot.com", styNormal)

		#1 row
		sito = Paragraph("<b>Sito</b><br/>"  + str(self.sito), styNormal)
		periodo = Paragraph("<b>Periodo</b><br/>"  + str(self.periodo), styNormal)
		fase = Paragraph("<b>Fase</b><br/>"  + str(self.fase), styNormal)

		#2 row
		cronologia = Paragraph("<b>CRONOLOGIA</b></b>",styNormal)
		
		#3 row
		cronologia_iniziale = Paragraph("<b>Cronologia iniziale</b><br/>"  + str(self.cron_iniziale), styNormal)
		cronologia_finale = Paragraph("<b>Cronologia finale</b><br/>"  + str(self.cron_finale), styNormal)
		datazione_ext = Paragraph("<b>Cronologia testuale</b><br/>"  + str(self.datazione_estesa), styNormal)

		#4 row
		descrizione = ''
		try:
			descrizione = Paragraph("<b>Descrizione</b><br/>" + str(self.descrizione), styDescrizione)
		except:
			pass

		#schema
		cell_schema =  [ #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
						[intestazione, '01', '02', '03', '04','05', '06', logo, '08', '09'], #0 row ok
						[sito, '01', '02', '03', '04', periodo, '06', '07', fase, '09'], #1 row ok
						[cronologia, '01', '02', '03', '04', '05', '06', '07', '08', '09'], #2 row ok
						[cronologia_iniziale, '01', cronologia_finale, '03', datazione_ext,'05', '06', '07', '08', '09'], #3 row
						[descrizione, '01','02', '03', '04', '05', '06', '07', '08', '09']]#4row ok

		#table style
		table_style=[
					('GRID',(0,0),(-1,-1),0.5,colors.black),
					#0 row
					('SPAN', (0,0),(6,0)),  #intestazione
					('SPAN', (7,0),(9,0)),  #intestazione

					#1 row
					('SPAN', (0,1),(4,1)),  #Sito
					('SPAN', (5,1),(7,1)),  #periodo
					('SPAN', (8,1),(9,1)),  #fase

					#2 row
					('SPAN', (0,2),(9,2)),  #intestazione cronologia

					#3 row
					('SPAN', (0,3),(1,3)),  #cron iniziale
					('SPAN', (2,3),(3,3)),  #cron finale
					('SPAN', (4,3),(9,3)),  #datazione estesa
					
					#4
					('SPAN', (0,4),(9,4)),  #datazione estesa
					('VALIGN',(0,4),(9,4),'TOP'), 
					#('VALIGN',(5,3),(5,3),'TOP'), 

					('VALIGN',(0,0),(-1,-1),'TOP')

					]

		t=Table(cell_schema, colWidths=50, rowHeights=None,style= table_style)

		return t
Example #39
0
 def create_sheet(self):
     styleSheet = getSampleStyleSheet()
     stylogo = styleSheet['Normal']
     stylogo.spaceBefore = 20
     stylogo.spaceAfter = 20
     stylogo.alignment = 1  # LEFT
     styleSheet = getSampleStyleSheet()
     styInt = styleSheet['Normal']
     styInt.spaceBefore = 20
     styInt.spaceAfter = 20
     styInt.fontSize = 8
     styInt.alignment = 1  # LEFT
     styleSheet = getSampleStyleSheet()
     styNormal = styleSheet['Normal']
     styNormal.spaceBefore = 20
     styNormal.spaceAfter = 20
     styNormal.fontSize = 6
     styNormal.alignment = 0  # LEFT
     styleSheet = getSampleStyleSheet()
     styDescrizione = styleSheet['Normal']
     styDescrizione.spaceBefore = 20
     styDescrizione.spaceAfter = 20
     styDescrizione.fontSize = 6
     styDescrizione.alignment = 4  # Justified
     styleSheet = getSampleStyleSheet()
     styUnitaTipo = styleSheet['Normal']
     styUnitaTipo.spaceBefore = 20
     styUnitaTipo.spaceAfter = 20
     styUnitaTipo.fontSize = 14
     styUnitaTipo.alignment = 1  # CENTER
     styleSheet = getSampleStyleSheet()
     styTitoloComponenti = styleSheet['Normal']
     styTitoloComponenti.spaceBefore = 20
     styTitoloComponenti.spaceAfter = 20
     styTitoloComponenti.fontSize = 6
     styTitoloComponenti.alignment = 1  # CENTER
     intestazione = Paragraph(
         "<b>Archaeological Underwater Survey - POTTERY FORM<br/>" + "</b>",
         styInt)
     home = os.environ['HFF_HOME']
     home_DB_path = '{}{}{}'.format(home, os.sep, 'HFF_DB_folder')
     logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.png')
     logo = Image(logo_path)
     ##      if test_image.drawWidth < 800:
     logo.drawHeight = 0.5 * inch * logo.drawHeight / logo.drawWidth
     logo.drawWidth = 0.5 * inch
     logo_path2 = '{}{}{}'.format(home_DB_path, os.sep, 'logo2.png')
     logo2 = Image(logo_path2)
     ##      if test_image.drawWidth < 800:
     logo2.drawHeight = 0.5 * inch * logo2.drawHeight / logo2.drawWidth
     logo2.drawWidth = 0.5 * inch
     #1 row
     divelog_id = Paragraph("<b>Dive ID</b><br/>" + str(self.divelog_id),
                            styNormal)
     artefact_id = Paragraph("<b>Artefact ID</b><br/>" + self.artefact_id,
                             styNormal)
     sito = Paragraph("<b>Site</b><br/>" + self.sito, styNormal)
     area = Paragraph("<b>Area</b><br/>" + self.area, styNormal)
     fabric = Paragraph("<b>Inclusions</b><br/>" + self.fabric, styNormal)
     specific_shape = Paragraph("<b>Form</b><br/>" + self.specific_shape,
                                styNormal)
     specific_part = Paragraph(
         "<b>Specific Part</b><br/>" + self.specific_part, styNormal)
     category = Paragraph("<b>Category</b><br/>" + self.category, styNormal)
     typology = Paragraph("<b>Typology</b><br/>" + self.typology, styNormal)
     depth = Paragraph("<b>Depth</b><br/>" + self.depth, styNormal)
     retrieved = Paragraph("<b>Retrieved</b><br/>" + self.retrieved,
                           styNormal)
     percent = Paragraph("<b>Percent of inclusion</b><br/>" + self.percent,
                         styNormal)
     provenience = Paragraph("<b>Provenance</b><br/>" + self.provenience,
                             styNormal)
     munsell = Paragraph("<b>Munsell Clay</b><br/>" + self.munsell,
                         styNormal)
     munsell_surf = Paragraph(
         "<b>Munsell Surfaces</b><br/>" + self.munsell_surf, styNormal)
     surf_trat = Paragraph("<b>Surface Treatment</b><br/>" + self.surf_trat,
                           styNormal)
     treatment = Paragraph("<b>Conservation</b><br/>" + self.treatment,
                           styNormal)
     period = Paragraph("<b>Period</b><br/>" + self.period, styNormal)
     state = Paragraph("<b>State</b><br/>" + self.state, styNormal)
     samples = Paragraph("<b>Samples</b><br/>" + self.samples, styNormal)
     diametro_max = Paragraph(
         "<b>Diameter Max</b><br/>" + str(self.diametro_max), styNormal)
     diametro_rim = Paragraph(
         "<b>Diameter Rim</b><br/>" + str(self.diametro_rim), styNormal)
     diametro_bottom = Paragraph(
         "<b>Diameter Bottom</b><br/>" + str(self.diametro_bottom),
         styNormal)
     total_height = Paragraph(
         "<b>Total Height</b><br/>" + str(self.total_height), styNormal)
     preserved_height = Paragraph(
         "<b>Preserved Height</b><br/>" + str(self.preserved_height),
         styNormal)
     base_height = Paragraph(
         "<b>Base Height</b><br/>" + str(self.base_height), styNormal)
     thickmin = Paragraph("<b>Thickness Min</b><br/>" + str(self.thickmin),
                          styNormal)
     thickmax = Paragraph("<b>Thickness Max</b><br/>" + str(self.thickmax),
                          styNormal)
     description = Paragraph("<b>Description</b><br/>" + self.description,
                             styNormal)
     data_ = Paragraph("<b>Date</b><br/>" + self.data_, styNormal)
     anno = Paragraph("<b>Year</b><br/>" + str(self.anno), styNormal)
     photographed = Paragraph(
         "<b>Photographed</b><br/>" + self.photographed, styNormal)
     drawing = Paragraph("<b>Drawing</b><br/>" + self.drawing, styNormal)
     wheel_made = Paragraph("<b>Wheel Made</b><br/>" + self.wheel_made,
                            styNormal)
     #schema
     cell_schema = [
         #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
         [
             logo2, '01', intestazione, '03', '04', '05', '06', '07', '08',
             '09', '10', '11', '12', '13', '14', '15', logo, '17'
         ],  #0 row ok
         [
             sito, '01', '02', '03', '04', '05', '06', '07', '08',
             artefact_id, '10', '11', '12', '13', '14', '15', '16', '17'
         ],  #1 row ok
         [
             divelog_id, '01', '02', '03', '04', '05', area, '07', '08',
             '09', '10', '11', anno, '13', '14', '15', '16', '17'
         ],  #2 row ok
         [
             fabric, '01', '02', '03', '04', '05', specific_part, '07',
             '08', '09', '10', '11', category, '13', '14', '15', '16', '17'
         ],  #2 row ok
         [
             specific_shape, '01', '02', '03', '04', '05', typology, '07',
             '08', '09', '10', '11', depth, '13', '14', '15', '16', '17'
         ],  #2 row ok
         [
             retrieved, '01', '02', '03', '04', '05', percent, '07', '08',
             '09', '10', '11', provenience, '13', '14', '15', '16', '17'
         ],  #2 row ok
         [
             munsell, '01', '02', '03', '04', '05', munsell_surf, '07',
             '08', '09', '10', '11', surf_trat, '13', '14', '15', '16', '17'
         ],  #2 row ok
         [
             treatment, '01', '02', '03', '04', '05', period, '07', '08',
             '09', '10', '11', state, '13', '14', '15', '16', '17'
         ],  #2 row ok
         [
             samples, '01', '02', '03', '04', '05', photographed, '07',
             '08', '09', '10', '11', drawing, '13', '14', '15', wheel_made,
             '17'
         ],  #2 row ok
         [
             diametro_max, '01', '02', '03', '04', '05', diametro_rim, '07',
             '08', '09', '10', '11', diametro_bottom, '13', '14', '15',
             '16', '17'
         ],  #2 row ok
         [
             total_height, '01', '02', '03', '04', '05', preserved_height,
             '07', '08', '09', '10', '11', base_height, '13', '14', '15',
             '16', '17'
         ],  #2 row ok
         [
             thickmin, '01', '02', '03', '04', '05', thickmax, '07', '08',
             '09', '10', '11', data_, '13', '14', '15', '16', '17'
         ],  #2 row ok
         [
             description, '01', '02', '03', '04', '05', '06', '07', '08',
             '09', '10', '11', '12', '13', '14', '15', '16', '17'
         ],  #8 row ok
     ]
     #table style
     table_style = [
         ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
         #0 row
         ('SPAN', (0, 0), (1, 0)),  #logo2
         ('SPAN', (2, 0), (15, 0)),  #intestazione
         ('SPAN', (16, 0), (17, 0)),  #logo
         ('SPAN', (0, 1), (8, 1)),  #sito
         ('SPAN', (9, 1), (17, 1)),  #divelogid
         ('SPAN', (0, 2), (5, 2)),  #diver1
         ('SPAN', (6, 2), (11, 2)),  #date_
         ('SPAN', (12, 2), (17, 2)),  #area_id
         ('SPAN', (0, 3), (5, 3)),  #diver2
         ('SPAN', (6, 3), (11, 3)),  #date_
         ('SPAN', (12, 3), (17, 3)),  #area_id
         ('SPAN', (0, 4), (5, 4)),  #diver2
         ('SPAN', (6, 4), (11, 4)),  #date_
         ('SPAN', (12, 4), (17, 4)),  #area_id
         ('SPAN', (0, 5), (5, 5)),  #diver2
         ('SPAN', (6, 5), (11, 5)),  #date_
         ('SPAN', (12, 5), (17, 5)),  #area_id
         ('SPAN', (0, 6), (5, 6)),  #diver2
         ('SPAN', (6, 6), (11, 6)),  #date_
         ('SPAN', (12, 6), (17, 6)),  #area_id
         ('SPAN', (0, 7), (5, 7)),  #diver2
         ('SPAN', (6, 7), (11, 7)),  #date_
         ('SPAN', (12, 7), (17, 7)),  #area_id
         ('SPAN', (0, 8), (5, 8)),  #diver2
         ('SPAN', (6, 8), (11, 8)),  #date_
         ('SPAN', (12, 8), (15, 8)),  #area_id
         ('SPAN', (16, 8), (17, 8)),  #area_id
         ('SPAN', (0, 9), (5, 9)),  #diver2
         ('SPAN', (6, 9), (11, 9)),  #date_
         ('SPAN', (12, 9), (17, 9)),  #area_id
         ('SPAN', (0, 10), (5, 10)),  #diver2
         ('SPAN', (6, 10), (11, 10)),  #date_
         ('SPAN', (12, 10), (17, 10)),  #area_id
         ('SPAN', (0, 11), (5, 11)),  #diver2
         ('SPAN', (6, 11), (11, 11)),  #date_
         ('SPAN', (12, 11), (17, 11)),  #area_id
         ('SPAN', (0, 12), (17, 12)),  #standby
     ]
     colWidths = (15, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
                  30, 30, 30, 30)
     rowHeights = None
     t = Table(cell_schema,
               colWidths=colWidths,
               rowHeights=rowHeights,
               style=table_style)
     return t
Example #40
0
def creditsects(form, elev, classe):
    """renvoie les crédits ects pdf de l'élève elev, ou si elev vaut None renvoie les crédits ects pdf de toute la classe en un seul fichier"""
    datedujour = form.cleaned_data['date'].strftime('%d/%m/%Y')
    filiere, annee = form.cleaned_data['classe'].split("_")
    signataire = form.cleaned_data['signature']
    etoile = form.cleaned_data['etoile']
    tree = etree.parse(join(RESOURCES_ROOT, 'classes.xml')).getroot()
    classexml = tree.findall("classe[@nom='{}'][@annee='{}']".format(
        filiere, annee)).pop()
    domaine = classexml.get("domaine")
    branche = classexml.get("type").lower()
    precision = classexml.get("precision")
    signature = False
    if 'tampon' in form.cleaned_data:
        signature = form.cleaned_data['tampon']
    LIST_NOTES = "ABCDEF"
    response = HttpResponse(content_type='application/pdf')
    if elev is None:
        eleves = Eleve.objects.filter(classe=classe).order_by(
            'user__last_name', 'user__first_name').select_related('user')
        nomfichier = "ECTS_{}.pdf".format(unidecode(classe.nom)).replace(
            " ", "-").replace('*', 'etoile')
        credits = NoteECTS.objects.credits(classe)[0]
    else:
        eleves = [elev]
        credits = [False]
        nomfichier = unidecode("ECTS_{}_{}_{}.pdf".format(
            classe.nom.upper(), elev.user.first_name,
            elev.user.last_name.upper())).replace(" ", "-")
    response['Content-Disposition'] = "attachment; filename={}".format(
        nomfichier)
    pdf = easyPdf()
    cm = pdf.format[0] / 21
    pdf.marge_x = cm  # 1cm de marge gauche/droite
    pdf.marge_y = 1.5 * cm  # 1,5cm de marge haut/bas
    I = Image(join(RESOURCES_ROOT, 'marianne.jpg'))
    I.drawHeight = 1.8 * cm
    I.drawWidth = 3 * cm
    if signature and signataire == 'Proviseur':
        try:
            I2 = Image(join(RESOURCES_ROOT, 'proviseur.png'))
        except Exception:
            try:
                I2 = Image(join(RESOURCES_ROOT, 'proviseur.png'))
            except Exception:
                I2 = False
    elif signature and signataire == 'Proviseur adjoint':
        try:
            I2 = Image(join(RESOURCES_ROOT, 'proviseuradjoint.png'))
        except Exception:
            try:
                I2 = Image(join(RESOURCES_ROOT, 'proviseuradjoint.png'))
            except Exception:
                I2 = False
    else:
        I2 = False
    if I2:
        I2.drawHeight = 3 * cm
        I2.drawWidth = 3 * cm
    newpage = False
    style = ParagraphStyle(name='normal', fontSize=9, leading=11, spaceAfter=5)
    styleResume = ParagraphStyle(name='resume',
                                 fontSize=9,
                                 leading=11,
                                 spaceAfter=0)
    styleTitre = ParagraphStyle(name='titre',
                                fontSize=12,
                                leading=13,
                                fontName="Helvetica-Bold",
                                borderColor='black',
                                borderPadding=(0, 0, 2, 0),
                                borderWidth=1,
                                backColor='#DDDDDD',
                                spaceAfter=2)
    data1 = [["A", "Très Bien", "C", "Assez Bien", "E", "Passable"],
             ["B", "Bien", "D", "Convenable", "F", "Insuffisant"]]
    LIST_STYLE1 = TableStyle([('GRID', (0, 0), (-1, -1), .2, (0, 0, 0)),
                              ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                              ('ALIGN', (0, 0), (-1, -1), 'CENTRE'),
                              ('FACE', (0, 0), (-1, -1), 'Helvetica'),
                              ('SIZE', (0, 0), (-1, -1), 8),
                              ('BACKGROUND', (0, 0), (-1, -1), (.9, .9, .9))])
    t1 = Table(data1,
               colWidths=[.8 * cm, 2 * cm, .8 * cm, 2 * cm, .8 * cm, 2 * cm],
               rowHeights=[12] * 2)
    t1.setStyle(LIST_STYLE1)
    data2 = [["8","D","","Université","",""],["7","D","","Université","",""],["6","D","","Université","",""],\
      ["5","M","","Université ou grande école","",""],["4","M","","Université ou grande école","",""],["3","L","ATS","Université ou grande école","",""],\
      ["2","L","STS-IUT","","Université","CPGE"],["1","L","STS-IUT","","Université","CPGE"],["0","Bac","Enseignement secondaire","","",""]]
    LIST_STYLE2 = TableStyle([
        ('GRID', (0, 0), (1, 4), .8, (0, 0, 0)),
        ('GRID', (3, 0), (5, 4), .8, (0, 0, 0)),
        ('GRID', (0, 5), (5, 8), .8, (0, 0, 0)),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('ALIGN', (0, 0), (-1, -1), 'CENTRE'),
        ('FACE', (0, 0), (-1, -1), 'Helvetica-Bold'),
        ('SIZE', (0, 0), (-1, -1), 8),
        ('BACKGROUND', (0, 0), (-1, -1), (1, 1, 1)), ('SPAN', (3, 0), (5, 0)),
        ('SPAN', (3, 1), (5, 1)), ('SPAN', (3, 2), (5, 2)),
        ('SPAN', (3, 3), (5, 3)), ('SPAN', (3, 4), (5, 4)),
        ('SPAN', (3, 5), (5, 5)), ('SPAN', (2, 6), (3, 6)),
        ('SPAN', (2, 7), (3, 7)), ('SPAN', (2, 8), (5, 8)),
        ('BACKGROUND', (3, 0), (5, 2), '#FABF8F'),
        ('BACKGROUND', (3, 3), (5, 4), '#FBD4B4'),
        ('BACKGROUND', (2, 5), (2, 5), '#76923C'),
        ('BACKGROUND', (3, 5), (5, 5), '#FDE9D9'),
        ('BACKGROUND', (4, 6), (4, 7), '#FDE9D9'),
        ('BACKGROUND', (2, 6), (3, 7), '#D6E3BC'),
        ('BACKGROUND', (5, 6), (5, 7), '#FF9900')
    ])
    t2 = Table(
        data2,
        colWidths=[.84 * cm, .91 * cm, .75 * cm, 1.4 * cm, 2.5 * cm, 2.5 * cm],
        rowHeights=[.8 * cm] * 9)
    t2.setStyle(LIST_STYLE2)
    texte = "1. Information sur l'étudiant"
    p1 = Paragraph(texte, styleTitre)
    texte = "2. Information sur la formation"
    p3 = Paragraph(texte, styleTitre)
    texte = "3. Information sur le niveau de la formation"
    p5 = Paragraph(texte, styleTitre)
    texte = """<b><i>3.1. Niveau de la formation:</i></b><br/>
	Située au sein des études menant au grade de licence.<br/>
	Niveau bac + 2 / 120 crédits ECTS<br/>
	<b><i>3.2. Durée officielle du programme de formation:</i></b><br/>
	La durée du programme est de 2 ans.<br/>
	<b><i>3.3. Conditions d’accès:</i></b><br/>
	Entrée sélective après le baccalauréat s’effectuant dans le cadre d’une procédure nationale d’admission.<br/>
	Cf: <a href="http://www.admission-postbac.fr" color="blue">http://www.admission-postbac.fr</a>"""
    p6 = Paragraph(texte, style)
    texte = """4. Information sur les contenus et les résultats obtenus"""
    p7 = Paragraph(texte, styleTitre)
    texte = """<b><i>4.1. Organisation des études:</i></b><br/>
	Plein temps, contrôle continu écrit et oral<br/>
	<b><i>4.2. Exigences du programme:</i></b><br/>
	La formation dispensée a pour objet de donner aux étudiants une compréhension approfondie des disciplines enseignées et une appréhension de leurs caractéristiques générales. Elle prend en compte leurs évolutions, leurs applications et la préparation à des démarches de recherche.
	Elle est définie par des programmes nationaux.<br/>
	<b><i>4.3. Précisions sur le programme:</i></b><br/>
	Voir relevé au verso et catalogue de cours<br/>
	<b><i>4.4. Échelle d’évaluation:</i></b><br/>
	L’évaluation prend en compte l’ensemble des travaux des étudiants. La qualité du travail, des résultats obtenus et des compétences acquises est exprimée par une mention conformément au tableau ci-dessous."""
    p8 = Paragraph(texte, styleResume)
    texte = """<b><i>4.5. Classification de la formation:</i></b><br/>
	Une mention globale, portant sur l’ensemble du parcours et s’exprimant dans la même échelle qu’en 4.4 figure à la fin du relevé."""
    p9 = Paragraph(texte, style)
    texte = "5. Information sur la fonction de la qualification"
    p10 = Paragraph(texte, styleTitre)
    texte = """<b><i>5.1. Accès à un niveau d’études supérieur:</i></b><br/>
	Accès par concours aux grandes écoles.<br/>
	Accès, par validation de parcours, à tout type d’établissement d’enseignement supérieur.<br/>
	<b><i>5.2. Statut  professionnel (si applicable):</i></b><br/>
	Sans objet"""
    p11 = Paragraph(texte, style)
    texte = "6. Informations complémentaires"
    p12 = Paragraph(texte, styleTitre)
    texte = """<b><i>6.1. Informations complémentaires:</i></b><br/>
	Catalogue des cours et arrêtés ministériels définissant les programmes consultables sur :<br/>
	<a href="http://www.enseignementsup-recherche.gouv.fr/" color="blue">http://www.enseignementsup-recherche.gouv.fr/</a><br/>
	<b><i>6.2. Autres sources d’information:</i></b><br/>
	Pour toute information sur le dispositif CPGE consulter :<br/>
	<a href="http://www.enseignementsup-recherche.gouv.fr/" color="blue">http://www.enseignementsup-recherche.gouv.fr/</a>"""
    p13 = Paragraph(texte, style)
    texte = "7. Certification de l’attestation"
    p14 = Paragraph(texte, styleTitre)
    texte = "8. Informations sur le système national d’enseignement supérieur"
    p16 = Paragraph(texte, styleTitre)
    p17 = Paragraph("<br/> <br/>", style)
    for eleve, credit in zip(eleves, credits):
        if elev or credit and credit['ddn'] and credit['ine'] and credit[
                'sem1'] == 30 and credit[
                    'sem2'] == 30:  # si l'élève a bien toutes les infos/crédits
            if newpage:  # si ce n'est pas la première page, on change de page
                pdf.showPage()
            pdf.y = pdf.format[1] - pdf.marge_y - 1.8 * cm
            I.drawOn(pdf, 9 * cm, pdf.y)
            pdf.y -= 10
            pdf.setFont("Times-Roman", 7)
            pdf.drawCentredString(10.5 * cm, pdf.y,
                                  "MINISTÈRE DE L'ÉDUCATION NATIONALE")
            pdf.y -= 8
            pdf.drawCentredString(
                10.5 * cm, pdf.y,
                "DE l'ENSEIGNEMENT SUPÉRIEUR ET DE LA RECHERCHE")
            pdf.y -= 12
            pdf.setFont("Helvetica-Bold", 11)
            pdf.drawCentredString(10.5 * cm, pdf.y,
                                  "CLASSES PRÉPARATOIRES AUX GRANDES ÉCOLES")
            pdf.y -= 12
            pdf.setFont("Helvetica", 11)
            pdf.drawCentredString(10.5 * cm, pdf.y,
                                  "ANNEXE DESCRIPTIVE DE LA FORMATION")
            story = [p1]
            texte = "<b><i>1.1. Nom:</i></b> {}<br/><b><i>1.2. Prénom:</i></b> {}<br/><b><i>1.3. Date de Naissance:</i></b> {}<br/><b><i>1.4. Lieu de Naissance:</i></b> {}<br/><b><i>1.5. N° INE:</i></b> {}".format(
                eleve.user.last_name.upper(), eleve.user.first_name.title(),
                "" if not eleve.ddn else eleve.ddn.strftime('%d/%m/%Y'),
                "" if not eleve.ldn else eleve.ldn.title(), eleve.ine)
            p2 = Paragraph(texte, style)
            story.extend([p2, p3])
            texte = """<b><i>2.1. Nom de la formation:</i></b><br/>
			Classe préparatoire {} {} {}<br/>
			<b><i>2.2. Principaux domaines d’étude:</i></b><br/>
			{}<br/>
			<b><i>2.3. Nom et statut de l’institution gérant la formation:</i></b><br/>
			Ministère de l’enseignement supérieur et de la recherche
			Classes préparatoires aux grandes écoles<br/>
			<b><i>2.4. Nom et statut de l’établissement dispensant la formation:</i></b><br/>
			{}<br/>
			<b><i>2.5. Langue de formation:</i></b> français""".format(
                branche, filiere, "(" + precision + ")" if precision else "",
                domaine,
                Config.objects.get_config().nom_adresse_etablissement.replace(
                    "\n",
                    "<br/>").replace("\r",
                                     "<br/>").replace("<br/><br/>", "<br/>"))
            p4 = Paragraph(texte, style)
            story.extend([p4, p5, p6, p7, p8, t1, p9])
            fl = Frame(cm,
                       1.5 * cm,
                       9 * cm,
                       23 * cm,
                       showBoundary=0,
                       leftPadding=0,
                       rightPadding=0,
                       topPadding=0,
                       bottomPadding=0)
            fl.addFromList(story, pdf)
            story = [p10, p11, p12, p13, p14]
            texte = """<b><i>7.1. Date:</i></b> {}<br/>
			<b><i>7.2. Signature:</i></b><br/><br/><br/><br/>
			<b><i>7.3. Fonction:</i></b> {}<br/>
			<b><i>7.4. Tampon ou cachet officiel:</i></b><br/><br/><br/><br/><br/><br/>""".format(
                datedujour, signataire)
            p15 = Paragraph(texte, style)
            story.extend([p15, p16, p17, t2])
            fr = Frame(11 * cm,
                       1.5 * cm,
                       9 * cm,
                       23 * cm,
                       showBoundary=0,
                       leftPadding=0,
                       rightPadding=0,
                       topPadding=0,
                       bottomPadding=0)
            fr.addFromList(story, pdf)
            if I2:
                I2.drawOn(pdf, 16.2 * cm, 13.2 * cm)
            pdf.showPage()
            pdf.y = pdf.format[1] - pdf.marge_y - 12
            pdf.setFont('Helvetica-Bold', 12)
            pdf.drawCentredString(
                10.5 * cm, pdf.y, "RELEVÉ DE RÉSULTATS (classe {})".format(
                    filiere + ('*' if etoile and classe.annee == 2 else '')))
            sem1, sem2 = NoteECTS.objects.notePDF(eleve)
            data = [["ENSEIGNEMENTS", "Crédits ECTS", "Mention"],
                    ["Premier semestre", "", ""]]
            sp = 0  # variable qui va contenir la somme pondérée des notes en vue du calcul de la mention globale
            coeff = 0  # somme des coeffs pour vérifier si on en a 60 au total
            for note in sem1:
                data.append([
                    note[0] + ("" if not note[1] else " ({})".format(note[1])),
                    note[2], LIST_NOTES[note[4]]
                ])
                sp += note[2] * note[4]
                if note[4] != 5:
                    coeff += note[2]
            data.append(["Deuxième semestre", "", ""])
            for note in sem2:
                data.append([
                    note[0] + ("" if not note[1] else " ({})".format(note[1])),
                    note[3], LIST_NOTES[note[4]]
                ])
                sp += note[3] * note[4]
                if note[4] != 5:
                    coeff += note[3]
            LIST_STYLE = TableStyle([
                ('GRID', (0, 0), (-1, -1), .8, (0, 0, 0)),
                ('SPAN', (0, 1), (2, 1)),
                ('SPAN', (0, 2 + len(sem1)), (2, 2 + len(sem1))),
                ('FACE', (0, 0), (-1, -1), 'Helvetica-Bold'),
                ('SIZE', (0, 0), (-1, -1), 8), ('SIZE', (0, 1), (2, 1), 9),
                ('SIZE', (0, 2 + len(sem1)), (2, 2 + len(sem1)), 9),
                ('SIZE', (0, 0), (2, 0), 10),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('ALIGN', (0, 2), (0, -1), 'LEFT'),
                ('ALIGN', (1, 0), (2, -1), 'CENTRE'),
                ('ALIGN', (0, 0), (2, 1), 'CENTRE'),
                ('ALIGN', (0, 2 + len(sem1)), (2, 2 + len(sem1)), 'CENTRE'),
                ('BACKGROUND', (0, 1), (2, 1), '#DDDDDD'),
                ('BACKGROUND', (0, 2 + len(sem1)), (2, 2 + len(sem1)),
                 '#DDDDDD')
            ])
            t = Table(data,
                      colWidths=[13 * cm, 2.8 * cm, 2.5 * cm],
                      rowHeights=[.8 * cm] * (3 + len(sem1) + len(sem2)))
            t.setStyle(LIST_STYLE)
            w, h = t.wrapOn(pdf, 0, 0)
            pdf.y -= h + 5
            pdf.x = (pdf.format[0] - w) / 2
            t.drawOn(pdf, pdf.x, pdf.y)
            pdf.y -= 20
            pdf.setFont('Helvetica-Bold', 10)
            if coeff == 60:
                pdf.drawString(
                    pdf.x, pdf.y, "Mention globale: {}".format(
                        LIST_NOTES[int(sp / 60 + .5)]))
            else:
                pdf.setFillColor((1, 0, 0))
                pdf.drawString(
                    pdf.x, pdf.y,
                    "Pas de mention, il manque {} crédits".format(60 - coeff))
                pdf.setFillColor((0, 0, 0))
            pdf.drawRightString(pdf.format[0] - pdf.x - 15, pdf.y,
                                "Cachet et signature")
            pdf.y -= 3.2 * cm
            if I2:
                I2.drawOn(pdf, pdf.format[0] - 2 * pdf.marge_x - 3 * cm, pdf.y)
            newpage = True
    pdf.save()
    fichier = pdf.buffer.getvalue()
    pdf.buffer.close()
    response.write(fichier)
    return response
Example #41
0
    def createDocument(self):  # funzione che crea il documento
        """"""
        voffset = 65  # offset verticale

        # add a logo and size it
        logo = Image('Image_pdf/Meta-logo.jpg')  # indica la path dell'immagine
        logo.drawHeight = 3 * inch  # indica l'alteza dell'immagine
        logo.drawWidth = 3.5 * inch  # indica la larghezza dell'immagine
        logo.wrapOn(
            self.c, self.width,
            self.height)  # indica l'impostazione dell'immagine nel foglio
        logo.drawOn(self.c, *self.coord(
            65, 80, mm))  # disegna la foto a coordinate fissate 65,80, mm

        address = """<font size="24">
		Stazione di %s%s</font>
        """ % (self.namestation, self.id
               )  # indica il nome della stazione corrente
        p = Paragraph(
            address,
            self.styles["Normal"])  # creazione di un paragrafo di testo
        p.wrapOn(self.c, self.width,
                 self.height)  # importazione del testo nel foglio
        if len(
                self.namestation
        ) == 6:  # if fatti per centrare il nome della stazione nel foglio
            self.X = 188
        elif len(self.namestation) == 3:
            self.X = 223
        elif len(self.namestation) == 4:
            self.X = 214
        elif len(self.namestation) == 5:
            self.X = 205
        elif len(self.namestation) == 7:
            self.X = 180
        elif len(self.namestation) == 8:
            self.X = 175
        elif len(self.namestation) == 9:
            self.X = 172
        elif len(self.namestation) == 10:
            self.X = 168
        elif len(self.namestation) == 11:
            self.X = 164
        elif len(self.namestation) == 12:
            self.X = 160
        elif len(self.namestation) == 13:
            self.X = 156
        elif len(self.namestation) == 14:
            self.X = 152
        elif len(self.namestation) == 15:
            self.X = 148
        elif len(self.namestation) == 16:
            self.X = 144
        elif len(self.namestation) == 17:
            self.X = 140
        elif len(self.namestation) == 18:
            self.X = 136
        elif len(self.namestation) == 19:
            self.X = 132
        elif len(self.namestation) == 20:
            self.X = 128
        elif len(self.namestation) == 21:
            self.X = 124
        elif len(self.namestation) == 22:
            self.X = 120
        elif len(self.namestation) == 23:
            self.X = 116
        p.drawOn(self.c, *self.coord(self.X,
                                     195))  # diesgna il testo a coordinate...

        tMedia = """<font size="12">
		<b>Temperatura media</b></font>
		"""                  # paragrafo di testo
        self.createParagraph(tMedia, 18, voffset + 25)  # creazione paragrafo
        data = [[
            "Dati attesi", "Dati effettivi", "Percentuale di funzionamento"
        ], [valTot, valPresTMED, "%d" % (percTMED) + "%"]]  # dati per tabella
        table = Table(data, colWidths=2 * inch)  # inizializzazione tabella
        table.setStyle([("VALIGN", (-1, -1), (-1, -1), "TOP"),
                        ("GRID", (0, 0), (-1, -1), 1, colors.black),
                        ("GRID", (0, 0), (-1, 0), 1, colors.black)
                        ])  # stile tabella
        table.wrapOn(self.c, self.width,
                     self.height)  # importazione nel foglio della tabella
        table.drawOn(self.c,
                     *self.coord(18, 105,
                                 mm))  # disegno della tabella a coordinate...

        umid = """<font size="12">
		<b>Umidità</b></font>
		"""
        self.createParagraph(umid, 18, voffset + 50)
        data = [[
            "Dati attesi", "Dati effettivi", "Percentuale di funzionamento"
        ], [valTot, valPresUMID, "%d" % (percUMID) + "%"]]
        table = Table(data, colWidths=2 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("GRID", (0, 0), (-1, -1), 1, colors.black),
                        ("GRID", (0, 0), (-1, 0), 1, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(18, 130, mm))

        piogg = """<font size="12">
		<b>Pioggia</b></font>
		"""
        self.createParagraph(piogg, 18, voffset + 75)
        data = [[
            "Dati attesi", "Dati effettivi", "Percentuale di funzionamento"
        ], [valTot, valPresPG, "%d" % (percPG) + "%"]]
        table = Table(data, colWidths=2 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("GRID", (0, 0), (-1, -1), 1, colors.black),
                        ("GRID", (0, 0), (-1, 0), 1, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(18, 155, mm))

        bagnFogl = """<font size="12">
		<b>Bagnatura fogliare</b></font>
		"""
        self.createParagraph(bagnFogl, 18, voffset + 100)
        data = [[
            "Dati attesi", "Dati effettivi", "Percentuale di funzionamento"
        ], [valTot, valPresFB, "%d" % (percFB) + "%"]]
        table = Table(data, colWidths=2 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("GRID", (0, 0), (-1, -1), 1, colors.black),
                        ("GRID", (0, 0), (-1, 0), 1, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(18, 180, mm))

        velVento = """<font size="12">
		<b>Velocità vento</b></font>
		"""
        self.createParagraph(velVento, 18, voffset + 125)
        data = [[
            "Dati attesi", "Dati effettivi", "Percentuale di funzionamento"
        ], [valTot, valPresVenVel,
            "%d" % (percVenVel) + "%"]]
        table = Table(data, colWidths=2 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("GRID", (0, 0), (-1, -1), 1, colors.black),
                        ("GRID", (0, 0), (-1, 0), 1, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(18, 205, mm))

        radSolare = """<font size="12">
		<b>Radiazione solare</b></font>
		"""
        self.createParagraph(radSolare, 18, voffset + 150)
        data = [[
            "Dati attesi", "Dati effettivi", "Percentuale di funzionamento"
        ], [valTot, valPresRAD, "%d" % (percRAD) + "%"]]
        table = Table(data, colWidths=2 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("GRID", (0, 0), (-1, -1), 1, colors.black),
                        ("GRID", (0, 0), (-1, 0), 1, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(18, 230, mm))

        self.c.showPage()  # per iniziare una nuova pagina

        self.drawing = Drawing(200, 400)  # disegna figura vuota
        self.drawing.rotate(-90)  # ruota figura vuota
        self.data = [(percRAD, percVenVel, percFB, percPG, percUMID, percTMED)
                     ]  #dati per il grafico
        self.names = [
            "Radiazione solare", "Velocità vento", "Bagnatura fogliare",
            "Pioggia", "Umidità", "Temperatura media"
        ]  #nomi per grafico
        self.bc = HorizontalBarChart()  # inizializzazione grafico orizzontale
        self.bc.x = 20  # x del grafico
        self.bc.y = 50  # y del grafico
        self.bc.height = 400  # altezza del grafico
        self.bc.width = 600  # larghezza grafico
        self.bc.data = self.data  # dati del grafico sono uguali a data
        self.bc.strokeColor = colors.white  # colore del grafico
        self.bc.valueAxis.valueMin = 0  # valore minimo asse
        self.bc.valueAxis.valueMax = 100  # valore massimo asse
        self.bc.valueAxis.valueStep = 5  # step di 5 dell'asse
        self.bc.categoryAxis.labels.boxAnchor = 'ne'  # non importante
        self.bc.categoryAxis.labels.dx = -10  # etichettatura grafico
        self.bc.categoryAxis.labels.fontName = 'Helvetica'  # font garfico
        self.bc.categoryAxis.categoryNames = self.names  # asse dei nomi, quello sotto
        self.drawing.add(self.bc)  # aggiunta del grafico alla figura vuota
        renderPDF.draw(self.drawing, self.c, 40,
                       700)  # disegmo del grafico sul pdf

        self.d = Drawing(0, 0)
        self.d.rotate(-90)
        self.c.rotate(-90)
        self.c.setFont('Helvetica', 30)
        self.cb = self.c.drawString(
            -600, 525, "Percentuale di funzionamento"
        )  # creazione titolo per grafico ruotato di -90 gradi
        self.d.add(
            self.cb
        )  # la x è negativa perchè anche le coordinate cambiano in base al punto di orgine
        renderPDF.draw(self.d, self.c, 100, 100)
Example #42
0
def exportHojaPDF(request):

    response = HttpResponse(content_type='application/pdf')
    buff = io.BytesIO()
    doc = SimpleDocTemplate(
        buff,
        fileName='Hoja.pdf',  #+str(pk),
        pagesize=landscape(letter),
        #pagesize=letter,
        rightMargin=40,
        leftMargin=20,
        topMargin=10,
        bottomMargin=18,
    )
    categorias = []
    styles = getSampleStyleSheet()
    styleN = styles["Normal"]

    pa = ParagraphStyle(
        'parrafos',
        alignment=TA_CENTER,
        fontSize=5,
    )
    pa2 = ParagraphStyle(
        'parrafos2',
        spaceAfter=6,
        alignment=TA_CENTER,
        fontSize=10,
    )

    pa3 = ParagraphStyle(
        'parrafos3',
        spaceAfter=6,
        alignment=TA_RIGHT,
        fontSize=15,
    )

    #ca  = Paragraph("Listado de 222 ", styles['Heading2'])
    #categorias.append(header)
    c = 0
    headings = ('ITEM', 'CODIGO 2019', 'CODIGO SBN', 'CODIGO 2018',
                'NOMBRE DEL BIEN', 'MARCA', 'MODELO', 'SERIE', 'MEDIDAS',
                'COLOR', 'EST', 'USO', 'OBSERVACION')
    #if not pk:
    #  ficha_unique = [(p.id, p.num_ficha, p.fecha_ficha, p.ambiente)
    #            for p in ficha_unique.objects.all().order_by('pk')]
    #else:
    pk = ficha.objects.get(id=int(request.GET.get('id_ficha', None)))
    ficha_unique = [(p.idusuario, p.num_ficha, p.fecha_ficha, p.ambiente,
                     p.sede, p.fecha_ficha, p.idusuario.numero_doc_usuario,
                     p.idusuario.moda_usuario.modalidad_contratacion, p.piso,
                     p.cod_ambiente, p.ambiente, p.dependencia)
                    for p in ficha.objects.filter(id=int(pk.id))]
    bienes = [(b.item, b.codigo_conformidad, b.base0_fk.codigo_sbn,
               b.base0_fk.codigo_interno,
               Paragraph(b.base0_fk.descripcion[0:25], pa),
               str(b.base0_fk.mar)[0:6], str(b.base0_fk.modelo)[0:6],
               Paragraph(str(b.base0_fk.serie)[0:8], pa), b.base0_fk.medida,
               str(b.base0_fk.col)[0:5], b.base0_fk.est.nom_es, b.base0_fk.op,
               str(b.base0_fk.observacion1)[0:15])
              for b in base12019.objects.filter(
                  idficha_id=int(pk.id)).order_by('item')]

    ca0 = Image(
        'https://upload.wikimedia.org/wikipedia/commons/c/ca/PCM-MIMP.png')
    ca0.drawHeight = 0.5 * inch
    ca0.drawWidth = 3.3 * inch
    ca0.hAlign = 'LEFT'

    header = Paragraph("HOJA DE TOMA DE INVENTARIO DE BIENES MUEBLES DEL MIMP",
                       pa2)
    header2 = Paragraph("AL 31 DE DICIEMBRE 2019 ", pa2)

    ca1 = Paragraph(
        "                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;          Folio "
        + str(ficha_unique[0][1]), styles['Heading5'])
    ca2 = Paragraph(
        "                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      Fecha "
        + str(ficha_unique[0][5]), styles['Heading5'])

    #Cabecera
    ca3 = Paragraph(
        "USUARIO RESPONSABLE: " + str(ficha_unique[0][0]) +
        " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SEDE:  "
        + str(ficha_unique[0][4]) + "", styles['Heading6'])
    ca4 = Paragraph(
        "DNI: " + str(ficha_unique[0][6]) + "  MODALIDAD: " +
        str(ficha_unique[0][7]) +
        " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PISO: "
        + str(ficha_unique[0][8]) + " ", styles['Heading6'])
    ca5 = Paragraph(
        "DIRECCIÓN:" + str(ficha_unique[0][11]) +
        "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CODIGO AMB: "
        + str(ficha_unique[0][9]) + "  AMBIENTE: " + str(ficha_unique[0][10]),
        styles['Heading6'])

    #Detalle
    #ca6 = Paragraph("", styles['Heading6'])
    #ca7 = Paragraph("", styles['Heading6'])
    #ca8 = Paragraph("", styles['Heading6'])
    #ca9 = Paragraph("", styles['Heading6'])

    t = Table([headings] + bienes,
              colWidths=[
                  1.0 * cm, 1.4 * cm, 2.5 * cm, 1.5 * cm, 5.0 * cm, 1.5 * cm,
                  2.8 * cm, 1.5 * cm, 1.7 * cm, 1.5 * cm, 1.0 * cm, 1.5 * cm,
                  2.0 * cm
              ],
              rowHeights=5.5 * mm)

    #, colWidths = [50, 50, 50, 50, 50,50, 50, 50, 50, 5050, 50, 50]

    count = base12019.objects.filter(idficha_id=pk).count()
    """for i in range(0, count+1):
       t.setStyle(TableStyle(
           ('FONTSIZE', (0, 0), (-1, 1), 5),
           ('GRID', (0, 0), (0, 0), 0, colors.white),
        ))"""

    t.setStyle(
        TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 5),
            ('GRID', (0, 0), (-1, -1), 0, colors.black),
            ('LINEBELOW', (0, 0), (-1, -1), 0, colors.black),
            #('BACKGROUND', (0, 0), (0, 0), colors.dodgerblue),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('BOTTOMPADDING', (-1, -1), (-1, -1), -100),
        ]))

    ca10 = Paragraph("Leyenda:_______________ USO (S)SI (N)NO ",
                     styles['Heading6'])
    ca11 = Paragraph(
        "_______________________ ESTADO (B) BUENO (R) REGULAR (M) MALO (X) RAEE (Y) CHATARRA",
        styles['Heading6'])

    ca12 = Paragraph("", styles['Heading6'])
    ca13 = Paragraph("", styles['Heading6'])
    ca14 = Paragraph("", styles['Heading6'])
    ca15 = Paragraph("", styles['Heading6'])

    ca16 = Paragraph(
        "           &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;                  ___________________________________________________________________________",
        styles['Heading6'])

    ca17 = Paragraph(
        "          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; INVENTARIADOR USUAIRO &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RESPONSABLE",
        styles['Heading6'])

    ca18 = Paragraph("", styles['Heading6'])
    ca19 = Paragraph("", styles['Heading6'])

    categorias.append(ca0)
    categorias.append(ca19)
    categorias.append(header)
    categorias.append(header2)

    categorias.append(ca18)
    #categorias.append(ca19)
    #print(t)
    categorias.append(ca1)
    categorias.append(ca2)

    categorias.append(ca3)
    categorias.append(ca4)
    categorias.append(ca5)
    #categorias.append(ca6)
    #categorias.append(ca7)
    #categorias.append(ca8)
    #categorias.append(ca9)

    categorias.append(t)
    categorias.append(ca10)
    categorias.append(ca11)

    #categorias.append(ca12)
    #categorias.append(ca13)
    #categorias.append(ca14)
    #categorias.append(ca15)

    categorias.append(ca16)

    categorias.append(ca17)
    element = []
    for c in bienes:
        if c[0] % 5 == 0:
            element.extend([PageBreak(), t])

    doc.build(categorias)
    response.write(buff.getvalue())
    buff.close()
    return response
Example #43
0
    def export_rel_pdf(self):
        Story = []
        home = os.environ['PYARCHINIT_HOME']

        home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder')
        logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg')
        logo = Image(logo_path)

        ##      if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch
        magName = "Pythonista"
        subPrice = "99.00"
        limitedDate = "03/05/2010"
        freeGift = "tin foil hat"

        # DATI INTESTAZIONE
        formatted_time = time.ctime()
        full_name = "Responsabile: Luca Mandolesi"
        address_parts = [
            "Sito: Via Cavour 60, Ravenna", "Indirizzo: Via Cavour 60",
            "Comune: Ravenna"
        ]

        Story.append(PageBreak())
        #im = Image(logo)
        Story.append(logo)

        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(name='Justify',
                           alignment=TA_JUSTIFY,
                           bulletText='-'))

        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))

        Story.append(PageBreak())

        ###Sezione 2 - SITO
        # Titolo descrizione sito

        # funzioni di ricerca
        search_dict = {'sito': "'" + str(self.SITO) + "'"}
        self.DATA_LIST = self.DB_MANAGER.query_bool(search_dict, "SITE")

        # formattazione del testo
        ptext = '<font size=14><b>Sito: %s</b></font>' % self.DATA_LIST[0].sito

        Story.append(Paragraph(ptext, styles["Normal"]))
        Story.append(Spacer(1, 12))
        # Descrizione sito
        ptext = '<font size=12> <b>Descrizione del sito </b><br/> %s </font>' % self.DATA_LIST[
            0].descrizione
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 12))

        # Titolo descrizione periodo
        # cerca se e' presente una scansione cronologica del sito
        self.DATA_LIST = []
        periodizzazione_records = self.search_records('sito', self.SITO,
                                                      'PERIODIZZAZIONE')
        if bool(periodizzazione_records):
            Story.append(PageBreak())
            # crea l'intestazione della Periodizzazione
            ptext = '<font size=16 ><b>Periodizzazione di scavo</b><br/><br/></font>'
            Story.append(Paragraph(ptext, styles["Normal"]))
            Story.append(Spacer(1, 12))
            # estrae gli id dai record
            id_list_periodo = self.extract_id_list(periodizzazione_records,
                                                   'id_perfas')
            # carica i record di periodo ordinati in base al codice di periodo
            self.load_data_sorted(id_list_periodo, ['cont_per'], 'asc',
                                  'PERIODIZZAZIONE', 'id_perfas')

            for sing_rec in range(len(self.DATA_LIST)):
                ptext = '<font size=12 ><b>Periodo: %s - Fase %s - Datazione estesa: %s</b></font><br/>' % (
                    self.DATA_LIST[sing_rec].periodo,
                    self.DATA_LIST[sing_rec].fase,
                    self.DATA_LIST[sing_rec].datazione_estesa)
                Story.append(Paragraph(ptext, styles["Normal"]))
                Story.append(Spacer(1, 12))

            Story.append(PageBreak())

            for sing_rec in range(len(self.DATA_LIST)):
                ptext = '<font size=12 ><b>Periodo: %s - Fase %s </b></font><br/>' % (
                    self.DATA_LIST[sing_rec].periodo,
                    self.DATA_LIST[sing_rec].fase)
                Story.append(Paragraph(ptext, styles["Normal"]))
                Story.append(Spacer(1, 12))

                # Descrizione periodo
                ptext = '<font size=12> %s </font><br/><br/>' % (
                    self.DATA_LIST[sing_rec].descrizione)
                Story.append(Paragraph(ptext, styles["Justify"]))
                Story.append(Spacer(1, 12))

                # Titolo descrizione struttura
                # cerca se sono presenti strutture
        self.DATA_LIST = []
        strutture_records = self.search_records('sito', self.SITO, 'STRUTTURA')
        if bool(strutture_records):
            Story.append(PageBreak())
            # crea l'intestazione delle Strutture
            ptext = '<font size=16 ><b>Strutture di scavo</b><br/><br/></font>'
            Story.append(Paragraph(ptext, styles["Normal"]))
            Story.append(Spacer(1, 12))
            # estrae gli id dai record
            id_list_strutture = self.extract_id_list(strutture_records,
                                                     'id_struttura')

            # carica i record di struttura ordinati in base alla sigla struttura e il suo numero
            self.load_data_sorted(id_list_strutture,
                                  ['sigla_struttura', 'numero_struttura'],
                                  'asc', 'STRUTTURA', 'id_struttura')

            # crea l'intestazione dell'elenco delle sigle struttura presenti nel DB
            ptext = '<font size=16 >Elenco Strutture<br/></font>'
            Story.append(Paragraph(ptext, styles["Normal"]))
            Story.append(Spacer(1, 12))

            # Viene stampata la prima sigla di struttura
            rec_sigla_struttura = self.search_records(
                'sigla', self.DATA_LIST[0].sigla_struttura,
                'PYARCHINIT_THESAURUS_SIGLE')
            sigla_temp = self.DATA_LIST[0].sigla_struttura
            ptext = '<font size=14 ><b>Sigla: %s - Tipologia: %s</b><br/></font>' % (
                sigla_temp, rec_sigla_struttura[0].sigla_estesa)
            Story.append(Paragraph(ptext, styles["Normal"]))
            Story.append(Spacer(1, 12))
            #ptext = '<bullet>'
            #Story.append(Paragraph(ptext, styles["Normal"],bulletText='-'))

            # crea l'elenco delle sigle struttura presenti nel DB
            for rec in range(len(self.DATA_LIST)):
                if sigla_temp == self.DATA_LIST[rec].sigla_struttura:
                    rec_sigla_struttura = self.search_records(
                        'sigla', self.DATA_LIST[rec].sigla_struttura,
                        'PYARCHINIT_THESAURUS_SIGLE')
                    ptext = '<font size=12 ><b> Sigla: %s%s - Tipologia: %s </b></font>' % (
                        self.DATA_LIST[rec].sigla_struttura,
                        str(self.DATA_LIST[rec].numero_struttura),
                        rec_sigla_struttura[0].sigla_estesa)
                    Story.append(
                        Paragraph(ptext, styles["Normal"], bulletText='-'))
                    Story.append(Spacer(1, 12))
                    ptext = '<font size=12 > - Periodo: %s - Fase: %s<br/><br/></font>' % (
                        str(self.DATA_LIST[rec].periodo_iniziale),
                        str(self.DATA_LIST[rec].fase_iniziale))
                    Story.append(
                        Paragraph(ptext, styles["Normal"], bulletText='   '))
                    Story.append(Spacer(1, 12))
                else:
                    #ptext = '<bullet>'
                    #Story.append(Paragraph(ptext, styles["Normal"], bulletText='-'))
                    rec_sigla_struttura = self.search_records(
                        'sigla', self.DATA_LIST[rec].sigla_struttura,
                        'PYARCHINIT_THESAURUS_SIGLE')
                    sigla_temp = self.DATA_LIST[rec].sigla_struttura
                    ptext = '<font size=14 ><b>Sigla: %s - Tipologia: %s</b><br/></font>' % (
                        sigla_temp, rec_sigla_struttura[0].sigla_estesa)
                    Story.append(Paragraph(ptext, styles["Normal"]))
                    Story.append(Spacer(1, 12))
                    ptext = '<bullet>'
                    Story.append(Paragraph(ptext, styles["Normal"]))
                    ptext = '<font size=12 ><b>Sigla: %s - Tipologia: %s </b></font>' % (
                        self.DATA_LIST[rec].sigla_struttura,
                        str(self.DATA_LIST[rec].numero_struttura),
                        rec_sigla_struttura[0].sigla_estesa)
                    Story.append(
                        Paragraph(ptext, styles["Normal"], bulletText='-'))
                    Story.append(Spacer(1, 12))
                    ptext = '<font size=12 > - Periodo: %s - Fase: %s<br/><br/></font>' % (
                        str(self.DATA_LIST[rec].periodo_iniziale),
                        str(self.DATA_LIST[rec].fase_iniziale))
                    Story.append(
                        Paragraph(ptext, styles["Normal"], bulletText='   '))
                    Story.append(Spacer(1, 12))
            #ptext = '</bullet>'
            #Story.append(Paragraph(ptext, styles["Normal"]))

            # crea la descrizione e interpretazione delle singole strutture presenti nel DB
            ptext = '<font size=16 ><b>Descrizione singole strutture</b><br/></font>'
            Story.append(Paragraph(ptext, styles["Normal"]))
            Story.append(Spacer(1, 12))
            for rec in range(len(self.DATA_LIST)):
                rec_sigla_struttura = self.search_records(
                    'sigla', self.DATA_LIST[rec].sigla_struttura,
                    'PYARCHINIT_THESAURUS_SIGLE')
                ptext = '<font size=14 ><b>Sigla: %s%s - Tipologia: %s </b><br/><br/></font>' % (
                    self.DATA_LIST[rec].sigla_struttura,
                    str(self.DATA_LIST[rec].numero_struttura),
                    rec_sigla_struttura[0].sigla_estesa)
                Story.append(Paragraph(ptext, styles["Normal"]))
                ptext = '<font size=12 ><b>Descrizione</b><br/>%s<br/><b>Intepretazione</b><br/>%s<br/></font>' % (
                    str(self.DATA_LIST[rec].descrizione),
                    str(self.DATA_LIST[rec].interpretazione))
                Story.append(Paragraph(ptext, styles["Normal"]))
                Story.append(Spacer(1, 12))
        Story.append(PageBreak())

        # Titolo dati di cantiere
        ptext = '<font size=14 ><b>Dati Cantiere</b></font>'

        Story.append(Paragraph(ptext, styles["Normal"]))
        Story.append(Spacer(1, 12))

        # Descrizione dati di scavo
        ptext = """<font size=12>Direttore Cantiere: Fox Molder</font>"""  # % (magName, issueNum,subPrice,limitedDate,freeGift)
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 12))
        Story.append(PageBreak())

        # Titolo Catalogo Immagini 1
        styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
        ptext = '<font size=36><b>Catalogo Immagini</b></font>'

        Story.append(Paragraph(ptext, styles["Center"]))
        Story.append(Spacer(1, 20))
        Story.append(PageBreak())

        # Immagini
        home = os.environ['PYARCHINIT_HOME']

        home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder')
        logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg')
        logo = Image(logo_path)
        #logo = os.path.join(os.path.dirname(__file__), "..", "..", "iconadarte.png")
        #im = Image(logo)
        Story.append(logo)
        # Didascalia
        ptext = '<font size=10><b>Figura 1 - Esempio di foto</b></font>'

        Story.append(Paragraph(ptext, styles["Normal"]))
        Story.append(Spacer(1, 200))

        #logo = os.path.join(os.path.dirname(__file__), "..", "..", "iconadarte.png")
        #im = Image(logo)
        Story.append(logo)
        # Didascalia
        ptext = '<font size=10><b>Figura 2 - Esempio di foto</b></font>'

        Story.append(Paragraph(ptext, styles["Normal"]))
        Story.append(Spacer(1, 12))
        Story.append(PageBreak())

        # Titolo Allegato 1
        ptext = '<font size=36><b>Allegato 1</b></font>'

        Story.append(Paragraph(ptext, styles["Center"]))
        Story.append(Spacer(1, 20))

        # Titolo Allegato 1
        ptext = '<font size=36><b>Schede US</b></font>'

        Story.append(Paragraph(ptext, styles["Center"]))
        Story.append(Spacer(1, 50))

        # Chiusura del documento

        filename = '{}{}{}'.format(self.PDF_path, os.sep, 'relazione.pdf')
        f = open(filename, "wb")
        # doc = SimpleDocTemplate(f)
        # doc.build(elements, canvasmaker=NumberedCanvas_Periodizzazionesheet)

        doc = SimpleDocTemplate(f,
                                pagesize=A4,
                                rightMargin=72,
                                leftMargin=72,
                                topMargin=72,
                                bottomMargin=40)
        doc.build(Story,
                  canvasmaker=NumberedCanvas_Relazione,
                  onFirstPage=self.myFirstPage)
        f.close()
    def create_sheet(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  # Justified

        # format labels

        # 0 row
        intestazione = Paragraph(
            "<b>SCHEDA REPERTI LAPIDEI<br/>" + str(self.datestrfdate()) +
            "</b>", styNormal)
        # intestazione2 = Paragraph("<b>pyArchInit</b>", styNormal)

        home = os.environ['PYARCHINIT_HOME']

        home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder')
        alma_path = '{}{}{}'.format(home_DB_path, os.sep, 'alma.jpg')
        alma = Image(alma_path)

        ##		if test_image.drawWidth < 800:

        alma.drawHeight = 1.5 * inch * alma.drawHeight / alma.drawWidth
        alma.drawWidth = 1.5 * inch

        # 1 row
        sito = Paragraph("<b>Contesto/Provenienza</b><br/>" + str(self.sito),
                         styNormal)
        scheda_numero = Paragraph(
            "<b>Scheda Numero</b><br/>" + str(self.scheda_numero), styNormal)

        # 2 row
        collocazione = Paragraph(
            "<b>Collocazione</b><br/>" + str(self.collocazione), styNormal)

        # 3 row
        materiale = Paragraph("<b>Materiale</b><br/>" + self.materiale,
                              styNormal)

        # 4 row
        oggetto = Paragraph("<b>Oggetto</b><br/>" + str(self.oggetto),
                            styNormal)

        # 5 row
        tipologia = Paragraph("<b>Tipologia</b><br/>" + self.tipologia,
                              styNormal)

        # 6 row
        d_letto_posa = Paragraph(
            "<b>D (letto posa)</b><br/>" + self.d_letto_posa, styNormal)

        # 7 row
        d_letto_attesa = Paragraph(
            "<b>D (letto attesa)</b><br/>" + self.d_letto_attesa, styNormal)

        # 8 row
        toro = Paragraph("<b>Toro</b><br/>" + self.toro, styNormal)

        # 9 row
        spessore = Paragraph("<b>Spessore</b><br/>" + self.spessore, styNormal)

        # 10 row
        lunghezza = Paragraph("<b>Lunghezza</b><br/>" + self.lunghezza,
                              styNormal)

        # 11 row
        larghezza = Paragraph("<b>Larghezza</b><br/>" + self.larghezza,
                              styNormal)

        # 12 row
        h = Paragraph("<b>h</b><br/>" + self.h, styNormal)

        # 13row
        lavorazione_e_stato_di_conservazione = Paragraph(
            "<b>Lavorazione e stato di conservazione</b><br/>" +
            self.lavorazione_e_stato_di_conservazione, styNormal)

        # 14 row
        confronti = Paragraph("<b>Confronti</b><br/>" + self.confronti,
                              styNormal)

        # 15 row
        cronologia = Paragraph("<b>Cronologia</b><br/>" + self.cronologia,
                               styNormal)

        # 16 row
        compilatore = Paragraph("<b>Autore scheda</b><br/>" + self.compilatore,
                                styNormal)

        # 17 row
        descrizione = ''
        try:
            descrizione = Paragraph(
                "<b>Descrizione</b><br/>" + self.descrizione, styDescrizione)
        except:
            pass

            # 18 row
        bibliografia = ''
        if len(eval(self.bibliografia)) > 0:
            for i in eval(self.bibliografia):  # gigi
                if bibliografia == '':
                    try:
                        bibliografia += (
                            "<b>Autore: %s, Anno: %s, Titolo: %s, Pag.: %s, Fig.: %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]), str(
                            i[3]), str(i[4]))
                    except:
                        pass
                else:
                    try:
                        bibliografia += (
                            "<b>Autore: %s, Anno: %s, Titolo: %s, Pag.: %s, Fig.: %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]), str(
                            i[3]), str(i[4]))
                    except:
                        pass

        bibliografia = Paragraph("<b>Bibliografia</b><br/>" + bibliografia,
                                 styNormal)

        # schema
        cell_schema = [  # 00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                alma, '01', '02', '03', '04', '05', '06', intestazione, '08',
                '09'
            ],  # 0 row ok
            [
                sito, '01', '02', '03', '04', '05', '06', '07', scheda_numero,
                '09'
            ],  # 1 row ok
            [
                collocazione, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 2 row ok
            [materiale, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 3 row ok
            [oggetto, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 4 row ok
            [tipologia, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 5 row ok
            [
                d_letto_posa, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 6 row ok
            [
                d_letto_attesa, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 7 row ok
            [toro, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 8 row ok
            [spessore, '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 9 row ok
            [larghezza, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 10 row ok
            [lunghezza, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 11 row ok
            [h, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 12 row ok
            [
                descrizione, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 13 row ok
            [
                lavorazione_e_stato_di_conservazione, '01', '02', '03', '04',
                '05', '06', '07', '08', '09'
            ],
            # 14 row ok
            [confronti, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 15 row ok
            [cronologia, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 16 row ok
            [
                bibliografia, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 17 row ok
            [
                compilatore, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 18 row ok
        ]

        # table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            # 0 row
            ('SPAN', (0, 0), (6, 0)),  # intestazione
            ('SPAN', (7, 0), (9, 0)),  # logo

            # 1 row
            ('SPAN', (0, 1), (7, 1)),  # sito
            ('SPAN', (8, 1), (9, 1)),  # scheda numero

            # 2 row
            ('SPAN', (0, 2), (9, 2)),  # collocazione
            #					('VALIGN',(0,2),(9,2),'TOP'),

            # 3 row
            ('SPAN', (0, 3), (9, 3)),  # materiale

            # 4 row
            ('SPAN', (0, 4), (9, 4)),  # oggetto

            # 5row
            ('SPAN', (0, 5), (9, 5)),  # tipologia

            # 6 row
            ('SPAN', (0, 6), (9, 6)),  # d_letto_posa

            # 7 row
            ('SPAN', (0, 7), (9, 7)),  # d_letto_attesa

            # 8 row
            ('SPAN', (0, 8), (9, 8)),  # toro

            # 9 row
            ('SPAN', (0, 9), (9, 9)),  # spessore

            # 10 row
            ('SPAN', (0, 10), (9, 10)),  # larghezza

            # 11 row
            ('SPAN', (0, 11), (9, 11)),  # lunghezza

            # 12row
            ('SPAN', (0, 12), (9, 12)),  # h

            # 13 row
            ('SPAN', (0, 13), (9, 13)),  # descrizione

            # 14 row
            ('SPAN', (0, 14), (9, 14)),  # lavorazione

            # 15 row
            ('SPAN', (0, 15), (9, 15)),  # confronti

            # 16 row
            ('SPAN', (0, 16), (9, 16)),  # cronologia

            # 17 row
            ('SPAN', (0, 17), (9, 17)),  # bibliografia

            # 18 row
            ('SPAN', (0, 18), (9, 18)),  # autore scheda
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

        t = Table(cell_schema,
                  colWidths=50,
                  rowHeights=None,
                  style=table_style)

        return t
    def create_sheet(self):
        self.unzip_rapporti_stratigrafici()
        self.unzip_documentazione()

        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  #LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  #Justified

        #format labels

        #0 row
        intestazione = Paragraph(
            "<b>SCHEDA DI UNITA' STRATIGRAFICA<br/>" +
            str(self.datestrfdate()) + "</b>", styNormal)
        #intestazione2 = Paragraph("<b>Pyarchinit</b><br/>https://sites.google.com/site/pyarchinit/", styNormal)

        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)

        ##		if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        #1 row
        sito = Paragraph("<b>Sito</b><br/>" + str(self.sito), styNormal)
        area = Paragraph("<b>Area</b><br/>" + str(self.area), styNormal)
        us = Paragraph("<b>US</b><br/>" + str(self.us), styNormal)

        #2 row
        d_stratigrafica = Paragraph(
            "<b>Definizione stratigrafica</b><br/>" + self.d_stratigrafica,
            styNormal)
        d_interpretativa = Paragraph(
            "<b>Definizione Interpretativa</b><br/>" + self.d_interpretativa,
            styNormal)

        #3 row
        stato_conservazione = Paragraph(
            "<b>Stato di conservazione</b><br/>" + self.stato_di_conservazione,
            styNormal)
        consistenza = Paragraph("<b>Consistenza</b><br/>" + self.consistenza,
                                styNormal)
        colore = Paragraph("<b>Colore</b><br/>" + self.colore, styNormal)

        #4 row
        inclusi_list = eval(self.inclusi)
        inclusi = ''
        for i in eval(self.inclusi):
            if inclusi == '':
                try:
                    inclusi += str(i[0])
                except:
                    pass
            else:
                try:
                    inclusi += ', ' + str(i[0])
                except:
                    pass
        inclusi = Paragraph("<b>Inclusi</b><br/>" + inclusi, styNormal)
        campioni_list = eval(self.campioni)
        campioni = ''
        for i in eval(self.campioni):
            if campioni == '':
                try:
                    campioni += str(i[0])
                except:
                    pass
            else:
                try:
                    campioni += ', ' + str(i[0])
                except:
                    pass
        campioni = Paragraph("<b>Campioni</b><br/>" + campioni, styNormal)
        formazione = Paragraph("<b>Formazione</b><br/>" + self.formazione,
                               styNormal)

        #05 row
        descrizione = ''
        try:
            descrizione = Paragraph(
                "<b>Descrizione</b><br/>" + self.descrizione, styDescrizione)
        except:
            pass

        interpretazione = ''
        try:
            interpretazione = Paragraph(
                "<b>Interpretazione</b><br/>" + self.interpretazione,
                styDescrizione)
        except:
            pass

        #6 row
        attivita = Paragraph("<b>Attivita'</b><br/>" + self.attivita,
                             styNormal)
        struttura = Paragraph("<b>Struttura</b><br/>" + self.struttura,
                              styNormal)
        quota_min = Paragraph("<b>Quota Min:</b><br/>" + self.quota_min,
                              styNormal)
        quota_max = Paragraph("<b>Quota Max:</b><br/>" + self.quota_max,
                              styNormal)

        #7 row
        periodizzazione = Paragraph("<b>PERIODIZZAZIONE</b>", styNormal)

        #8 row
        iniziale = Paragraph("<b>INIZIALE</b>", styNormal)
        periodo_iniziale = Paragraph(
            "<b>Periodo</b><br/>" + self.periodo_iniziale, styNormal)
        fase_iniziale = Paragraph("<b>Fase</b><br/>" + self.fase_iniziale,
                                  styNormal)
        finale = Paragraph("<b>FINALE</b>", styNormal)
        periodo_finale = Paragraph("<b>Periodo</b><br/>" + self.periodo_finale,
                                   styNormal)
        fase_finale = Paragraph("<b>Fase</b><br/>" + self.fase_finale,
                                styNormal)

        #9 row
        rapporti_stratigrafici = Paragraph("<b>RAPPORTI STRATIGRAFICI</b>",
                                           styNormal)
        piante = Paragraph("<b>Planimetrie</b><br/>" + self.piante, styNormal)

        #10
        si_lega_a = Paragraph("<b>Si lega a</b><br/>" + self.si_lega_a,
                              styNormal)
        uguale_a = Paragraph("<b>Uguale a</b><br/>" + self.uguale_a, styNormal)

        #11
        copre = Paragraph("<b>Copre</b><br/>" + self.copre, styNormal)
        coperto_da = Paragraph("<b>Coperto da</b><br/>" + self.coperto_da,
                               styNormal)

        #12
        riempie = Paragraph("<b>Riempie</b><br/>" + self.riempie, styNormal)
        riempito_da = Paragraph("<b>Riempito da</b><br/>" + self.riempito_da,
                                styNormal)

        #13
        taglia = Paragraph("<b>Taglia</b><br/>" + self.taglia, styNormal)
        tagliato_da = Paragraph("<b>Tagliato da</b><br/>" + self.tagliato_da,
                                styNormal)

        #14
        si_appoggia_a = Paragraph(
            "<b>Si appoggia a</b><br/>" + self.si_appoggia_a, styNormal)
        gli_si_appoggia = Paragraph(
            "<b>Gli si appoggia</b><br/>" + self.gli_si_appoggia, styNormal)

        #15
        scavato = Paragraph("<b>Scavato</b><br/>" + self.scavato, styNormal)
        anno_di_scavo = Paragraph(
            "<b>Anno di scavo</b><br/>" + self.anno_scavo, styNormal)
        metodo_di_scavo = Paragraph(
            "<b>Metodo di scavo</b><br/>" + self.metodo_di_scavo, styNormal)
        data_schedatura = Paragraph(
            "<b>Data schedatura</b><br/>" + self.data_schedatura, styNormal)
        schedatore = Paragraph("<b>Schedatore</b><br/>" + self.schedatore,
                               styNormal)

        #16
        sing_doc = self.documentazione_print
        self.documentazione_print = Paragraph(
            "<b>Documentazione</b><br/>" + sing_doc, styNormal)

        #schema
        cell_schema = [
            #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                intestazione, '01', '02', '03', '04', '05', '06', logo, '08',
                '09'
            ],  #0 row ok
            [sito, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  #1 row ok
            [area, '01', '02', '03', '04', us, '06', '07', '08',
             '09'],  #2 row ok
            [
                d_stratigrafica, '01', '02', '03', '04', d_interpretativa,
                '06', '07', '08', '09'
            ],  #3 row ok
            [
                stato_conservazione, '01', '02', consistenza, '04', '05',
                colore, '07', '08', '09'
            ],  #4 row ok
            [
                inclusi, '01', '02', '03', campioni, '05', '06', '07',
                formazione, '09'
            ],  #5 row ok
            [
                descrizione, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  #6row ok
            [
                interpretazione, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #7 row ok
            [
                attivita, '01', '02', struttura, '04', '05', quota_min, '07',
                quota_max, '09'
            ],  #8 row
            [
                periodizzazione, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #9 row
            [
                iniziale, '01', periodo_iniziale, '03', fase_iniziale, finale,
                '06', periodo_finale, '08', fase_finale
            ],  #10 row
            [
                rapporti_stratigrafici, '01', '02', '03', '04', piante, '06',
                '07', '08', '09'
            ],  #11 row
            [
                si_lega_a, '01', '02', '03', '04', uguale_a, '06', '07', '08',
                '09'
            ],  #12 row
            [
                copre, '01', '02', '03', '04', coperto_da, '06', '07', '08',
                '09'
            ],  #13 row
            [
                riempie, '01', '02', '03', '04', riempito_da, '06', '07', '08',
                '09'
            ],  #14 row
            [
                taglia, '01', '02', '03', '04', tagliato_da, '06', '07', '08',
                '09'
            ],  #15 row
            [
                si_appoggia_a, '01', '02', '03', '04', gli_si_appoggia, '06',
                '07', '08', '09'
            ],  #16row
            [
                self.documentazione_print, '01', '02', '03', '04', '05', '06',
                '07', '08', '09'
            ],  #17 row
            [
                scavato, anno_di_scavo, '02', metodo_di_scavo, '04',
                data_schedatura, '06', schedatore, '08', '09'
            ]  #18 row
        ]

        #table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            #0 row
            ('SPAN', (0, 0), (6, 0)),  #intestazione
            ('SPAN', (7, 0), (9, 0)),  #intestazione

            #1 row
            ('SPAN', (0, 1), (9, 1)),  #dati identificativi

            #2 row
            ('SPAN', (0, 2), (4, 2)),  #dati identificativi
            ('SPAN', (5, 2), (9, 2)),  #dati identificativi

            #3 row
            ('SPAN', (0, 3), (4, 3)),  #Definizione - interpretazone
            ('SPAN', (5, 3), (9, 3)),  #definizione - intepretazione

            #3 row
            ('SPAN', (0, 4), (2, 4)),  #conservazione - consistenza - colore
            ('SPAN', (3, 4), (5, 4)),  #conservazione - consistenza - colore
            ('SPAN', (6, 4), (9, 4)),  #conservazione - consistenza - colore

            #4 row
            ('SPAN', (0, 5), (3, 5)),  #inclusi - campioni - formazione
            ('SPAN', (4, 5), (7, 5)),  #inclusi - campioni - formazione
            ('SPAN', (8, 5), (9, 5)),  #inclusi - campioni - formazione

            #5 row
            ('SPAN', (0, 6), (9, 6)),  #descrizione
            ('SPAN', (0, 7), (9, 7)),  #interpretazione #6 row
            ('VALIGN', (0, 6), (9, 6), 'TOP'),

            #7 row
            ('SPAN', (0, 8), (2, 8)
             ),  #Attivita - Struttura - Quota min - Quota max
            ('SPAN', (3, 8),
             (5, 8)),  #Attivita - Struttura - Quota min - Quota max
            ('SPAN', (6, 8),
             (7, 8)),  #Attivita - Struttura - Quota min - Quota max
            ('SPAN', (8, 8),
             (9, 8)),  #Attivita - Struttura - Quota min - Quota max

            #8 row
            ('SPAN', (0, 9), (9, 9)),  #Periodizzazione - Titolo

            #8 row
            ('SPAN', (0, 10), (1, 10)),  #iniziale
            ('SPAN', (2, 10), (3, 10)),  #periodo inizlae
            ('SPAN', (5, 10), (6, 10)),  #fase iniziale
            ('SPAN', (7, 10), (8, 10)),  #finale
            ('VALIGN', (0, 10), (0, 10), 'TOP'),
            ('VALIGN', (5, 10), (5, 10), 'TOP'),

            #9 row
            ('SPAN', (0, 11), (4, 11)),  #Rapporti stratigrafici - Titolo
            ('SPAN', (5, 11), (9, 11)),  #Piante - Titolo

            #10 row
            ('SPAN', (0, 12), (4, 12)
             ),  #Rapporti stratigrafici - Si lega a - Uguale a
            ('SPAN', (5, 12),
             (9, 12)),  #Rapporti stratigrafici - Si lega a - Uguale a

            #11 row
            ('SPAN', (0, 13), (4, 13)
             ),  #Rapporti stratigrafici - Copre - Coperto da
            ('SPAN', (5, 13),
             (9, 13)),  #Rapporti stratigrafici - Copre - Coperto da

            #12 row
            ('SPAN', (0, 14), (4, 14)
             ),  #Rapporti stratigrafici - Riempie - Riempito da
            ('SPAN', (5, 14),
             (9, 14)),  #Rapporti stratigrafici - Riempie - Riempito da

            #13 row
            ('SPAN', (0, 15), (4, 15)
             ),  #Rapporti stratigrafici - Taglia - Tagliato da
            ('SPAN', (5, 15),
             (9, 15)),  #Rapporti stratigrafici - Taglia - Tagliato da

            #14 row
            ('SPAN', (0, 16), (4, 16)
             ),  #Rapporti stratigrafici - Si appoggia a - Gli si appoggia
            ('SPAN', (5, 16),
             (9,
              16)),  #Rapporti stratigrafici - Si appoggia a - Gli si appoggia
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),

            #16 row
            ('SPAN', (0, 17), (9, 17)),  #pie' di pagina
            ('ALIGN', (0, 17), (9, 17), 'CENTER'),

            #15 row
            ('SPAN', (1, 18), (2, 18)
             ),  #scavato anno_di_scavo - metodo_di_scavo, data_schedatura
            ('SPAN', (3, 18),
             (4,
              18)),  #scavato anno_di_scavo - metodo_di_scavo, data_schedatura
            ('SPAN', (5, 18),
             (6,
              18)),  #scavato anno_di_scavo - metodo_di_scavo, data_schedatura
            ('SPAN', (7, 18),
             (9,
              18)),  #scavato anno_di_scavo - metodo_di_scavo, data_schedatura
        ]

        t = Table(cell_schema,
                  colWidths=55,
                  rowHeights=None,
                  style=table_style)

        return t
Example #46
0
    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('&', '&amp;')

        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_sheet_en(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  # Justified
        """
        #format labels
        self.id_scheda_ind = data[0]
        self.sito = data[1]
        self.area = data[2]
        self.us = data[3]
        self.nr_individuo = data[4]
        self.data_schedatura = data[5]
        self.schedatore = data[6]
        self.sesso = data[7]
        self.eta_min = data[8]
        self.eta_max =  data[9]
        self.classi_eta = data[10]
        self.osservazioni = data[11]
        """
        # 0 row
        intestazione = Paragraph(
            "<b>INDIVIDUAL FORM<br/>" + str(self.datestrfdate()) + "</b>",
            styNormal)
        # intestazione2 = Paragraph("<b>pyArchInit</b>", styNormal)

        home = os.environ['PYARCHINIT_HOME']

        home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder')
        logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg')
        logo = Image(logo_path)

        ##      if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        # 1 row
        sito = Paragraph("<b>Site</b><br/>" + str(self.sito), styNormal)
        area = Paragraph("<b>Area</b><br/>" + str(self.area), styNormal)
        us = Paragraph("<b>SU</b><br/>" + str(self.us), styNormal)
        nr_inventario = Paragraph(
            "<b>Individual Nr.</b><br/>" + str(self.nr_individuo), styNormal)

        # 2 row
        sesso = Paragraph("<b>Sex</b><br/>" + self.sesso, styNormal)

        if str(self.eta_min) == "None":
            eta_min = Paragraph("<b>Age min</b><br/>", styNormal)
        else:
            eta_min = Paragraph("<b>Age min</b><br/>" + str(self.eta_min),
                                styNormal)

        if str(self.eta_max) == "None":
            eta_max = Paragraph("<b>Age max</b><br/>", styNormal)
        else:
            eta_max = Paragraph("<b>Age max</b><br/>" + str(self.eta_max),
                                styNormal)

            # 3 row
        classi_eta_string = str(self.classi_eta).replace("<", "&lt;")
        # classi_eta = Paragraph(classi_eta_string, styNormal)
        classi_eta = Paragraph("<b>Age class</b><br/>" + classi_eta_string,
                               styNormal)

        # 4 row
        osservazioni = ''
        try:
            osservazioni = Paragraph(
                "<b>Notes</b><br/>" + str(self.osservazioni), styDescrizione)
        except:
            pass

            # 12 row
        data_schedatura = Paragraph("<b>Date</b><br/>" + self.data_schedatura,
                                    styNormal)
        schedatore = Paragraph("<b>Filler</b><br/>" + self.schedatore,
                               styNormal)

        # schema
        cell_schema = [  # 00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                intestazione, '01', '02', '03', '04', '05', '06', logo, '08',
                '09'
            ],
            [sito, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 1 row ok
            [
                area, '01', '02', us, '04', '05', nr_inventario, '07', '08',
                '09'
            ],  # 2row ok
            [
                sesso, '01', '02', eta_min, '04', '05', eta_max, '07', '08',
                '09'
            ],  # 3row ok
            [classi_eta, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 4 row ok
            [
                osservazioni, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 5 row ok
            [
                data_schedatura, '01', '02', '03', '04', '05', schedatore,
                '07', '08', '09'
            ]  # 5 row ok
            # ['https://sites.google.com/site/pyarchinit/', '01', '02', '03', '04','05', '06', '07','08', '09'] #6 row
        ]

        # table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            # 0 row
            ('SPAN', (0, 0), (6, 0)),  # intestazione
            ('SPAN', (7, 0), (9, 0)),  # intestazione2

            # 1 row
            ('SPAN', (0, 1), (9, 1)),  # sito

            # 2 row
            ('SPAN', (0, 2), (2, 2)),  # area
            ('SPAN', (3, 2), (5, 2)),  # us
            ('SPAN', (6, 2), (9, 2)),  # nr_inventario

            # 2 row
            ('SPAN', (0, 3), (2, 3)),  # sesso
            ('SPAN', (3, 3), (5, 3)),  # eta_min
            ('SPAN', (6, 3), (9, 3)),  # eta_max
            ('VALIGN', (0, 3), (9, 3), 'TOP'),

            # 3 row
            ('SPAN', (0, 4), (9, 4)),  # classi_eta

            # 4 row
            ('SPAN', (0, 5), (9, 5)),  # osservazioni

            # 5 row
            ('SPAN', (0, 6), (5, 6)),  # data_schedatura
            ('SPAN', (6, 6), (9, 6)),  # schedatore
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

        t = Table(cell_schema,
                  colWidths=50,
                  rowHeights=None,
                  style=table_style)

        return t
	def create_sheet(self):
		self.unzip_rapporti_stratigrafici()
		self.unzip_documentazione()

		styleSheet = getSampleStyleSheet()
		styNormal = styleSheet['Normal']
		styNormal.spaceBefore = 20
		styNormal.spaceAfter = 20
		styNormal.alignment = 0 #LEFT
		
		
		styleSheet = getSampleStyleSheet()
		styDescrizione = styleSheet['Normal']
		styDescrizione.spaceBefore = 20
		styDescrizione.spaceAfter = 20
		styDescrizione.alignment = 4 #Justified
		
		
		#format labels

		#0 row
		intestazione = Paragraph("<b>SCHEDA DI UNITA' STRATIGRAFICA<br/>" + str(self.datestrfdate()) + "</b>", styNormal)
		#intestazione2 = Paragraph("<b>Pyarchinit</b><br/>https://sites.google.com/site/pyarchinit/", styNormal)

		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)

		##		if test_image.drawWidth < 800:

		logo.drawHeight = 1.5*inch*logo.drawHeight / logo.drawWidth
		logo.drawWidth = 1.5*inch


		#1 row
		sito = Paragraph("<b>Sito</b><br/>"  + str(self.sito), styNormal)
		area = Paragraph("<b>Area</b><br/>"  + str(self.area), styNormal)
		us = Paragraph("<b>US</b><br/>"  + str(self.us), styNormal)

		#2 row
		d_stratigrafica = Paragraph("<b>Definizione stratigrafica</b><br/>"  + self.d_stratigrafica, styNormal)
		d_interpretativa = Paragraph("<b>Definizione Interpretativa</b><br/>"  + self.d_interpretativa, styNormal)

		#3 row
		stato_conservazione = Paragraph("<b>Stato di conservazione</b><br/>" + self.stato_di_conservazione, styNormal)
		consistenza = Paragraph("<b>Consistenza</b><br/>"  + self.consistenza, styNormal)
		colore = Paragraph("<b>Colore</b><br/>"  + self.colore, styNormal)

		#4 row
		inclusi_list = eval(self.inclusi)
		inclusi = ''
		for i in eval(self.inclusi):
			if inclusi == '':
				try:
					inclusi += str(i[0])
				except:
					pass
			else:
				try:
					inclusi += ', ' + str(i[0])
				except:
					pass
		inclusi = Paragraph("<b>Inclusi</b><br/>"  + inclusi, styNormal)
		campioni_list = eval(self.campioni)
		campioni = ''
		for i in eval(self.campioni):
			if campioni == '':
				try:
					campioni += str(i[0])
				except:
					pass
			else:
				try:
					campioni += ', ' + str(i[0])
				except:
					pass
		campioni = Paragraph("<b>Campioni</b><br/>"  + campioni, styNormal)
		formazione = Paragraph("<b>Formazione</b><br/>"  + self.formazione, styNormal)

		#05 row
		descrizione = ''
		try:
			descrizione = Paragraph("<b>Descrizione</b><br/>" + self.descrizione, styDescrizione)
		except:
			pass

		interpretazione = ''
		try:
			interpretazione = Paragraph("<b>Interpretazione</b><br/>" + self.interpretazione,styDescrizione)
		except:
			pass

		#6 row
		attivita = Paragraph("<b>Attivita'</b><br/>" + self.attivita,styNormal)
		struttura = Paragraph("<b>Struttura</b><br/>" + self.struttura,styNormal)
		quota_min = Paragraph("<b>Quota Min:</b><br/>"+ self.quota_min,styNormal)
		quota_max = Paragraph("<b>Quota Max:</b><br/>"+ self.quota_max,styNormal)
		
		#7 row
		periodizzazione = Paragraph("<b>PERIODIZZAZIONE</b>",styNormal)

		#8 row
		iniziale = Paragraph("<b>INIZIALE</b>",styNormal)
		periodo_iniziale = Paragraph("<b>Periodo</b><br/>" + self.periodo_iniziale,styNormal)
		fase_iniziale = Paragraph("<b>Fase</b><br/>" + self.fase_iniziale,styNormal)
		finale = Paragraph("<b>FINALE</b>",styNormal)
		periodo_finale = Paragraph("<b>Periodo</b><br/>" + self.periodo_finale,styNormal)
		fase_finale = Paragraph("<b>Fase</b><br/>" + self.fase_finale,styNormal)

		#9 row
		rapporti_stratigrafici = Paragraph("<b>RAPPORTI STRATIGRAFICI</b>",styNormal)
		piante = Paragraph("<b>Planimetrie</b><br/>" + self.piante,styNormal)

		#10
		si_lega_a = Paragraph("<b>Si lega a</b><br/>" + self.si_lega_a,styNormal)
		uguale_a = Paragraph("<b>Uguale a</b><br/>" + self.uguale_a,styNormal)

		#11
		copre = Paragraph("<b>Copre</b><br/>" + self.copre,styNormal)
		coperto_da = Paragraph("<b>Coperto da</b><br/>" + self.coperto_da,styNormal)

		#12
		riempie = Paragraph("<b>Riempie</b><br/>" + self.riempie,styNormal)
		riempito_da = Paragraph("<b>Riempito da</b><br/>" + self.riempito_da,styNormal)

		#13
		taglia = Paragraph("<b>Taglia</b><br/>" + self.taglia,styNormal)
		tagliato_da = Paragraph("<b>Tagliato da</b><br/>" + self.tagliato_da,styNormal)

		#14
		si_appoggia_a = Paragraph("<b>Si appoggia a</b><br/>" + self.si_appoggia_a,styNormal)
		gli_si_appoggia = Paragraph("<b>Gli si appoggia</b><br/>" + self.gli_si_appoggia,styNormal)

		#15
		scavato = Paragraph("<b>Scavato</b><br/>" + self.scavato,styNormal)
		anno_di_scavo = Paragraph("<b>Anno di scavo</b><br/>" + self.anno_scavo,styNormal)
		metodo_di_scavo = Paragraph("<b>Metodo di scavo</b><br/>" + self.metodo_di_scavo,styNormal)
		data_schedatura  = Paragraph("<b>Data schedatura</b><br/>" + self.data_schedatura,styNormal)
		schedatore = Paragraph("<b>Schedatore</b><br/>" + self.schedatore,styNormal)
		
		#16
		sing_doc = self.documentazione_print
		self.documentazione_print = Paragraph("<b>Documentazione</b><br/>"  + sing_doc, styNormal) 

		#schema
		cell_schema =  [
						#00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
						[intestazione, '01', '02', '03', '04','05', '06', logo, '08', '09'], #0 row ok
						[sito, '01', '02', '03', '04', '05', '06', '07', '08', '09'], #1 row ok
						[area, '01', '02', '03', '04', us, '06', '07','08', '09'], #2 row ok
						[d_stratigrafica, '01', '02','03','04', d_interpretativa,'06', '07', '08', '09'], #3 row ok
						[stato_conservazione, '01', '02', consistenza,'04', '05', colore, '07', '08', '09'], #4 row ok
						[inclusi, '01', '02', '03', campioni, '05', '06', '07', formazione, '09'], #5 row ok
						[descrizione, '01','02', '03', '04','05', '06', '07', '08', '09'], #6row ok
						[interpretazione, '01','02', '03', '04','05', '06', '07', '08', '09'], #7 row ok
						[attivita, '01', '02', struttura,'04', '05', quota_min, '07', quota_max, '09'], #8 row
						[periodizzazione, '01', '02', '03', '04', '05', '06', '07', '08', '09'], #9 row
						[iniziale, '01', periodo_iniziale, '03', fase_iniziale, finale, '06',periodo_finale, '08', fase_finale], #10 row
						[rapporti_stratigrafici, '01', '02', '03', '04', piante, '06', '07', '08', '09'], #11 row
						[si_lega_a, '01', '02', '03', '04', uguale_a, '06', '07', '08', '09'], #12 row
						[copre, '01', '02', '03', '04', coperto_da, '06', '07', '08', '09'], #13 row
						[riempie, '01', '02', '03', '04', riempito_da, '06', '07', '08', '09'], #14 row
						[taglia, '01', '02', '03', '04', tagliato_da, '06', '07', '08', '09'], #15 row
						[si_appoggia_a, '01', '02', '03', '04', gli_si_appoggia, '06', '07', '08', '09'], #16row
						[self.documentazione_print, '01', '02', '03', '04','05', '06', '07','08', '09'], #17 row
						[scavato, anno_di_scavo, '02', metodo_di_scavo, '04', data_schedatura, '06', schedatore, '08', '09'] #18 row
						]

		#table style
		table_style=[
					('GRID',(0,0),(-1,-1),0.5,colors.black),
					#0 row
					('SPAN', (0,0),(6,0)),  #intestazione
					('SPAN', (7,0),(9,0)),  #intestazione

					#1 row
					('SPAN', (0,1),(9,1)),  #dati identificativi

					#2 row
					('SPAN', (0,2),(4,2)),  #dati identificativi
					('SPAN', (5,2),(9,2)),  #dati identificativi

					#3 row
					('SPAN', (0,3),(4,3)),  #Definizione - interpretazone
					('SPAN', (5,3),(9,3)),  #definizione - intepretazione

					#3 row
					('SPAN', (0,4),(2,4)),  #conservazione - consistenza - colore
					('SPAN', (3,4),(5,4)),  #conservazione - consistenza - colore
					('SPAN', (6,4),(9,4)),  #conservazione - consistenza - colore

					#4 row
					('SPAN', (0,5),(3,5)),  #inclusi - campioni - formazione
					('SPAN', (4,5),(7,5)),  #inclusi - campioni - formazione
					('SPAN', (8,5),(9,5)),  #inclusi - campioni - formazione

					#5 row
					('SPAN', (0,6),(9,6)),  #descrizione
					('SPAN', (0,7),(9,7)),  #interpretazione #6 row
					('VALIGN',(0,6),(9,6),'TOP'), 

					#7 row
					('SPAN', (0,8),(2,8)),  #Attivita - Struttura - Quota min - Quota max
					('SPAN', (3,8),(5,8)),  #Attivita - Struttura - Quota min - Quota max
					('SPAN', (6,8),(7,8)),  #Attivita - Struttura - Quota min - Quota max
					('SPAN', (8,8),(9,8)),  #Attivita - Struttura - Quota min - Quota max

					#8 row
					('SPAN', (0,9),(9,9)),  #Periodizzazione - Titolo

					#8 row
					('SPAN', (0,10),(1,10)),  #iniziale
					('SPAN', (2,10),(3,10)),  #periodo inizlae
					('SPAN', (5,10),(6,10)),  #fase iniziale
					('SPAN', (7,10),(8,10)),  #finale
					('VALIGN',(0,10),(0,10),'TOP'), 
					('VALIGN',(5,10),(5,10),'TOP'), 
					
					#9 row
					('SPAN', (0,11),(4,11)),  #Rapporti stratigrafici - Titolo
					('SPAN', (5,11),(9,11)),  #Piante - Titolo

					#10 row
					('SPAN', (0,12),(4,12)),  #Rapporti stratigrafici - Si lega a - Uguale a
					('SPAN', (5,12),(9,12)),  #Rapporti stratigrafici - Si lega a - Uguale a

					#11 row
					('SPAN', (0,13),(4,13)),  #Rapporti stratigrafici - Copre - Coperto da
					('SPAN', (5,13),(9,13)),  #Rapporti stratigrafici - Copre - Coperto da

					#12 row
					('SPAN', (0,14),(4,14)),  #Rapporti stratigrafici - Riempie - Riempito da
					('SPAN', (5,14),(9,14)),  #Rapporti stratigrafici - Riempie - Riempito da

					#13 row
					('SPAN', (0,15),(4,15)),  #Rapporti stratigrafici - Taglia - Tagliato da
					('SPAN', (5,15),(9,15)),  #Rapporti stratigrafici - Taglia - Tagliato da

					#14 row
					('SPAN', (0,16),(4,16)),  #Rapporti stratigrafici - Si appoggia a - Gli si appoggia
					('SPAN', (5,16),(9,16)),  #Rapporti stratigrafici - Si appoggia a - Gli si appoggia

					('VALIGN',(0,0),(-1,-1),'TOP'),

					#16 row
					('SPAN', (0,17),(9,17)),  #pie' di pagina
					('ALIGN',(0,17),(9,17),'CENTER'),

					#15 row
					('SPAN', (1,18),(2,18)),  #scavato anno_di_scavo - metodo_di_scavo, data_schedatura
					('SPAN', (3,18),(4,18)),  #scavato anno_di_scavo - metodo_di_scavo, data_schedatura
					('SPAN', (5,18),(6,18)),  #scavato anno_di_scavo - metodo_di_scavo, data_schedatura
					('SPAN', (7,18),(9,18)),  #scavato anno_di_scavo - metodo_di_scavo, data_schedatura
					]


		t=Table(cell_schema, colWidths=55, rowHeights=None,style= table_style)

		return t
Example #49
0
    l, a = pdf.tamanho(componente, 1)
    l += 2 * pdf.espacamento
    a += 2 * pdf.espacamento + .3 * a
    pdf.celula( l, a, None, [componente], posicao = (20 * cm - l, 28.7 * cm - a), borda= True)
    pdf.celula( 5 * cm, 1 * cm, 'Teste', '1')
    pdf.celula(15 * cm, 2 * cm, 'Teste', '2')
    pdf.celula( 4 * cm, 5 * cm, 'Teste', '3')
    pdf.celula(10 * cm, 1 * cm, 'Teste', '4')
    pdf.celula( 5 * cm, 5 * cm, 'Teste', '5')
    pdf.celula( 4 * cm, 3 * cm, 'Teste', '6')
    pdf.celula( 7 * cm, 1 * cm, 'Teste', '7')

    # Renderiza uma imagem
    img = Image(logo)
    largura = 5 * cm   # redimensionar imagem para 5 cm de largura
    img.drawHeight = largura * img.drawHeight / img.drawWidth
    img.drawWidth = largura
    pdf.celula(largura, 1, None, [img])
    # Renderiza uma célula texto com título e outra sem título
    pdf.celula(10 * cm, 1, 'Título da célula', 'Texto de conteúdo da célula')
    pdf.celula(10 * cm, 1, '', 'Texto de conteúdo da célula sem título')
    # Renderiza uma tabela simples
    estilo = [('GRID', (0,0), (-1,-1),0.5, colors.black),
              ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
              ('TOPPADDING', (0,0), (-1,-1), 0),
              ('RIGHTPADDING', (0,0), (-1,-1), 1*mm),
              ('LEFTPADDING', (0,0), (-1,-1), 1*mm),
              ('FONTSIZE', (0,0), (-1,-1), normal_centro.fontSize),
              ('LEADING', (0,0), (-1,-1), normal_centro.leading),
              ('BOTTOMPADDING', (0,0), (-1,-1), 1)]
    dados = [[123, 'Hora 1', 5465, 123465, 1, 2, 3, 4, True] ,
	def create_sheet(self):
		styleSheet = getSampleStyleSheet()
		styNormal = styleSheet['Normal']
		styNormal.spaceBefore = 20
		styNormal.spaceAfter = 20
		styNormal.alignment = 0 #LEFT

		styleSheet = getSampleStyleSheet()
		styDescrizione = styleSheet['Normal']
		styDescrizione.spaceBefore = 20
		styDescrizione.spaceAfter = 20
		styDescrizione.alignment = 4 #Justified

		#format labels

		#0 row
		intestazione = Paragraph("<b>SCHEDA TAFONOMICA<br/>" + str(self.datestrfdate()) + "</b>", styNormal)

		
		#intestazione2 = Paragraph("<b>pyArchInit</b><br/>pyarchinit", styNormal)
		
		#intestazione2  = Paragraph("<b>Ditta esecutrice</b><br/>", styNormal)
		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)

		##		if test_image.drawWidth < 800:

		logo.drawHeight = 1.5*inch*logo.drawHeight / logo.drawWidth
		logo.drawWidth = 1.5*inch

		#1 row
		sito = Paragraph("<b>Sito</b><br/>"  + str(self.sito), styNormal)
		sigla_struttura = Paragraph("<b>Sigla struttura</b><br/>"  + str(self.sigla_struttura)+str(self.nr_struttura), styNormal)
		nr_individuo = Paragraph("<b>Nr. Individuo</b><br/>"  + str(self.nr_individuo), styNormal)
		nr_scheda = Paragraph("<b>Nr. Scheda</b><br/>"  + str(self.nr_scheda_taf), styNormal)

		#2 row
		periodizzazione = Paragraph("<b>PERIODIZZAZIONE DEL RITO DI SEPOLTURA</b><br/>", styNormal)

		#3 row
		if  str(self.periodo_iniziale) == "None":
			periodo_iniziale = Paragraph("<b>Periodo iniziale</b><br/>", styNormal)
		else:
			periodo_iniziale = Paragraph("<b>Periodo iniziale</b><br/>" + str(self.periodo_iniziale), styNormal)
		
		if  str(self.fase_iniziale) == "None":
			fase_iniziale = Paragraph("<b>Fase iniziale</b><br/>", styNormal)
		else:
			fase_iniziale = Paragraph("<b>Fase iniziale</b><br/>" + str(self.fase_iniziale), styNormal)

		if  str(self.periodo_finale) == "None":
			periodo_finale = Paragraph("<b>Periodo finale</b><br/>", styNormal)
		else:
			periodo_finale = Paragraph("<b>Periodo finale</b><br/>" + str(self.periodo_finale), styNormal)
			

		if  str(self.fase_finale) == "None":
			fase_finale = Paragraph("<b>Fase finale</b><br/>", styNormal)
		else:
			fase_finale = Paragraph("<b>Fase finale</b><br/>" + str(self.fase_finale), styNormal)

		#4 row
		if  str(self.datazione_estesa) == "None":
			datazione_estesa = Paragraph("<b>Datazione estesa</b><br/>", styNormal)
		else:
			datazione_estesa = Paragraph("<b>Datazione estesa</b><br/>" + str(self.datazione_estesa), styNormal)

		#5 row
		elementi_strutturali = Paragraph("<b>ELEMENTI STRUTTURALI</b></b>",styNormal)

		#6row
		tipo_contenitore_resti = Paragraph("<b>Tipo contenitore resti</b><br/>"  + str(self.tipo_contenitore_resti), styNormal)
		tipo_copertura = Paragraph("<b>Tipo copertura</b><br/>"  + str(self.copertura_tipo), styNormal)
		segnacoli = Paragraph("<b>Segnacoli</b><br/>"  + str(self.segnacoli), styNormal)
		canale_libatorio = Paragraph("<b>Canale libatorio</b><br/>"  + str(self.canale_libatorio_si_no), styNormal)

		#7 row
		dati_deposizionali = Paragraph("<b>DATI DEPOSIZIONALI INUMATO<b></b>",styNormal)

		#8 row
		rito = Paragraph("<b>Rito</b><br/>"  + self.rito, styNormal)
		orientamento_asse = Paragraph("<b>Orientamento asse</b><br/>"  + str(self.orientamento_asse), styNormal)
		if str(self.orientamento_azimut) == "None":
			orientamento_azimut = Paragraph("<b>Azimut</b><br/>", styNormal)
		else:
			orientamento_azimut_conv = self.PU.conversione_numeri(self.orientamento_azimut)
			orientamento_azimut = Paragraph("<b>Azimut</b><br/>"  + orientamento_azimut_conv + "°", styNormal)
		posizione_cranio = Paragraph("<b>Posizione cranio</b><br/>"  +  str(self.posizione_cranio), styNormal)

		#9 row
		posizione_scheletro = Paragraph("<b>Posizione scheletro</b><br/>"  + str(self.posizione_scheletro), styNormal)
		if str(self.lunghezza_scheletro) == "None":
			lunghezza_scheletro = Paragraph("<b>Lunghezza scheletro</b><br/>", styNormal)
		else:
			lunghezza_scheletro_conv = self.PU.conversione_numeri(self.lunghezza_scheletro)
			lunghezza_scheletro = Paragraph("<b>Lunghezza scheletro</b><br/>"  + lunghezza_scheletro_conv +" m", styNormal)
		posizione_arti_superiori = Paragraph("<b>Posizione arti superiori</b><br/>"  + str(self.posizione_arti_superiori), styNormal)
		posizione_arti_inferiori = Paragraph("<b>Posizione arti inferiori</b><br/>"  + str(self.posizione_arti_inferiori), styNormal)

		#10 row
		dati_postdeposizionali = Paragraph("<b>DATI POSTDEPOSIZIONALI<b></b>",styNormal)

		#11 row
		stato_conservazione = Paragraph("<b>Stato di conservazione</b><br/>"  + str(self.stato_di_conservazione), styNormal)
		disturbato = Paragraph("<b>Disturbato</b><br/>"  + str(self.segnacoli), styNormal)
		completo = Paragraph("<b>Completo</b><br/>"  + str(self.canale_libatorio_si_no), styNormal)
		in_connessione = Paragraph("<b>In connessione</b><br/>"  + str(self.oggetti_rinvenuti_esterno), styNormal)

		#12 row
		caratteristiche_tafonomiche = ''
		caratteristiche_list = eval(self.caratteristiche)
		if len(caratteristiche_list) > 0 :
			for i in caratteristiche_list:
				if caratteristiche_tafonomiche == '':
					caratteristiche_tafonomiche = ("Tipo caratteristica: %s, posizione: %s") % (str(i[0]), str(i[1]))
				else:
					caratteristiche_tafonomiche += ("<br/>Tipo caratteristica: %s, posizione: %s") % (str(i[0]), str(i[1]))

		caratteristiche_tafonomiche_txt = Paragraph("<b>CARATTERISTICHE TAFONOMICHE</b><br/>"  + caratteristiche_tafonomiche, styNormal)


		#13 row
		descrizione = ''
		try:
			descrizione = Paragraph("<b>Descrizione</b><br/>" + str(self.descrizione_taf), styDescrizione)
		except:
			pass

		interpretazione = ''
		try:
			interpretazione = Paragraph("<b>Interpretazione</b><br/>" + str(self.interpretazione_taf),styDescrizione)
		except:
			pass
		
		#14 row
		corredo = Paragraph("<b>CORREDO</b></b>",styNormal)

		#15 row
		corredo_presente = Paragraph("<b>Presenza</b><br/>" + str(self.corredo_presenza),styDescrizione)
		
		#16 row
		corredo_descrizione = Paragraph("<b>Descrizione</b><br/>" + str(self.corredo_descrizione),styDescrizione)

		#17 row
		corredo_tipo = ''
		if eval(self.corredo_tipo) > 0 :
			for i in eval(self.corredo_tipo):
				if corredo_tipo == '':
					try:
						corredo_tipo += ("Nr. reperto %s, tipo corredo: %s, descrizione: %s") % (str(i[0]), str(i[1]), str(i[2]))
					except:
						pass
				else:
					try:
						corredo_tipo += ("<br/>Nr. reperto %s, tipo corredo: %s, descrizione: %s") % (str(i[0]), str(i[1]), str(i[2]))
					except:
						pass

		corredo_tipo_txt = Paragraph("<b>Singoli oggetti di corredo</b><br/>"  + corredo_tipo, styNormal)
		
		#18 row
		misure_tafonomia = ''
		if eval(self.misure_tafonomia) > 0 :
			for i in eval(self.misure_tafonomia):
				if misure_tafonomia == '':
					try:
						misure_tafonomia += ("%s: %s %s") % (str(i[0]), str(i[2]), str(i[1]))
					except:
						pass
				else:
					try:
						misure_tafonomia += ("<br/>%s: %s %s") % (str(i[0]), str(i[2]), str(i[1]))
					except:
						pass

		misure_tafonomia_txt = Paragraph("<b>Misurazioni</b><br/>"  + misure_tafonomia, styNormal)

		#19 row
		quote_tafonomia = Paragraph("<b>QUOTE INDIVIDUO E STRUTTURA</b><br/>", styNormal)

		#20 row
		quota_min_ind = Paragraph("<b>Quota min individuo</b><br/>" + str(self.quota_min_ind), styNormal)
		quota_max_ind = Paragraph("<b>Quota max individuo</b><br/>" + str(self.quota_max_ind), styNormal)
		quota_min_strutt = Paragraph("<b>Quota min struttura</b><br/>" + str(self.quota_min_strutt), styNormal)
		quota_max_strutt = Paragraph("<b>Quota max struttura</b><br/>" + str(self.quota_max_strutt), styNormal)


		#schema
		cell_schema =  [ #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
						[intestazione, '01', '02', '03', '04','05', '06', logo, '08', '09'], #0 row  ok
						[sito, '01', '02', '03', '04', sigla_struttura, '06', '07',nr_individuo,nr_scheda], #1 row ok
						[periodizzazione, '01', '02', '03', '04', '07', '06', '07','08', '09'], #2 row ok
						[periodo_iniziale, '01', '02', fase_iniziale, '04', periodo_finale, '06', fase_finale,'08','09'], #3 row ok
						[datazione_estesa, '01', '02', '03', '04', '07', '06', '07','08', '09'], #4 row ok
						[elementi_strutturali, '01', '02', '03', '04', '07', '06', '07','08', '09'], #5 row ok
						[tipo_contenitore_resti, '01', '02', tipo_copertura,'04', segnacoli,'06', canale_libatorio, '08'], #6 row ok
						[dati_deposizionali, '01', '02','03','04', '05','06', '07', '08','09'], #7 row ok
						[rito, '01', '02',orientamento_asse,'04', orientamento_azimut,'06', posizione_cranio, '08','09'], #8 row ok
						[posizione_scheletro, '01', lunghezza_scheletro, '03', posizione_arti_superiori,'05','06', posizione_arti_inferiori, '08','09'], #9 row ok
						[dati_postdeposizionali, '01', '02','03','04', '05','06', '07', '08','09'], #10 row ok
						[stato_conservazione, '01', '02', disturbato,'04', completo,'06', in_connessione, '08'], #11 row ok
						[caratteristiche_tafonomiche_txt, '01', '02','03','04', '05','06', '07', '08','09'], #12 row ok
						[descrizione, '01','02', '03', '04', interpretazione, '06', '07', '08', '09'], #13 row ok
						[corredo, '01', '02', '03', '04', '05', '06', '07', '08', '09'], #14 row ok
						[corredo_presente,'01', '02', '03', '04','05', '06', '07', '08', '09'], #15 ow
						[corredo_descrizione,'01', '02', '03', '04','05', '06', '07', '08', '09'], #16 row
						[corredo_tipo_txt,'01', '02', '03', '04','05', '06', '07', '08', '09'], #17 row
						[misure_tafonomia_txt,'01', '02', '03', '04','05', '06', '07', '08', '09'], #18 row
						[quote_tafonomia, '01', '02', '03', '04', '07', '06', '07','08', '09'], #19 row ok
						[quota_min_ind, '01', '02', quota_max_ind, '04', quota_min_strutt, '06', quota_max_strutt,'08','09'] #20 row ok
						]

		#table style
		table_style=[
					('GRID',(0,0),(-1,-1),0.5,colors.black),
					#0 row
					('SPAN', (0,0),(6,0)),  #intestazione
					('SPAN', (7,0),(9,0)),  #intestazione

					#1 row
					('SPAN', (0,1),(4,1)),  #dati identificativi
					('SPAN', (5,1),(7,1)),  #dati identificativi
					('SPAN', (8,1),(8,1)),  #dati identificativi
					('SPAN', (9,1),(9,1)),  #dati identificativi

					#2 row
					('SPAN', (0,2),(9,2)),  #Periodizzazione
	
					#3 row
					('SPAN', (0,3),(2,3)),  #
					('SPAN', (3,3),(4,3)),  #
					('SPAN', (5,3),(6,3)),  #
					('SPAN', (7,3),(9,3)),  #
					
					#4 row
					('SPAN', (0,4),(9,4)),  #datazione estesa
					##################################
					#5 row
					('SPAN', (0,5),(9,5)),  #Elementi strutturali

					#6 row
					('SPAN', (0,6),(2,6)),  #
					('SPAN', (3,6),(4,6)),  #
					('SPAN', (5,6),(6,6)),  #
					('SPAN', (7,6),(9,6)),  #

					#7 row
					('SPAN', (0,7),(9,7)),  #

					#8 row
					('SPAN', (0,8),(2,8)),  #
					('SPAN', (3,8),(4,8)),  #
					('SPAN', (5,8),(6,8)),  #
					('SPAN', (7,8),(9,8)),  #

					#9 row
					('SPAN', (0,9),(1,9)),  #
					('SPAN', (2,9),(3,9)),  #
					('SPAN', (4,9),(6,9)),  #
					('SPAN', (7,9),(9,9)),  #

					#10 row
					('SPAN', (0,10),(9,10)),  #

					#11 row
					('SPAN', (0,11),(2,11)),  #
					('SPAN', (3,11),(4,11)),  #
					('SPAN', (5,11),(6,11)),  #
					('SPAN', (7,11),(9,11)),  #

					#12 row
					('SPAN', (0,12),(9,12)),  #

					#13 row
					('SPAN', (0,13),(4,13)),  #
					('SPAN', (5,13),(9,13)),  #

					#14 row
					('SPAN', (0,14),(9,14)),  #

					#15 row
					('SPAN', (0,15),(9,15)),  #

					#16 row
					('SPAN', (0,16),(9,16)),  

					#17 row
					('SPAN', (0,17),(9,17)),  #

					#18 row
					('SPAN', (0,18),(9,18)),  #

					('SPAN', (0,19),(9,19)),  #Periodizzazione

					#3 row
					('SPAN', (0,20),(2,20)),  #
					('SPAN', (3,20),(4,20)),  #
					('SPAN', (5,20),(6,20)),  #
					('SPAN', (7,20),(9,20)),  #

					('VALIGN',(0,0),(-1,-1),'TOP')

					]

		t=Table(cell_schema, colWidths=50, rowHeights=None,style= table_style)

		return t
    def create_sheet(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  #LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  #Justified

        #format labels

        #0 row
        intestazione = Paragraph(
            "<b>SCHEDA PERIODIZZAZIONE<br/>" + str(self.datestrfdate()) +
            "</b>", styNormal)

        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)

        ##		if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        #intestazione2 = Paragraph("<b>pyArchInit</b><br/>www.pyarchinit.blogspot.com", styNormal)

        #1 row
        sito = Paragraph("<b>Sito</b><br/>" + str(self.sito), styNormal)
        periodo = Paragraph("<b>Periodo</b><br/>" + str(self.periodo),
                            styNormal)
        fase = Paragraph("<b>Fase</b><br/>" + str(self.fase), styNormal)

        #2 row
        cronologia = Paragraph("<b>CRONOLOGIA</b></b>", styNormal)

        #3 row
        cronologia_iniziale = Paragraph(
            "<b>Cronologia iniziale</b><br/>" + str(self.cron_iniziale),
            styNormal)
        cronologia_finale = Paragraph(
            "<b>Cronologia finale</b><br/>" + str(self.cron_finale), styNormal)
        datazione_ext = Paragraph(
            "<b>Cronologia testuale</b><br/>" + str(self.datazione_estesa),
            styNormal)

        #4 row
        descrizione = ''
        try:
            descrizione = Paragraph(
                "<b>Descrizione</b><br/>" + str(self.descrizione),
                styDescrizione)
        except:
            pass

        #schema
        cell_schema = [  #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                intestazione, '01', '02', '03', '04', '05', '06', logo, '08',
                '09'
            ],  #0 row ok
            [sito, '01', '02', '03', '04', periodo, '06', '07', fase,
             '09'],  #1 row ok
            [cronologia, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  #2 row ok
            [
                cronologia_iniziale, '01', cronologia_finale, '03',
                datazione_ext, '05', '06', '07', '08', '09'
            ],  #3 row
            [
                descrizione, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ]
        ]  #4row ok

        #table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            #0 row
            ('SPAN', (0, 0), (6, 0)),  #intestazione
            ('SPAN', (7, 0), (9, 0)),  #intestazione

            #1 row
            ('SPAN', (0, 1), (4, 1)),  #Sito
            ('SPAN', (5, 1), (7, 1)),  #periodo
            ('SPAN', (8, 1), (9, 1)),  #fase

            #2 row
            ('SPAN', (0, 2), (9, 2)),  #intestazione cronologia

            #3 row
            ('SPAN', (0, 3), (1, 3)),  #cron iniziale
            ('SPAN', (2, 3), (3, 3)),  #cron finale
            ('SPAN', (4, 3), (9, 3)),  #datazione estesa

            #4
            ('SPAN', (0, 4), (9, 4)),  #datazione estesa
            ('VALIGN', (0, 4), (9, 4), 'TOP'),
            #('VALIGN',(5,3),(5,3),'TOP'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

        t = Table(cell_schema,
                  colWidths=50,
                  rowHeights=None,
                  style=table_style)

        return t
Example #52
0
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 })
Example #53
0
def cedula_hallazgo(documento):
    domicilio, gerente, supervisor, funcionarios, apoyo = documento_info(
        documento)

    output = PdfFileWriter()
    # create response object
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Cedula_de_Hallazgo.pdf'

    buffer = StringIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=50,
                            bottomMargin=100)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER, fontSize=8))
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              fontSize=8))

    Story = []

    I = Image(os.path.join(settings.BASE_DIR, 'static', 'img', 'logo.png'))
    I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth
    I.drawWidth = 1.25 * inch
    data = [[I, '', '', '', '', ''], ['SUJETO PASIVO:', '', '', '', '', ''],
            ['MATERIA:', '', '', '', '', '']]
    data[0][2] = Paragraph(
        u'''<b>CEDULA DE HALLAZGOS<br/>
                            Contribución Especial del 1% por la Presentación de<br/>
                            Servicios Turísticos</b>''', styles["Center"])
    data[0][4] = documento.codigo
    data[1][1] = documento.pst.nombre_o_razon()
    data[1][3] = 'RIF: ' + documento.pst.rif
    data[2][1] = documento.hallazgos_materia
    data[2][3] = 'PERIODO: ' + documento.fecha_notificacion.strftime(
        "%d/%m/%Y")
    w = [80, 30, 90, 90, 80, 80]
    Story.append(
        Table(data,
              colWidths=w,
              style=[('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                     ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                     ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                     ('FONTSIZE', (0, 0), (-1, -1), 8),
                     ('SPAN', (0, 0), (1, 0)), ('SPAN', (2, 0), (3, 0)),
                     ('SPAN', (4, 0), (5, 0)), ('SPAN', (1, 1), (2, 1)),
                     ('SPAN', (1, 2), (2, 2)), ('SPAN', (3, 1), (5, 1)),
                     ('SPAN', (3, 2), (5, 2))]))
    Story.append(Spacer(1, 12))

    data = [['CONDICIÓN', 'CRITERIO', 'EFECTO', 'EVIDENCIA'], ['', '', '', ''],
            ['', '', '', '']]
    try:
        data[2][0] = Paragraph(documento.hallazgos_condicion,
                               styles["Justify"])
        data[2][1] = Paragraph(documento.hallazgos_criterio, styles["Justify"])
        data[2][2] = Paragraph(documento.hallazgos_efecto, styles["Justify"])
        data[2][3] = Paragraph(documento.hallazgos_evidencia,
                               styles["Justify"])
    except:
        pass
    Story.append(
        Table(data,
              colWidths=[95, 170, 81, 105],
              style=[
                  ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                  ('GRID', (0, 2), (-1, 2), 0.25, colors.black),
                  ('FONTSIZE', (0, 0), (-1, -1), 8),
                  ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                  ('VALIGN', (0, 2), (-1, 2), 'TOP'),
              ]))
    Story.append(Spacer(1, 12))

    ptext = 'Observaciones: <u>%s</u>' % documento.observaciones
    Story.append(Paragraph(ptext, styles['Normal']))
    Story.append(Spacer(1, 12))

    Story.append(
        Paragraph('Fiscal Actuante: %s' % gerente.get_full_name(),
                  styles['Normal']))
    Story.append(
        Paragraph('Supervisor: %s' % supervisor.get_full_name(),
                  styles['Normal']))

    doc.build(Story)

    watermark = PdfFileReader(buffer)
    output.addPage(watermark.getPage(0))
    output.write(response)
    return response
Example #54
0
def genPinTable(pin):
    pinElemTable = None
    pinElemWidth = 250

    titleTable = Table([[pin.title]], pinElemWidth)

    refNoTable = Table([
        ['Ref.No:', pin.refNo, 'N 100'],
    ], [60, 120, 70])

    pinTable = Table([
        ['PIN', pin.PIN],
    ], [60, 190])

    serialTable = Table([
        ['Serial No.:', pin.serialNo],
    ], [60])

    dateTable = Table([[
        'Date:',
        pin.date.strftime('%m/%d/%Y'),
        pin.date.strftime('%I:%M:%S %p'),
    ]], [60])

    serialDateTable = Table([[serialTable], [dateTable]])

    picture = Image(pin.picPath)
    picture.drawWidth = 30
    picture.drawHeight = 30
    pictureTable = Table([[picture]], 30, 30)

    serialDatePictureTable = Table([[serialDateTable, pictureTable]],
                                   [190, 50])

    pinElemTable = Table(
        [[titleTable], [refNoTable], [pinTable], [serialDatePictureTable]],
        pinElemWidth)

    #tablestyle
    titleTableStyle = TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTSIZE', (0, 0), (-1, -1), 12),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Oblique'),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTOOMPADDING', (0, 0), (-1, -1), 0),
    ])
    titleTable.setStyle(titleTableStyle)

    refNoTableStyle = TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTOOMPADDING', (0, 0), (-1, -1), 0),
    ])
    refNoTable.setStyle(refNoTableStyle)

    pinTableStyle = TableStyle([
        ('FONTSIZE', (1, 0), (-1, 0), 13),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold'),
        ('VALIGN', (0, 0), (-1, 0), 'TOP'),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTOOMPADDING', (0, 0), (-1, -1), 0),
    ])
    pinTable.setStyle(pinTableStyle)

    serialTableStyle = TableStyle([
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTOOMPADDING', (0, 0), (-1, -1), 0),
    ])
    serialTable.setStyle(serialTableStyle)

    dateTableStyle = TableStyle([
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTOOMPADDING', (0, 0), (-1, -1), 2),
    ])
    dateTable.setStyle(dateTableStyle)

    serialDateTableStyle = TableStyle([
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTOOMPADDING', (0, 0), (-1, -1), 0),
        ('LEFTPADDING', (0, 0), (-1, -1), 0),
    ])
    serialDateTable.setStyle(serialDateTableStyle)

    picTableStyle = TableStyle([
        ('LEFTPADDING', (0, 0), (-1, -1), 15),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
    ])
    pictureTable.setStyle(picTableStyle)

    serialDatePicTableStyle = TableStyle([
        ('LEFTPADDING', (0, 0), (-1, -1), 0),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
    ])
    serialDatePictureTable.setStyle(serialDatePicTableStyle)

    pinElemTableStyle = TableStyle([
        ('BOX', (0, 0), (-1, -1), 3, colors.black),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
    ])
    pinElemTable.setStyle(pinElemTableStyle)

    return pinElemTable
Example #55
0
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
Example #56
0
    def createDocument(self):
        """"""
        for page in progressbar.progressbar(self.e.findall("page")):
            self.width, self.height = int(page.get("width")), int(
                page.get("height"))
            self.c.setPageSize((self.width, self.height))
            for image in page.findall("image"):
                src = self.template_folder + "/" + image.get("src")
                if "charts" in src:
                    chart_name = basename(src)
                    chart_path = dirname(src)
                    dest = chart_path + "/reduced_" + chart_name
                    if not isfile(dest):
                        pilImg = PILImage.open(src)
                        size = (pilImg.size[0] / 1.5, pilImg.size[1] / 1.5)
                        pilImg.thumbnail(size, PILImage.NEAREST)
                        pilImg.save(dest, optimize=True)
                else:
                    dest = src
                logo = Image(dest)
                logo.drawHeight = int(image.get("height"))
                logo.drawWidth = int(image.get("width"))
                logo.wrapOn(self.c, self.width, self.height)
                logo.drawOn(
                    self.c,
                    *self.coord(
                        int(image.get("left")),
                        int(image.get("top")) + int(image.get("height"))))
            for text in page.findall("text"):
                if len(text.getchildren()) == 0:
                    font = self.fonts[text.get("font")]
                    replacement = text.text

                    if text.get("shrink"):
                        textLen = float(len(replacement))
                        fontSizeAdj = int(font["size"])
                        heightAdj = int(
                            text.get("height")) * 2 if textLen > 30 else int(
                                text.get("height"))
                        width = int(text.get("width"))
                    else:
                        fontSizeAdj = int(font["size"])
                        heightAdj = int(text.get("height"))
                        width = self.width

                    style = ParagraphStyle(
                        'default',
                        fontName="Geomanist",
                        leading=fontSizeAdj,
                        fontSize=fontSizeAdj,
                        borderPadding=int(font["padding"]),
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )

                    self.createParagraph(replacement, int(text.get("left")),
                                         (int(text.get("top")) + heightAdj),
                                         width, style)
                else:
                    innerText = ElementTree.tostring(text.getchildren()[0])
                    font = self.fonts[text.get("font")]
                    replacement = innerText

                    if text.get("shrink"):
                        textLen = float(len(replacement))
                        fontSizeAdj = int(font["size"])
                        heightAdj = int(
                            text.get("height")) * 2 if textLen > 30 else int(
                                text.get("height"))
                        width = int(text.get("width"))
                    else:
                        fontSizeAdj = int(font["size"])
                        heightAdj = int(text.get("height"))
                        width = self.width

                    style = ParagraphStyle(
                        'default',
                        fontName="Geomanist",
                        leading=fontSizeAdj,
                        fontSize=fontSizeAdj,
                        borderPadding=int(font["padding"]),
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )

                    self.createParagraph(replacement, int(text.get("left")),
                                         (int(text.get("top")) + heightAdj),
                                         width, style)
            for line in page.findall("line"):
                self.c.setDash(int(line.get("on")), int(line.get("off")))
                self.c.setStrokeColor(line.get("color"))
                self.c.line(int(line.get("x1")),
                            self.height - int(line.get("y1")),
                            int(line.get("x2")),
                            self.height - int(line.get("y2")))
            for button in page.findall("button"):
                padtop = int(button.get("pt")) if button.get("pt") else 0
                padbottom = int(button.get("pb")) if button.get("pb") else 0
                padleft = int(button.get("pl")) if button.get("pl") else 0
                padright = int(button.get("pr")) if button.get("pr") else 0
                top = (self.height - int(button.get("top"))) + padtop
                bottom = (
                    (top - padtop) - int(button.get("height"))) - padbottom
                left = int(button.get("left")) - padleft
                right = (
                    (left + padleft) + int(button.get("width"))) + padright
                rect = (left, bottom, right, top)
                self.c.linkAbsolute("",
                                    button.get("href"),
                                    rect,
                                    Border='[0 0 0]')
            for bookmark in page.findall("bookmark"):
                self.c.bookmarkPage(bookmark.get("name"),
                                    fit="FitR",
                                    left=1,
                                    right=self.width,
                                    bottom=self.height - self.width,
                                    top=self.height)

            self.c.showPage()
Example #57
0
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"
Example #58
0
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})




  
Example #59
0
def attestationects(form, elev, classe):
    """renvoie l'attestation ects pdf de l'élève elev, ou si elev vaut None renvoie les attestations ects pdf de toute la classe classe en un seul fichier"""
    datedujour = form.cleaned_data['date'].strftime('%d/%m/%Y')
    filiere = form.cleaned_data['classe'].split("_")[0]
    signataire = form.cleaned_data['signature']
    annee = form.cleaned_data['anneescolaire']
    etoile = form.cleaned_data['etoile']
    signature = False
    if 'tampon' in form.cleaned_data:
        signature = form.cleaned_data['tampon']
    config = Config.objects.get_config()
    annee = "{}-{}".format(int(annee) - 1, annee)
    response = HttpResponse(content_type='application/pdf')
    if elev is None:
        eleves = Eleve.objects.filter(classe=classe).order_by(
            'user__last_name', 'user__first_name').select_related('user')
        nomfichier = "ATTESTATIONS_{}.pdf".format(unidecode(
            classe.nom)).replace(" ", "-")
        credits = NoteECTS.objects.credits(classe)[0]
    else:
        eleves = [elev]
        credits = [False]
        nomfichier = unidecode("ATTESTATION_{}_{}_{}.pdf".format(
            elev.classe.nom.upper(), elev.user.first_name,
            elev.user.last_name.upper())).replace(" ", "-")
    response['Content-Disposition'] = "attachment; filename={}".format(
        nomfichier)
    pdf = easyPdf()
    pdf.marge_x = cm  # 1cm de marge gauche/droite
    pdf.marge_y = 1.5 * cm  # 1,5cm de marge haut/bas
    I = Image(join(RESOURCES_ROOT, 'marianne.jpg'))
    I.drawHeight = 1.8 * cm
    I.drawWidth = 3 * cm
    if signature and signataire == 'Proviseur':
        try:
            I2 = Image(join(RESOURCES_ROOT, 'proviseur.png'))
        except Exception:
            try:
                I2 = Image(join(RESOURCES_ROOT, 'proviseur.png'))
            except Exception:
                I2 = False
    elif signature and signataire == 'Proviseur adjoint':
        try:
            I2 = Image(join(RESOURCES_ROOT, 'proviseuradjoint.png'))
        except Exception:
            try:
                I2 = Image(join(RESOURCES_ROOT, 'proviseuradjoint.png'))
            except Exception:
                I2 = False
    else:
        I2 = False
    if I2:
        I2.drawHeight = 3 * cm
        I2.drawWidth = 3 * cm
    newpage = False
    for eleve, credit in zip(eleves, credits):
        if elev or credit and credit['ddn'] and credit['ine'] and credit[
                'sem1'] == 30 and credit[
                    'sem2'] == 30:  # si l'élève a bien toutes les infos/crédits
            if newpage:  # si ce n'est pas la première page, on change de page
                pdf.showPage()
            pdf.y = pdf.format[1] - pdf.marge_y - 1.8 * cm
            I.drawOn(pdf, 9 * cm, pdf.y)
            pdf.y -= 10
            pdf.setFont("Times-Roman", 7)
            pdf.drawCentredString(pdf.format[0] / 2, pdf.y,
                                  "MINISTÈRE DE L'ÉDUCATION NATIONALE")
            pdf.y -= 8
            pdf.drawCentredString(
                pdf.format[0] / 2, pdf.y,
                "DE l'ENSEIGNEMENT SUPÉRIEUR ET DE LA RECHERCHE")
            pdf.y -= 30
            pdf.setFont('Helvetica-Bold', 14)
            pdf.drawCentredString(pdf.format[0] / 2, pdf.y,
                                  "ATTESTATION DU PARCOURS DE FORMATION")
            pdf.y -= 30
            pdf.drawCentredString(pdf.format[0] / 2, pdf.y, "EN")
            pdf.y -= 30
            pdf.drawCentredString(pdf.format[0] / 2, pdf.y,
                                  "CLASSE PRÉPARATOIRE AUX GRANDES ÉCOLES")
            pdf.y -= 40
            pdf.setFont("Helvetica-Oblique", 11)
            pdf.drawCentredString(
                pdf.format[0] / 2, pdf.y,
                "Le recteur de l'académie de {}, Chancelier des universités,".
                format(config.academie))
            pdf.y -= 15
            pdf.drawCentredString(pdf.format[0] / 2, pdf.y, "atteste que")
            pdf.y -= 40
            pdf.setFont("Helvetica", 12)
            pdf.drawCentredString(pdf.format[0] / 2, pdf.y, "{}".format(eleve))
            pdf.y -= 50
            pdf.setFont("Helvetica", 11)
            pdf.drawString(
                2 * cm, pdf.y,
                "né(e) le {} à {}".format(eleve.ddn.strftime('%d/%m/%Y'),
                                          eleve.ldn.title()))
            pdf.y -= 15
            pdf.drawString(2 * cm, pdf.y, "n° INE: {}".format(eleve.ine))
            pdf.y -= 50
            pdf.setFont("Helvetica-Oblique", 11)
            pdf.drawCentredString(
                pdf.format[0] / 2, pdf.y,
                "a accompli un parcours de formation dans la filière {}".
                format(filiere +
                       ('*' if etoile and eleve.classe.annee == 2 else '')))
            pdf.y -= 50
            pdf.drawCentredString(
                pdf.format[0] / 2, pdf.y,
                "Valeur du parcours en crédits du système ECTS :")
            pdf.setFont("Helvetica-Bold", 16)
            pdf.drawString(15 * cm, pdf.y, "60")
            pdf.y -= 50
            pdf.setFont("Helvetica-Oblique", 11)
            pdf.drawCentredString(pdf.format[0] / 2, pdf.y,
                                  "Mention globale obtenue :")
            pdf.setFillColor((1, 0, 0))
            pdf.setFont("Helvetica-Bold", 13)
            pdf.drawCentredString(
                13 * cm, pdf.y, "ABCDEF"[NoteECTS.objects.moyenneECTS(eleve)])
            pdf.y -= 50
            pdf.setFillColor((0, 0, 0))
            pdf.setFont("Helvetica", 11)
            pdf.drawString(2 * cm, pdf.y, "Année académique: {}".format(annee))
            pdf.y -= 15
            pdf.drawString(2 * cm, pdf.y, config.nom_etablissement)
            pdf.y -= 30
            pdf.drawCentredString(pdf.format[0] / 2, pdf.y,
                                  "Fait à {},".format(config.ville))
            pdf.y -= 15
            pdf.drawString(15 * cm, pdf.y, "le {}".format(datedujour))
            pdf.y -= 15
            pdf.drawString(15 * cm, pdf.y, "Pour le recteur,")
            pdf.y -= 15
            pdf.drawString(15 * cm, pdf.y, "Le {}".format(signataire.lower()))
            pdf.y -= 3 * cm
            pdf.x = pdf.format[0] - 5 * cm - 2 * pdf.marge_x
            if I2:
                I2.drawOn(pdf, pdf.x, pdf.y)
            pdf.setFont("Helvetica-Oblique", 9)
            pdf.y = 3 * cm
            pdf.drawCentredString(
                pdf.format[0] / 2, pdf.y,
                "Attestation délivrée en application des dispositions de l’article 8 du décret n° 94-1015"
            )
            pdf.y -= 12
            pdf.drawCentredString(
                pdf.format[0] / 2, pdf.y,
                "du 23 novembre 1994 modifié par le décret n° 2007-692 du 3 mai 2007"
            )
            pdf.y -= 12
            pdf.drawCentredString(
                pdf.format[0] / 2, pdf.y,
                "Le descriptif de la formation figure dans l’annexe jointe.")
            newpage = True
    pdf.save()
    fichier = pdf.buffer.getvalue()
    pdf.buffer.close()
    response.write(fichier)
    return response
    def createDocument(self):
        """"""
        for page in self.e.findall("page"):
            for image in page.findall("image"):
                if image.get("variable") == "True":
                    src = image.get("path") + self.country + "/" + image.get(
                        "src")
                    dest = image.get(
                        "path") + self.country + "/reduced_" + image.get("src")
                    pilImg = PILImage.open(src)
                    size = (pilImg.size[0] / 1.5, pilImg.size[1] / 1.5)
                    pilImg.thumbnail(size, PILImage.NEAREST)
                    pilImg.save(dest, optimize=True)
                else:
                    src = image.get("path") + image.get("src")
                    dest = src
                # logo = Image(dest)
                logo = Image(src)
                logo.drawHeight = int(image.get("height"))
                logo.drawWidth = int(image.get("width"))
                logo.wrapOn(self.c, self.width, self.height)
                logo.drawOn(
                    self.c,
                    *self.coord(
                        int(image.get("left")),
                        int(image.get("top")) + int(image.get("height"))))
            for text in page.findall("text"):
                if len(text.getchildren()) == 0:
                    font = self.fonts[text.get("font")]
                    if text.get("replace"):
                        replacement = dataDictionary[self.country][text.get(
                            "replace")]
                    else:
                        replacement = text.text

                    if text.get("shrink"):
                        fontSize = float(font["size"])
                        height = int(text.get("height"))
                        textLen = float(len(replacement))
                        divisor = max(((textLen / 25.0) + (2.0 / 3.0)), 1)
                        fontSizeAdj = int(fontSize / divisor)
                        fontSizeDiff = int(float(fontSize - fontSizeAdj) / 2.0)
                        heightAdj = height - fontSizeDiff
                    else:
                        fontSizeAdj = int(font["size"])
                        heightAdj = int(text.get("height"))

                    style = ParagraphStyle(
                        'default',
                        fontName="Arial",
                        leading=fontSizeAdj,
                        fontSize=fontSizeAdj,
                        borderPadding=int(font["padding"]),
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )

                    self.createParagraph(replacement, int(text.get("left")),
                                         (int(text.get("top")) + heightAdj),
                                         style)
                else:
                    innerText = ElementTree.tostring(text.getchildren()[0])
                    font = self.fonts[text.get("font")]
                    if text.get("replace"):
                        replacement = dataDictionary[self.country][text.get(
                            "replace")]
                    else:
                        replacement = innerText

                    if text.get("shrink"):
                        fontSize = float(font["size"])
                        height = int(text.get("height"))
                        textLen = float(len(replacement))
                        divisor = max(((textLen / 25.0) + (2.0 / 3.0)), 1)
                        fontSizeAdj = int(fontSize / divisor)
                        fontSizeDiff = int(float(fontSize - fontSizeAdj) / 2.0)
                        heightAdj = height - fontSizeDiff
                    else:
                        fontSizeAdj = int(font["size"])
                        heightAdj = int(text.get("height"))

                    style = ParagraphStyle(
                        'default',
                        fontName="Arial",
                        leading=fontSizeAdj,
                        fontSize=fontSizeAdj,
                        borderPadding=int(font["padding"]),
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )

                    self.createParagraph(replacement, int(text.get("left")),
                                         (int(text.get("top")) + heightAdj),
                                         style)
            for line in page.findall("line"):
                self.c.setDash(int(line.get("on")), int(line.get("off")))
                self.c.setStrokeColor(line.get("color"))
                self.c.line(int(line.get("x1")),
                            self.height - int(line.get("y1")),
                            int(line.get("x2")),
                            self.height - int(line.get("y2")))
            for table in page.findall("table"):
                self.c.setDash(1, 0)
                tabDat = dataDictionary[self.country][table.get("data")]
                if table.get("widths"):
                    colWidths = [
                        float(width)
                        for width in table.get("widths").split(",")
                    ]
                else:
                    colWidths = float(table.get("width")) / len(tabDat[0])
                if table.get("heights"):
                    rowHeights = [
                        float(height)
                        for height in table.get("heights").split(",")
                    ]
                else:
                    rowHeights = float(table.get("height")) / len(tabDat)
                t = Table(tabDat,
                          colWidths,
                          rowHeights,
                          style=tableStyles[table.get("data")])
                t.wrapOn(self.c, self.width, self.height)
                t.drawOn(
                    self.c,
                    *self.coord(
                        int(table.get("left")),
                        int(table.get("top")) + int(table.get("height"))))

            self.c.showPage()