Ejemplo n.º 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()
Ejemplo n.º 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)
Ejemplo n.º 3
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
Ejemplo n.º 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)
Ejemplo n.º 5
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
Ejemplo n.º 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)
Ejemplo n.º 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)
Ejemplo n.º 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())
Ejemplo n.º 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()
Ejemplo n.º 12
0
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)
Ejemplo n.º 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
Ejemplo n.º 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
Ejemplo n.º 15
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
Ejemplo n.º 16
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
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)
Ejemplo n.º 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()
Ejemplo n.º 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)
Ejemplo n.º 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"]))
Ejemplo n.º 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))
Ejemplo n.º 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()
Ejemplo n.º 25
0
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)
	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
	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
from reportlab.lib.styles import getSampleStyleSheet

pdf_path = os.getcwd() + "\\pdf\\complex_cell_values.pdf"
doc = SimpleDocTemplate(pdf_path,
                        pagesize=letter,
                        rightMargin=20,
                        leftMargin=20,
                        topMargin=200)
# container for the 'Flowable' objects
elements = []

styleSheet = getSampleStyleSheet()

I = Image('rp_logo.png')
I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth
I.drawWidth = 1.25 * inch
P0 = Paragraph('''A 
    paragraph
    1''', styleSheet["BodyText"])

P = Paragraph(''' The ReportLab Left
    Logo
    Image''', 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),
Ejemplo n.º 29
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)
Ejemplo n.º 30
0
    def buildShotPDF(self, filename, shot):
        """
        Builds the Shot Turnover PDF file using the reportlab API

        :param filename: PDF file name
        :param shot: Shot entity to build report for 
        :returns: None
        """

        """
        # grab thumbnails -- Might eventually use this. Keeping for posterity.
        shot["image"] = self._downloaded_thumb_paths["Shot"].get(shot.get("id", -1))
        # if the path doesn't exist on disk, reset the value so it doesn't fail later
        if shot["image"] and not os.path.exists(shot["image"]):
            shot["image"] = None
        """
            
        # layout properties -- constants used throughout report
        margin = 0.25*inch
        padding = 0.15*inch
        (width, height) = letter
        content_width = width - 2*margin
        quarter_width = content_width / 4
        half_width = content_width / 2

        # create the doc
        doc = OneColDocTemplate(
            filename,
            pagesize=letter,
            leftMargin=margin,
            rightMargin=margin,
            topMargin=margin,
            bottomMargin=margin,
        )

        # define styles and colors
        self.styles = define_text_styles()
        dark_grey = colors.Color(0.66, 0.66, 0.66)
        light_grey = colors.Color(0.8, 0.8, 0.8)
        jaunt_green = colors.Color(0.741, 1, 0)
        note_style = ParagraphStyle(fontName="Helvetica", name="NoteText")

        # content
        story = []

        # Construct the Header Table data
        release_title = shot.get("project.Project.sg_release_title") or ""
        vendor_name = (shot.get("sg_awarded_vendor") or {}).get("name") or ""
        vendor_label = "Vendor" if vendor_name else ""
        vendor_code = shot.get("sg_awarded_vendor.HumanUser.sg_vendor_code") or ""
        vendor_code_label = "Comp Code" if vendor_code else ""
        date_label = "Turnover Date" if vendor_label else "Bid Material Sent"
        turn_notes = safe_para(shot.get("sg_turnover_notes___linked_field") or "",
                               note_style)
        header_logo = self._jaunt_logo()
        if header_logo:
            header_logo = Image(header_logo)
            header_logo.drawHeight = quarter_width*header_logo.drawHeight / header_logo.drawWidth
            header_logo.drawWidth = quarter_width
        header_data = [
            [header_logo,           release_title,      vendor_label,       vendor_name],
            ["",                    "",                 vendor_code_label,  vendor_code],
            ["",                    shot["code"],       date_label,         date.today().strftime("%m/%d/%y")],
            ["Turnover Notes : ",   turn_notes,         "",                 ""],
        ]
        # Add an empty row at the bottom for nice spacing
        header_data.append([""]*len(header_data[0]))

        # Specify the column widths for the Header Table.
        col_widths = [quarter_width, 0.9*half_width, 1.2*quarter_width/2, 1.2*quarter_width/2]

        # Create the Header Table and format the cells.
        header = Table(header_data, colWidths=col_widths)
        header.setStyle(TableStyle([
            ("BACKGROUND",  (0,0), (-1,2),  light_grey),
            ("SPAN",        (0,0), (0,2)),
            ("VALIGN",      (0,0), (0,2),   "TOP"),
            ("SPAN",        (1,0), (1,1)),
            ("ALIGN",       (1,0), (1,2),   "CENTER"),
            ("VALIGN",      (1,0), (1,2),   "MIDDLE"),
            ("FONT",        (1,0), (1,0),   "Helvetica-Bold", 18),
            ("FONT",        (1,1), (1,2),   "Helvetica-Bold", 14),
            ("ALIGN",       (2,0), (2,2),   "LEFT"),
            ("FONT",        (2,0), (2,2),   "Helvetica-Oblique", 12),
            ("ALIGN",       (3,0), (3,2),   "RIGHT"),
            ("FONT",        (3,0), (3,2),   "Helvetica", 12),
            ("LINEBELOW",   (0,2), (-1,2),  2, jaunt_green),
            ("ALIGN",       (0,3), (0,3),   "LEFT"),
            ("VALIGN",      (0,3), (0,3),   "TOP"),
            ("FONT",        (0,3), (0,3),   "Helvetica-BoldOblique", 12),
            ("SPAN",        (1,3), (-1,3)),
            ("ALIGN",       (1,3), (-1,3),  "LEFT"),
            ("FONT",        (1,3), (-1,3),  "Helvetica", 12),
        ]))
        story.append(header)

        # Turnover Materials -- first construct the Table data
        material_data = [
            ["Turnover Materials", "Description"]
        ]
        segments = self._segments_by_shot.get(shot["id"]) or []
        for segment in segments:
            material_data.append([segment["code"], segment["description"]])
        for version in (self._versions_by_shot.get(shot["id"]) or []):
            material_data.append([version["code"], version["description"]])
        # Add an empty row for nice spacing
        material_data.append([""]*len(material_data[0]))

        # Specify the Turnover Materials Table column widths
        col_widths = [half_width]*2

        # Create the Turnover Materials Table and format the cells.
        materials = Table(material_data, colWidths=col_widths)
        materials.setStyle(TableStyle([
            ("BACKGROUND",  (0,0), (-1,0),  dark_grey),
            ("FONT",        (0,0), (-1,0),  "Helvetica-Bold", 12),
            ("ALIGN",       (0,0), (-1,-1), "LEFT"),
            ("FONT",        (0,1), (-1,-1), "Helvetica", 10),
        ]))
        story.append(materials)

        # Editorial Information -- first construct the Table data
        editorial_data = [
            ["EDITORIAL", "", "", "", "", ""],
            ["Plate", "Plate Range", "Plate IN", "Plate OUT", "Comp IN", "Comp OUT"],
        ]
        for segment in segments :
            editorial_data.append([
                segment["code"],
                _float_to_timecode(segment["sg_duration"]),
                _float_to_timecode(segment["sg_start"]),
                _float_to_timecode(segment["sg_end"]),
                segment["sg_timeline_start"],
                segment["sg_timeline_end"]])
        # Add an empty row for nice spacing
        editorial_data.append([""]*len(editorial_data[0]))

        # Specify the Editorial Table column widths
        col_widths = [half_width] + [content_width/10]*5

        # Create the Editorial Table and format the cells.
        editorial = Table(editorial_data, colWidths=col_widths)
        editorial.setStyle(TableStyle([
            ("BACKGROUND",  (0,0), (-1,0),  dark_grey),
            ("SPAN",        (0,0), (-1,0)),
            ("FONT",        (0,0), (0,0),   "Helvetica-BoldOblique", 12),
            ("ALIGN",       (0,0), (1,-1),  "CENTER"),
            ("ALIGN",       (0,1), (0,1),   "LEFT"), 
            ("BACKGROUND",  (0,1), (-1,1),  light_grey),
            ("FONT",        (0,1), (-1,1),  "Helvetica-Bold", 10),
            ("FONT",        (0,2), (-1,-1), "Helvetica", 10),
            ("ALIGN",       (0,2), (0,-1),  "LEFT"),
            ("ALIGN",       (1,2), (-1,-1), "CENTER")
        ]))
        story.append(editorial)

        # Notes -- first construct the Notes Table data
        notes = self._notes_by_shot.get(shot["id"]) or []
        note_data = [["Notes"]]
        [note_data.append([safe_para(n["content"], note_style)]) for n in notes]

        # Specify the Notes Table column width(s)
        col_widths = [content_width]

        # Create the Notes Table and format the cells.
        shot_notes = Table(note_data, colWidths=col_widths)
        shot_notes.setStyle(TableStyle([
            ("BACKGROUND",  (0,0), (-1,0),  dark_grey),
            ("FONT",        (0,0), (-1,0),  "Helvetica-BoldOblique", 12),
            ("ALIGN",       (0,0), (-1,-1), "LEFT"),
            ("FONT",        (0,1), (-1,-1), "Helvetica", 12),
        ]))
        story.append(shot_notes)

        # This builds and saves the document to disk.
        doc.build(story, canvasmaker=NumberedCanvas)
Ejemplo n.º 31
0
    def run(self, m):
        # m = {'customer': 'Pak', 'contacts': '89161234567', 'place': 'Rostov', 'datetime': '18-00', 'count_tables': '50',
        #      'count_peoples': '100', 'payer': 'Pak', 'type': 'Marriage', 'comment': 'test',
        #      'menu': [{'name': 'Суп', 'value': 2, 'price': '500', 'weight': '300', 'photo': '1.jpg'},
        #               {'name': 'Салат', 'value': 2, 'price': '200', 'weight': '400', 'photo': '2.jpeg'},
        #               {'name': 'Десерт', 'value': 3, 'price': '600', 'weight': '300', 'photo': '3.jpg'}]}

        DocName = datetime.datetime.now().strftime('genpdf_%Y%m%d_%H%M.pdf')
        doc = SimpleDocTemplate(DocName,
                                pagesize=A4,# размер страницы == портретный A4
                                leftMargin=1 * cm,# отступ слева
                                rightMargin=2 * cm,# отступ справа
                                bottomMargin=2 * cm,# отступ сверху
                                topMargin=2 * cm,# отступ снизу
                                )
        style = self.styles["Normal"]


        DataTable = [['ФИО', m['customer']],
                     ['Контакт', m['contacts']],
                     ['Место', m['place']],
                     ['Дата и время', m['datetime']],
                     ['Количество столов', m['count_tables']],
                     ['Количество людей', m['count_peoples']],
                     ['Плательщик', m['payer']],
                     ['Вид мероприятия', m['type']],
                     ['Примечания', m['comment']]]

        GridObj = Table(DataTable,
                        colWidths = [100, 300],
                        rowHeights = None,
                        style = self._style,
                        splitByRow = 1,
                        #repeatRows = 1,
                        #repeatCols = 0,
                        )


        DataTable1 = [ [ "Название","Кол-во","Цена","Вес" ] ]

        for i in m["menu"]:

            I = Image(f"static/{i['photo']}")
            I.drawHeight = 1 * inch * I.drawHeight / I.drawWidth
            I.drawWidth = 1 * inch

            buf = []

            buf.append(i["name"])
            buf.append(i["value"])
            buf.append(i["price"])
            buf.append(i["weight"])

            buf.append(I)

            DataTable1.append(buf)


        GridObj1 = Table(DataTable1,
                        colWidths = [80, 80, 80, 80, 80],
                        rowHeights = None,
                        style = self._style,
                        splitByRow = 1,
                        #repeatRows = 1,
                        #repeatCols = 0,
                        )


        total = sum([int(i["value"]) * int(i["price"]) for i in m['menu']])

        # s = []
        # for i in m["menu"]:
        #     s.append( int(i["value"]) * int(i["price"]))
        # total = sum(s)


        tips = total/10
        total_with_tips = total + tips
        total_for_person = total_with_tips/int(m["count_peoples"])


        DataTable2 = [['Итого по мероприятию', total],
                      ['Обслуживание 10%', tips],
                      ['Итого по мероприятию с обслуживанием', total_with_tips],
                      ['Сумма на человека', total_for_person]]

        GridObj2 = Table(DataTable2,
             colWidths=[300, 100],
             rowHeights=None,
             style=self._style,
             splitByRow=1,
             # repeatRows = 1,
             # repeatCols = 0,
             )

        # насколько я понял этот код создает вторую таблицу и в тогда надо вставить в doc.build([BGridObj])
        # BGridObj = Table([[GridObj,GridObj]],
        #                 colWidths = [320,320,],
        #                 rowHeights = None,
        #                 style = self._style,
        #                 splitByRow = 1,
        #                 repeatRows = 1,
        #                 #repeatCols = 0,
        #                 )
        doc.build([GridObj, GridObj1, GridObj2], onFirstPage = self.myFirstPage, onLaterPages = self.myLaterPages)
 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['PYARCHINIT_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
Ejemplo n.º 33
0
def _generate_pdf(course, output):
    from reportlab.lib.enums import TA_JUSTIFY, TA_RIGHT, TA_LEFT, TA_CENTER
    from reportlab.lib.pagesizes import A4
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle, PropertySet
    from reportlab.lib.units import mm, inch
    from reportlab.lib import colors
    from reportlab.platypus import XPreformatted, Preformatted
    from django.conf import settings
    from reportlab.pdfgen import canvas
    pdfmetrics.registerFont(TTFont('simhei', 'simhei.ttf'))
    pdfmetrics.registerFont(TTFont('Arialuni', 'arialuni.ttf'))

    doc = SimpleDocTemplate(output,
                            pagesize=A4,
                            rightMargin=.5 * inch,
                            leftMargin=.5 * inch,
                            topMargin=inch,
                            bottomMargin=.6 * inch)

    Story = [Spacer(1, 3.5 * inch)]
    style = styles["Normal"]
    styleN = styles['Normal']
    styleH = styles['Heading1']

    ###
    stylesheet = getSampleStyleSheet()
    normalStyle = stylesheet['Normal']

    #頁首的資訊
    header = [
        ['Quotation No', ':', course.order_number],
        ['Customer', ':', course.customer.title],
        ['Contact Person', ':', course.contact.name],
        ['Contact Email', ':', course.contact.email],
        ['Date', ':', course.ord_date],
        ['Expired Date', ':', course.effective_date],
    ]

    h = Table(header,
              style=[
                  ('ALIGN', (0, 0), (0, -1), 'LEFT'),
                  ('FONTNAME', (2, 0), (2, -1), 'Arialuni'),
                  ('SPAN', (1, -1), (1, -1)),
                  ('VALIGN', (0, 0), (0, -1), 'TOP'),
              ])

    Story.append(h)

    Story.append(PageBreak())

    #因為要套用字型Arialuni, 所以將comment改為Paragraph
    comment = Paragraph(
        '''
       <para align=left spaceb=3><font face="Arialuni">''' + course.comment +
        '''</font></para>''', styles["BodyText"])

    #頁首的資訊

    #要把使用者的名字的第一個字大寫
    order_person = str(course.quote_user).split('.')
    str_sales_name = "%s %s" % (str(course.quote_user.first_name).capitalize(),
                                str(course.quote_user.last_name).capitalize())

    header = [['Quotation No', ':', course.order_number, '', '', '', ''],
              [
                  'Customer', ':', course.customer.title, '', 'Date', ':',
                  course.ord_date
              ],
              [
                  'Contact Person', ':', course.contact.name, '',
                  'Expired Date', ':', course.effective_date
              ],
              [
                  'Contact Email', ':', course.contact.email, '',
                  'Sales Contact', ':', str_sales_name
              ],
              [
                  'Payment Term', ':', course.paymentterm, '', 'Email', ':',
                  course.quote_user.email
              ],
              [
                  'Price Term', ':', course.priceterm, '', 'Currency', ':',
                  course.currency
              ], ['', '', '', '', '', '', '']]

    h = Table(
        header,
        colWidths=[
            1.0 * inch, 0.1 * inch, 2.8 * inch, 0.3 * inch, 0.9 * inch,
            0.1 * inch, 2.0 * inch
        ],
        style=[
            #('ALIGN',(0,0),(0,-1), 'LEFT'),
            ('SPAN', (2, 0), (3, 0)),
            ('FONTNAME', (2, 0), (2, -1), 'Arialuni'),
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('ALIGN', (3, 0), (3, -1), 'LEFT'),
            ('FONTNAME', (6, 0), (6, -1), 'Arialuni'),
        ])

    Story.append(h)

    element = []
    tableheader = ['No.', 'Image', 'Product  Description', 'Quantity', 'Price']
    #tableheader = ['No.','Image', 'Product      Description                                                            ', 'Quantity' ,'Price']

    element.append(tableheader)
    loopcounter = 1
    grund_total = 0
    for item in course.orderitem_set.all():

        myitem = []
        myitem.append(loopcounter)
        img = settings.MEDIA_ROOT + "/" + str(
            item.product.image.url).split("/")[2]
        I = Image(img)
        I.drawHeight = 0.85 * inch
        I.drawWidth = 0.85 * inch

        myitem.append(I)
        productname = item.orderitem_name

        line_remark = ""
        if item.is_special:
            special = "★ Customized Product"
            productname = "%s      %s" % (item.orderitem_name, special)

        if item.line_remark is not None:
            line_remark = "%s %s" % ("Remark: ", item.line_remark)

        desctiption = "Watt: " + str(
            item.orderitem_watt
        ) + " , Option1:" + item.orderitem_option1 + " , Beam Angle:" + item.orderitem_beam_angle + ' , CRI: ' + str(
            item.orderitem_cri) + ' , CCT: ' + item.orderitem_cct
        myitem.append(productname + '\n' + desctiption + '\nDimming Option:' +
                      str(item.orderitem_dimming) + '\nModel No: ' +
                      item.orderitem_modelname + '\n' + line_remark)

        qty_group = [
            item.quantity, item.quantity1, item.quantity2, item.quantity3
        ]
        price_group = [item.price, item.price1, item.price2, item.price3]

        str_qty = ''
        str_price = ''

        for q in qty_group:
            if q is not None:
                str_qty += str('{:,.0f}'.format(int(q))) + '\n'

        for p in price_group:
            if p is not None:
                #加上貨幣符號
                str_price += str(course.currency.symbol) + str(
                    '{:,.2f}'.format(float(p))) + '\n'

        myitem.append(str_qty)
        myitem.append(str_price)

        element.append(myitem)
        loopcounter += 1

    #repeatRows=1 是指第一行(表頭) 換頁時會重複
    t = Table(
        element,
        colWidths=[0.3 * inch, 1.0 * inch, 4.6 * inch, 0.8 * inch, 1.0 * inch],
        repeatRows=1)

    t.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (4, 0), colors.skyblue),
            ('ALIGN', (0, 0), (3, 0), 'CENTER'),
            ('SIZE', (0, 1), (0, -1), 8),
            ('SIZE', (2, 1), (2, -1), 8),
            ('VALIGN', (0, 0), (4, -1), 'TOP'),
            ('ALIGN', (3, 0), (4, -1), 'RIGHT'),
            ('TEXTCOLOR', (3, 1), (4, -1), colors.blue),
            ('SIZE', (3, 1), (4, -1), 8),
            ('LINEBELOW', (0, -1), (-1, -1), 1, colors.black),
        ]))
    # t.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'),
    #                    ('TEXTCOLOR',(1,1),(-2,-2),colors.red),
    #                    ('VALIGN',(0,0),(0,-1),'TOP'),
    #                    ('TEXTCOLOR',(0,0),(0,-1),colors.blue),
    #                    ('ALIGN',(0,-1),(-1,-1),'CENTER'),
    #                    ('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
    #                    ('TEXTCOLOR',(0,-1),(-1,-1),colors.green),
    #                    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    #                    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
    #                    ]))

    Story.append(t)

    #頁首的資訊
    #因為要套用字型Arialuni, 所以將comment改為Paragraph
    comment = Paragraph(
        '''
       <para align=left spaceb=3><font face="Arialuni" >''' +
        str(course.comment).replace('\n', '<br/>\n') + '''</font></para>''',
        styles["BodyText"])
    footer = [
        ['Remark:'],
        [comment],
    ]

    f = Table(footer)

    Story.append(f)

    style = getSampleStyleSheet()['Normal']
    style.leading = 8
    # generalterm.content   通用條款 Start
    #Story.append(PageBreak())
    # 因為要套用字型Arialuni, 所以將comment改為Paragraph
    terms = Paragraph(
        '''
       <para align=left spaceb=3><fontSize=10 color=skyblue><strong>General Term and Conditions:</strong></fontSize><br/><font size="6">'''
        + str(course.generalterm).replace('\n', '<br/>\n') +
        '''</font></para>''', style)

    Story.append(KeepTogether(terms))

    doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPage)
Ejemplo n.º 34
0
def generate_pdf_structure(reports):
    """
    Returns the elements object for the report to be generated in PDF
    Accepts a schema of the report
    """
    def numtoStr(s):
        """Convert string to either int or float."""
        try:
            ret = int(s)
        except ValueError:
            ret = float(s)
        return ret

    months = [
        u'Ιανουάριος', u'Φεβρουάριος', u'Μάρτιος', u'Απρίλιος', u'Μάιος',
        u'Ιούνιος', u'Ιούλιος', u'Αύγουστος', u'Σεπτέμβριος', u'Οκτώβριος',
        u'Νοέμβριος', u'Δεκέμβριος'
    ]
    elements = []
    for report in reports:
        logo = os.path.join(settings.MEDIA_ROOT, "logo.png")

        width, height = A4
        head_logo = getSampleStyleSheet()
        head_logo.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=8))
        heading_style = getSampleStyleSheet()
        heading_style.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans-Bold',
                           fontSize=12))
        heading_style.add(
            ParagraphStyle(name='Spacer',
                           spaceBefore=5,
                           spaceAfter=5,
                           fontName='DroidSans-Bold',
                           fontSize=12))
        signature = getSampleStyleSheet()
        signature.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=10))
        tbl_style = getSampleStyleSheet()
        tbl_style.add(
            ParagraphStyle(name='Left',
                           alignment=TA_LEFT,
                           fontName='DroidSans',
                           fontSize=10))
        tbl_style.add(
            ParagraphStyle(name='Right',
                           alignment=TA_RIGHT,
                           fontName='DroidSans',
                           fontSize=10))
        tbl_style.add(
            ParagraphStyle(name='BoldLeft',
                           alignment=TA_LEFT,
                           fontName='DroidSans-Bold',
                           fontSize=10))

        tsl = [('ALIGN', (0, 0), (-1, -1), 'CENTER'),
               ('FONT', (0, 0), (-1, 0), 'DroidSans'),
               ('FONTSIZE', (0, 0), (-1, 0), 8),
               ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
               ('TOPPADDING', (0, 0), (-1, -1), 0)]
        tsh = [('ALIGN', (1, 1), (-1, -1), 'LEFT'),
               ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]
        ts = [('ALIGN', (1, 1), (-1, -1), 'LEFT'),
              ('FONT', (0, 0), (-1, 0), 'DroidSans'),
              ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
              ('GRID', (0, 0), (-1, -1), 0.5, colors.black)]
        tsf = [('ALIGN', (1, 1), (-1, -1), 'CENTER')]

        im = Image(logo)
        im.drawHeight = 1.25 * cm
        im.drawWidth = 1.25 * cm
        data = []
        data.append([im, ""])
        data.append(
            [Paragraph(u'ΕΛΛΗΝΙΚΗ ΔΗΜΟΚΡΑΤΙΑ', head_logo['Center']), ''])
        data.append([
            Paragraph(u'%s' % SETTINGS['full_ministry_title'],
                      head_logo['Center']), ''
        ])
        data.append([
            Paragraph(u'ΠΕΡΙΦΕΡΕΙΑΚΗ ΔΙΕΥΘΥΝΣΗ ΠΡΩΤΟΒΑΘΜΙΑΣ',
                      head_logo['Center']), ''
        ])
        data.append([
            Paragraph(
                u'ΚΑΙ ΔΕΥΤΕΡΟΒΑΘΜΙΑΣ ΕΚΠΑΙΔΕΥΣΗΣ %s' %
                SETTINGS['dide_district'], head_logo['Center']), ''
        ])
        data.append([
            Paragraph(
                u'ΔΙΕΥΘΥΝΣΗ ΔΕΥΤΕΡΟΒΑΘΜΙΑΣ ΕΚΠΑΙΔΕΥΣΗΣ %s' %
                SETTINGS['dide_place_caps'], head_logo['Center']), ''
        ])
        table0 = Table(data, style=tsl, colWidths=[8.0 * cm, 11.0 * cm])
        elements.append(table0)
        elements.append(Paragraph(u' ', heading_style['Spacer']))

        if report['report_type'] == '0':
            elements.append(
                Paragraph(u'ΒΕΒΑΙΩΣΗ ΑΠΟΔΟΧΩΝ', heading_style['Center']))
            if report['type'] > 12:
                elements.append(
                    Paragraph(
                        u'Αποδοχές %s %s' % (report['type'], report['year']),
                        heading_style["Center"]))
            else:
                elements.append(
                    Paragraph(
                        u'Μισθοδοσία %s %s' % (report['type'], report['year']),
                        heading_style['Center']))
            elements.append(Paragraph(u' ', heading_style['Spacer']))

        else:
            elements.append(
                Paragraph(u'ΒΕΒΑΙΩΣΗ ΑΠΟΔΟΧΩΝ %s' % report['year'],
                          heading_style['Center']))
            elements.append(Paragraph(u' ', heading_style['Spacer']))

        if report['emp_type'] == 1:
            headdata = [[
                Paragraph(u'ΑΡ. ΜΗΤΡΩΟΥ', tbl_style['Left']),
                Paragraph('%s' % report['registration_number'] or u'Δ/Υ',
                          tbl_style['Left']),
                Paragraph('ΑΦΜ', tbl_style['Left']),
                Paragraph(u'%s' % report['vat_number'], tbl_style['Left'])
            ],
                        [
                            Paragraph(u'ΕΠΩΝΥΜΟ', tbl_style['Left']),
                            Paragraph('%s' % report['lastname'],
                                      tbl_style['Left']),
                            Paragraph('', tbl_style['Left']),
                            Paragraph('', tbl_style['Left'])
                        ],
                        [
                            Paragraph(u'ΟΝΟΜΑ', tbl_style['Left']),
                            Paragraph('%s' % report['firstname'],
                                      tbl_style['Left']),
                            Paragraph(u'ΒΑΘΜΟΣ - ΚΛΙΜΑΚΙΟ', tbl_style['Left']),
                            Paragraph(
                                u'%s' % report['rank'] if report['rank']
                                is not None else u'Δ/Υ', tbl_style['Left'])
                        ]]
        else:
            headdata = [[
                Paragraph(u'ΑΦΜ', tbl_style['Left']),
                Paragraph('%s' % report['vat_number'], tbl_style['Left']),
                Paragraph('', tbl_style['Left']),
                Paragraph('', tbl_style['Left'])
            ],
                        [
                            Paragraph(u'ΕΠΩΝΥΜΟ', tbl_style['Left']),
                            Paragraph('%s' % report['lastname'],
                                      tbl_style['Left']),
                            Paragraph('', tbl_style['Left']),
                            Paragraph('', tbl_style['Left'])
                        ],
                        [
                            Paragraph(u'ΟΝΟΜΑ', tbl_style['Left']),
                            Paragraph('%s' % report['firstname'],
                                      tbl_style['Left']),
                            Paragraph('', tbl_style['Left']),
                            Paragraph('', tbl_style['Left'])
                        ]]

        table1 = Table(headdata,
                       style=tsh,
                       colWidths=[3 * cm, 6 * cm, 5 * cm, 3 * cm])
        elements.append(table1)
        elements.append(Paragraph(u' ', heading_style['Spacer']))
        del data
        data = []
        total_amount = 0
        total_tax_amount = 0
        for i in report['payment_categories']:
            if len(i['payments']) > 0:  # fixing empty payments
                elements.append(Paragraph(u' ', heading_style['Spacer']))
                s = u'%s' % i['title']
                if (i['start_date'] and i['start_date'] != 'NULL') and (
                        i['end_date'] and i['start_date'] != 'NULL'):
                    s1 = "/".join(list(reversed(i['start_date'].split('-'))))
                    s2 = "/".join(list(reversed(i['end_date'].split('-'))))
                    s += ' (%s - %s) ' % (s1, s2)
                if (i['month'] and i['month'] != 'NULL') and (
                        i['year'] and i['year'] != 'NULL'):
                    if int(i['month']) <= 12:

                        s += ' %s %s' % (months[int(i['month'] - 1)],
                                         i['year'])
                    else:
                        s += u' Άλλο %s' % i['year']
                data.append([Paragraph('%s' % s, tbl_style['BoldLeft'])])
                if data:
                    table2 = Table(data, style=tsh, colWidths=[17 * cm])
                    elements.append(table2)
                del data
                data = []
                data.append([
                    Paragraph('Αποδοχές', tbl_style['BoldLeft']),
                    Paragraph('Κρατήσεις', tbl_style['BoldLeft'])
                ])
                table3 = Table(data, style=ts, colWidths=[8.5 * cm, 8.5 * cm])
                elements.append(table3)
                del data
                gret = []
                de = []
                data = []
                grnum = 0
                denum = 0
                for p in i['payments']:
                    if p['type'] == 'gr' or p['type'] == 'et':
                        s = u'%s' % p['code']
                        gret.append([
                            Paragraph(s, tbl_style['Left']),
                            Paragraph('%.2f €' % p['amount'],
                                      tbl_style['Right'])
                        ])
                        if p['type'] == 'gr':
                            grnum += float(p['amount'])
                    else:
                        s = u'%s' % p['code']
                        if p['info'] is not None:
                            s = s + " (%s)" % p['info']
                        if int(p['code_tax']) == 1:
                            total_tax_amount += p['amount']
                        de.append([
                            Paragraph(s, tbl_style['Left']),
                            Paragraph('%.2f €' % p['amount'],
                                      tbl_style['Right'])
                        ])
                        denum += float(p['amount'])
                _get = lambda l, i: l[i] if i < len(l) else ['', '']
                data = [
                    _get(gret, i) + _get(de, i)
                    for i in range(0, max(len(gret), len(de)))
                ]
                if len(data) > 0:
                    table4 = Table(
                        data,
                        style=ts,
                        colWidths=[6.5 * cm, 2.0 * cm, 6.5 * cm, 2.0 * cm])
                    elements.append(table4)
                total_amount += float(grnum) - float(denum)
                del data
                data = []
                elements.append(Paragraph(u' ', heading_style['Spacer']))
            elements.append(Paragraph(u' ', heading_style['Spacer']))
            elements.append(Paragraph(u' ', heading_style['Spacer']))
            if data:
                del data
        if report['report_type'] == '0':
            data = []
            data.append([Paragraph('Πληρωτέο', tbl_style['BoldLeft'])])
            table5 = Table(data, style=ts, colWidths=[17 * cm])
            elements.append(table5)
            del data
            data = []

            if report['net_amount1'] != '0' and report['net_amount2'] != '0':
                data.append([
                    Paragraph('Α\' δεκαπενθήμερο', tbl_style['Left']),
                    Paragraph('%.2f €' % numtoStr(report['net_amount1']),
                              tbl_style['Right']), '', ''
                ])
                data.append([
                    Paragraph('Β\' δεκαπενθήμερο', tbl_style['Left']),
                    Paragraph('%.2f €' % numtoStr(report['net_amount2']),
                              tbl_style['Right']), '', ''
                ])
            else:
                data.append([
                    Paragraph('Σύνολο', tbl_style['Left']),
                    Paragraph('%.2f €' % total_amount, tbl_style['Right']), '',
                    ''
                ])
                total_amount = 0

            table5 = Table(data,
                           style=ts,
                           colWidths=[6.5 * cm, 2.0 * cm, 6.5 * cm, 2.0 * cm])
            elements.append(table5)
            del data
        else:
            data = []
            data.append([
                Paragraph('Καθαρό Ποσό', tbl_style['Left']),
                Paragraph('%.2f €' % total_amount, tbl_style['Right']),
                Paragraph('%s' % SETTINGS.get_desc('tax_reduction_factor'),
                          tbl_style['Left']),
                Paragraph(
                    '%.2f €' % (total_tax_amount /
                                float(SETTINGS['tax_reduction_factor'])),
                    tbl_style['Right'])
            ])
            total_amount = 0
            total_tax_amount = 0
            table5 = Table(data,
                           style=ts,
                           colWidths=[6.5 * cm, 2.0 * cm, 6.5 * cm, 2.0 * cm])
            elements.append(table5)
            del data

        today = datetime.date.today()
        elements.append(Paragraph(u' ', heading_style['Spacer']))
        elements.append(Paragraph(u' ', heading_style['Spacer']))

        data = []
        data.append([
            Paragraph(u' ', signature['Center']),
            Paragraph(
                u'Ρόδος, %s / %s / %s' % (today.day, today.month, today.year),
                signature['Center'])
        ])

        sign = os.path.join(settings.MEDIA_ROOT, "signature.png")
        im = Image(sign)
        im.drawHeight = 3.2 * cm
        im.drawWidth = 6.5 * cm

        data.append([Paragraph(u' ', signature['Center']), im])

        #        data.append([Paragraph(u' ', signature['Center']),
        #                     Paragraph(u' ', signature['Center'])])
        #        data.append([Paragraph(u' ', signature['Center']),
        #                     Paragraph(u'Ο Διευθυντής', signature['Center'])])
        #        data.append([Paragraph(u' ', signature['Center']),
        #                     Paragraph(u' ', signature['Center'])])
        #        data.append([Paragraph(u' ', signature['Center']),
        #                     Paragraph(u' ', signature['Center'])])
        #        data.append([Paragraph(u' ', signature['Center']),
        #                     Paragraph(u' ', signature['Center'])])
        #        data.append([Paragraph(u' ', signature['Center']),
        #                     Paragraph(u' ', signature['Center'])])
        #        data.append([Paragraph(u' ', signature['Center']),
        #                     Paragraph(SETTINGS['manager'], signature['Center'])])

        table6 = Table(data, style=tsf, colWidths=[11.0 * cm, 6.0 * cm])
        elements.append(table6)
        elements.append(PageBreak())
    return elements
	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/>" + str(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/>"  + str(self.sito), styNormal)
		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. Individuo</b><br/>"  + str(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/>" + str(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/>" + 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>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

		#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', '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
Ejemplo n.º 36
0
def create_test_report_pdf(job_result_dict):
    # print job_result_dict
    story = []
    stylesheet = getSampleStyleSheet()

    normalStyle = stylesheet['Normal']
    curr_date = time.strftime("%Y-%m-%d", time.localtime())
    reportfilename = "Estuary-Test_Report-%s.pdf" % (curr_date)
    rpt_title = '<para autoLeading="off" fontSize=15 align=center><b>[ Estuary ] Test Report %s</b><br/><br/><br/></para>' % (
        curr_date)
    story.append(Paragraph(rpt_title, normalStyle))

    rpt_ps = '<para autoLeading="off" fontSize=8 align=center>( This mail is send by Jenkins automatically, don\'t reply )</para>'
    story.append(Paragraph(rpt_ps, normalStyle))

    text = '''<para autoLeading="off" fontSize=12><br /><font color=black>1.General Report</font><br /><br /></para>'''
    story.append(Paragraph(text, normalStyle))

    # pie image
    pieimg = Image('baseinfo_pie.jpg')
    pieimg.drawHeight = 320
    pieimg.drawWidth = 480
    story.append(pieimg)

    # calculate the pass number for each suit
    test_suite_dict = {}
    for job_id in job_result_dict.keys():
        for item in job_result_dict[job_id]:
            if item['suite'] not in test_suite_dict:
                test_suite_dict[item['suite']] = {}
                if item['result'] not in test_suite_dict[item['suite']]:
                    test_suite_dict[item['suite']][item['result']] = 1
                else:
                    value = test_suite_dict[item['suite']][item['result']]
                    value = value + 1
                    test_suite_dict[item['suite']][item['result']] = value
            else:
                if item['result'] not in test_suite_dict[item['suite']]:
                    test_suite_dict[item['suite']][item['result']] = 1
                else:
                    value = test_suite_dict[item['suite']][item['result']]
                    value = value + 1
                    test_suite_dict[item['suite']][item['result']] = value

    component_data = [['TestSuite', 'Passes', 'Fails', 'Totals']]
    for test_suite in sorted(test_suite_dict.keys()):
        passnum = 0
        failnum = 0
        if 'pass' in test_suite_dict[test_suite]:
            passnum = test_suite_dict[test_suite]['pass']
        if 'fail' in test_suite_dict[test_suite]:
            failnum = test_suite_dict[test_suite]['fail']
        totalnum = passnum + failnum
        data = [test_suite, passnum, failnum, totalnum]
        component_data.append(data)

    component_table = Table(component_data, colWidths=[150, 60, 60, 60])
    component_table.setStyle(
        TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 8),  #font size
            ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue),  #
            ('ALIGN', (-1, 0), (-2, 0), 'RIGHT'),  #
            ('VALIGN', (-1, 0), (-2, 0), 'MIDDLE'),  #
            ('LINEBEFORE', (0, 0), (0, -1), 0.1, colors.grey),  #
            ('TEXTCOLOR', (0, 1), (-2, -1), colors.black),  #
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),  #
        ]))
    story.append(component_table)

    text = '''<para autoLeading="off" fontSize=12><br /><font color=black>2.Test Suite Result Detail</font><br /><br /></para>'''
    story.append(Paragraph(text, normalStyle))
    component_data = [['JobID', 'Suite', 'Name', 'Result']]
    for job_id in sorted(job_result_dict.keys()):
        for item in sorted(job_result_dict[job_id], key=lambda x: x['suite']):
            if item['suite'] != 'lava':
                component_data.append(
                    [job_id, item['suite'], item['name'], item['result']])

    component_table = Table(component_data)
    component_table.setStyle(
        TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 8),  #font size
            ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue),  #
            ('ALIGN', (-1, 0), (-2, 0), 'RIGHT'),  #
            ('VALIGN', (-1, 0), (-2, 0), 'MIDDLE'),  #
            ('LINEBEFORE', (0, 0), (0, -1), 0.1, colors.grey),  #
            ('TEXTCOLOR', (0, 1), (-2, -1), colors.black),  #
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),  #
        ]))
    story.append(component_table)

    text = '''<para autoLeading="off" fontSize=12><br /><font color=black>3.Different Scope Pass Number</font><br /><br /></para>'''
    story.append(Paragraph(text, normalStyle))

    # bar image
    barimg = Image('baseinfo_bar.jpg')
    barimg.drawHeight = 320
    barimg.drawWidth = 480
    story.append(barimg)

    # generate pdf
    doc = SimpleDocTemplate('resultfile.pdf')
    doc.build(story)
Ejemplo n.º 37
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 REPERTI LAPIDEI<br/>" + str(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')
		alma_path = ('%s%s%s') % (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 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
Ejemplo n.º 38
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 DOCUMENTAZIONE<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)
        nome_doc = Paragraph(
            "<b>Nome documentazione</b><br/>" + str(self.nome_doc), styNormal)
        data = Paragraph("<b>Data</b><br/>" + str(self.data), styNormal)

        # 2 row
        tipo_documentazione = Paragraph(
            "<b>Tipo documentazione</b><br/>" + str(self.tipo_documentazione),
            styNormal)
        sorgente = Paragraph("<b>Sorgente</b><br/>" + str(self.sorgente),
                             styNormal)
        scala = Paragraph("<b>Scala</b><br/>" + str(self.scala), styNormal)

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

        # 4 row
        note = Paragraph("<b>Note</b><br/>" + str(self.note), styDescrizione)
        #		nr_cassa = Paragraph("<b>Nr. Cassa</b><br/>" + unicode(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', '08',
             '09'],  # 1 row ok
            [
                tipo_documentazione, '01', '02', nome_doc, '04', '05', '06',
                scala, '08', '09'
            ],  # 2 row ok
            [note, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 3 row ok
            [
                data, '01', '02', '03', '04', disegnatore, '06', '07', '08',
                '09'
            ]  # 4 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), (9, 1)),  # sito
            #					('SPAN', (7,1),(9,1)),   #data

            # 2 row
            ('SPAN', (0, 2), (2, 2)),  # tipo_documentazione
            ('SPAN', (3, 2), (6, 2)),  # nome_doc
            ('SPAN', (7, 2), (9, 2)),  # scala
            #					('VALIGN',(0,2),(9,2),'TOP'),

            # 3 row
            ('SPAN', (0, 3), (9, 3)),  # note
            ('VALIGN', (0, 3), (9, 3), 'TOP'),

            # 5 row
            ('SPAN', (0, 4), (4, 4)),  # data
            ('SPAN', (5, 4), (9, 4)),  # disegnatore
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

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

        return t
Ejemplo n.º 39
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
Ejemplo n.º 40
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 - DIVELOG 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
        logo.hAlign = "CENTER"
        logo2.hAlign = "CENTER"
        #1 row
        divelog = Paragraph("<b>Dive log number:  </b>" + str(self.divelog_id),
                            styNormal)
        area_id = Paragraph("<b>Area</b><br/>" + str(self.area_id), styNormal)
        years = Paragraph("<b>Year</b><br/>" + str(self.years), styNormal)
        diver_1 = Paragraph("<b>Diver 1</b><br/>" + self.diver_1, styNormal)
        diver_2 = Paragraph("<b>Diver 2</b><br/>" + self.diver_2, styNormal)
        diver_3 = Paragraph("<b>Additional Diver</b><br/>" + self.diver_3,
                            styNormal)
        standby = Paragraph("<b>Standby Diver</b><br/>" + self.standby_diver,
                            styNormal)
        tender = Paragraph("<b>Dive Supervisor</b><br/>" + self.tender,
                           styNormal)
        bar_start = Paragraph(
            "<b>Bar Start Diver 1: </b>" + self.bar_start + "<br/>"
            "<b>Bar Start Diver 2: </b>" + self.bar_start_2, styNormal)
        bar_end = Paragraph(
            "<b>Bar End Diver 1: </b>" + self.bar_end + "<br/>"
            "<b>Bar End Diver 2: </b>" + self.bar_end_2, styNormal)
        bottom_time = Paragraph("<b>Bottom Time</b><br/>" + self.bottom_time,
                                styNormal)
        temperature = Paragraph(
            "<b>UW Temperature</b><br/>" + self.temperature, styNormal)
        visibility = Paragraph("<b>UW Visibility</b><br/>" + self.visibility,
                               styNormal)
        current = Paragraph(
            "<b>UW Current direction & strength</b><br/>" + self.current_,
            styNormal)
        wind = Paragraph("<b>Wind</b><br/>" + self.wind, styNormal)
        breathing_mix = Paragraph(
            "<b>Breathing mix</b><br/>" + self.breathing_mix, styNormal)
        max_depth = Paragraph("<b>Max Depth</b><br/>" + self.max_depth,
                              styNormal)
        surface_interval = Paragraph(
            "<b>Surface Interval</b><br/>" + self.surface_interval, styNormal)
        time_in = Paragraph("<b>Time in</b><br/>" + self.time_in, styNormal)
        time_out = Paragraph("<b>Time out</b><br/>" + self.time_out, styNormal)
        date_ = Paragraph("<b>Date</b><br/>" + self.date_, styNormal)
        dp = Paragraph(
            "<b>DP Diver 1: </b>" + self.dp + "<br/>"
            "<b>DP Diver 2: </b>" + self.dp_2, styNormal)
        # photos_taken = Paragraph("<b>Photos Taken</b><br/>"  , styInt)
        # videos_taken = Paragraph("<b>Videos taken</b><br/>"  , styInt)
        conditions = Paragraph("<b>U/W Conditions</b><br/>", styInt)
        camera_of = Paragraph("<b>Camera: </b>" + self.camera_of, styNormal)
        photo_nbr = Paragraph(
            "<b>Number of pictures: </b>" + str(self.photo_nbr), styNormal)
        video_nbr = Paragraph(
            "<b>Number of videos: </b>" + str(self.video_nbr), styNormal)
        sito = Paragraph("<b>Location: </b>" + str(self.sito), styNormal)
        layer = Paragraph("<b>Layer</b><br/>" + str(self.layer), styNormal)

        task = ''
        try:
            task = Paragraph("<b>Task</b><br/>" + self.task, styDescrizione)
        except:
            pass
        result = ''
        try:
            result = Paragraph("<b>Result</b><br/>" + self.result,
                               styDescrizione)
        except:
            pass
        comments_ = ''
        try:
            comments_ = Paragraph("<b>Comments</b><br/>" + self.comments_,
                                  styDescrizione)
        except:
            pass
        #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', divelog,
                '10', '11', '12', '13', '14', '15', '16', '17'
            ],  #1 row ok
            [
                diver_1, '01', '02', '03', '04', '05', date_, '07', '08', '09',
                '10', '11', area_id, '13', '14', '15', '16', '17'
            ],  #2 row ok
            [
                diver_2, '01', '02', '03', '04', '05', time_in, '07', '08',
                '09', '10', '11', time_out, '13', '14', '15', '16', '17'
            ],  #3 row ok
            [
                standby, '01', '02', '03', '04', '05', bottom_time, '07', '08',
                '09', '10', '11', max_depth, '13', '14', '15', '16', '17'
            ],  #4 row ok
            [
                tender, '01', '02', '03', '04', '05', bar_start, '07', '08',
                '09', '10', '11', bar_end, '13', '14', '15', '16', '17'
            ],  #5 row ok
            [
                dp, '01', '02', '03', '04', '05', breathing_mix, '07', '08',
                '09', '10', '11', wind, '13', '14', '15', '16', '17'
            ],  #6 row ok
            [
                photo_nbr, '01', '02', '03', '04', '05', video_nbr, '07', '08',
                '09', '10', '11', camera_of, '13', '14', '15', '16', '17'
            ],  #7
            [
                task, '01', '02', '03', '04', '05', '06', '07', '08', '09',
                '10', '11', '12', '13', '14', '15', '16', '17'
            ],  #8 row ok
            [
                result, '01', '02', '03', '04', '05', '06', '07', '08', '09',
                '10', '11', '12', '13', '14', '15', '16', '17'
            ],  #9 row ok
            [
                comments_, '01', '02', '03', '04', '05', '06', '07', '08',
                '09', '10', '11', '12', '13', '14', '15', '16', '17'
            ],  #10 row ok
            [
                conditions, '01', '02', '03', '04', '05', '08', '07', '08',
                '09', '10', '11', '12', '13', '14', '15', '16', '17'
            ],  #11 row ok
            [
                current, '01', '02', '03', '04', '05', visibility, '07', '08',
                '09', '10', '11', temperature, '13', '14', '15', '16', '17'
            ],  #12

            # [photo_id,'01', '02', '03', '04','05', video_id, '07', '08', '09','10','11',current,'13', '14','15','16','17'], #13
        ]
        #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)),  #time_in
            ('SPAN', (12, 3), (17, 3)),  #time_out
            ('SPAN', (0, 4), (5, 4)),  #standby
            ('SPAN', (6, 4), (11, 4)),  #bottom_time
            ('SPAN', (12, 4), (17, 4)),  #maxdepth
            ('SPAN', (0, 5), (5, 5)),  #standby
            ('SPAN', (6, 5), (11, 5)),  #bottom_time
            ('SPAN', (12, 5), (17, 5)),  #maxdepth 
            ('SPAN', (0, 6), (5, 6)),  #standby
            ('SPAN', (6, 6), (11, 6)),  #bottom_time
            ('SPAN', (12, 6), (17, 6)),  #maxdepth 
            ('SPAN', (0, 7), (5, 7)),  #standby
            ('SPAN', (6, 7), (11, 7)),  #standby
            ('SPAN', (12, 7), (17, 7)),  #standby
            ('SPAN', (0, 8), (17, 8)),  #standby
            ('SPAN', (0, 9), (17, 9)),  #standby
            ('SPAN', (0, 10), (17, 10)),  #standby
            # ('SPAN', (6,10),(11,10)),  #bottom_time
            # ('SPAN', (12,10),(17,10)),  #maxdepth
            ('SPAN', (0, 11), (17, 11)),  #standby
            ('SPAN', (0, 12), (5, 12)),  #bottom_time
            ('SPAN', (6, 12), (11, 12)),  #maxdepth 
            ('SPAN', (12, 12), (17, 12)),  #maxdepth 

            # ('SPAN', (0,13),(5,13)),  #standby
            # ('SPAN', (6,13),(11,13)),  #bottom_time
            # ('SPAN', (12,13),(17,13)),  #maxdepth
        ]
        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
Ejemplo n.º 41
0
    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()
Ejemplo n.º 42
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 INVENTARIO REPERTI<br/>" + str(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/>" + str(self.sito), styNormal)
        nr_inventario = Paragraph(
            "<b>Nr. Inventario</b><br/>" + str(self.numero_inventario),
            styNormal)

        #2 row
        riferimenti_stratigrafici = Paragraph(
            "<b>Riferimenti stratigrafici</b>", styNormal)
        area = Paragraph("<b>Area</b><br/>" + str(self.area), styNormal)
        us = Paragraph("<b>US</b><br/>" + str(self.us), styNormal)

        #3 row
        criterio_schedatura = Paragraph(
            "<b>Criterio schedatura</b><br/>" + self.criterio_schedatura,
            styNormal)
        tipo_reperto = Paragraph(
            "<b>Tipo reperto</b><br/>" + self.tipo_reperto, styNormal)
        definizione = Paragraph("<b>Definizione</b><br/>" + self.definizione,
                                styNormal)

        #4 row
        stato_conservazione = Paragraph(
            "<b>Stato Conservazione</b><br/>" + self.stato_conservazione,
            styNormal)
        datazione = Paragraph("<b>Datazione</b><br/>" + self.datazione_reperto,
                              styNormal)

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

        #6 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 misura: %s, Quantita': %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]))
                    except:
                        pass
                else:
                    try:
                        elementi_reperto += (
                            "<br/>Elemento rinvenuto: %s, Unita' di misura: %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)

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

        #8 row
        tecnologie = ''
        if eval(self.tecnologie) > 0:
            for i in eval(self.tecnologie):
                if tecnologie == '':
                    try:
                        tecnologie += (
                            "Tipo tecnologia: %s, Posizione: %s, Tipo quantita': %s, Unita' di misura: %s, Quantita': %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]), str(
                            i[3]), str(i[4]))
                    except:
                        pass
                else:
                    try:
                        tecnologie += (
                            "<br/>Tipo tecnologia: %s, Posizione: %s, Tipo quantita': %s, Unita' di misura: %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)

        #9 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 += (
                            "<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

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

        #11 row
        repertato = Paragraph("<b>Repertato</b><br/>" + self.repertato,
                              styNormal)
        diagnostico = Paragraph("<b>Diagnostico</b><br/>" + self.diagnostico,
                                styNormal)

        #12 row
        riferimenti_magazzino = Paragraph("<b>Riferimenti magazzino</b>",
                                          styNormal)

        #13 row
        lavato = Paragraph("<b>Lavato</b><br/>" + self.lavato, styNormal)
        nr_cassa = Paragraph("<b>Nr. Cassa</b><br/>" + self.nr_cassa,
                             styNormal)
        luogo_conservazione = Paragraph(
            "<b>Luogo di conservazione</b><br/>" + self.luogo_conservazione,
            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_inventario,
                '09'
            ],  #1 row ok
            [
                riferimenti_stratigrafici, '01', '02', '03', area, '05', '06',
                us, '08', '09'
            ],  #2 row ok
            [
                tipo_reperto, '01', '02', criterio_schedatura, '04', '05',
                definizione, '07', '08', '09'
            ],  #3 row ok
            [
                datazione, '01', '02', '03', '04', stato_conservazione, '06',
                '07', '08', '09'
            ],  #4 row ok
            [
                descrizione, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  #5 row ok
            [
                elementi_reperto, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #6 row ok
            [
                misurazioni, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  #7 row ok
            [tecnologie, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  #8 row ok
            [rif_biblio, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  #9 row ok
            [
                riferimenti_stratigrafici, '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #10 row ok
            [
                repertato, '01', '02', diagnostico, '04', '05', '06', '07',
                '08', '09'
            ],  #11 row ok
            [
                riferimenti_magazzino, '01', '02', '03', '04', '05', '06',
                '07', '08', '09'
            ],  #12 row ok
            [
                lavato, '01', '02', nr_cassa, '04', '05', luogo_conservazione,
                '07', '08', '09'
            ]  #13 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)),  #nr_inventario

            #2 row
            ('SPAN', (0, 2), (3, 2)),  #rif stratigrafici
            ('SPAN', (4, 2), (6, 2)),  #area
            ('SPAN', (7, 2), (9, 2)),  #us
            ('VALIGN', (0, 2), (9, 2), 'TOP'),

            #3 row
            ('SPAN', (0, 3), (2, 3)),  #tipo_reperto
            ('SPAN', (3, 3), (5, 3)),  #criterio_schedatura
            ('SPAN', (6, 3), (9, 3)),  #definizione
            ('VALIGN', (0, 3), (9, 3), 'TOP'),

            #4 row
            ('SPAN', (0, 4), (4, 4)),  #datazione
            ('SPAN', (5, 4), (9, 4)),  #conservazione

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

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

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

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

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

            #10 row
            ('SPAN', (0, 10), (9, 10)),  #Riferimenti stratigrafici - Titolo

            #11 row
            ('SPAN', (0, 11), (2, 11)),  #Riferimenti stratigrafici - area
            ('SPAN', (3, 11), (9, 11)),  #Riferimenti stratigrafici - us

            #12 row
            ('SPAN', (0, 12), (9, 12)),  #Riferimenti magazzino - Titolo

            #13 row
            ('SPAN', (0, 13), (2, 13)),  #Riferimenti magazzino - lavato
            ('SPAN', (3, 13), (5, 13)),  #Riferimenti magazzino - nr_cassa
            ('SPAN', (6, 13),
             (9, 13)),  #Riferimenti magazzino - luogo conservazione
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

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

        return t
Ejemplo n.º 43
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
Ejemplo n.º 44
0
    def generate_pdf(self):

        name = self.tableWidget.item(self.tableWidget.currentRow(), 1).text()
        Fname = self.tableWidget.item(self.tableWidget.currentRow(), 2).text()
        dob = self.tableWidget.item(self.tableWidget.currentRow(), 3).text()
        level = self.tableWidget.item(self.tableWidget.currentRow(), 4).text()
        branch = self.tableWidget.item(self.tableWidget.currentRow(), 5).text()
        regid = self.tableWidget.item(self.tableWidget.currentRow(), 6).text()

        info = [['Name : {}'.format(name)],
                ['Father\'s name : {}'.format(Fname)],
                ['Level : {}'.format(level)], ['Branch : {}'.format(branch)],
                ['Registration ID : {}'.format(regid)],
                ['DoB : {}'.format(dob)]]

        picFN = '{}.jpg'.format(regid)
        with open(picFN, 'wb') as f:
            Code39(regid, writer=ImageWriter()).write(f)

        buffer = 'buffer.pdf'
        fileName = '{}.pdf'.format(regid)
        pdf = SimpleDocTemplate(buffer,
                                pagesize=A4,
                                leftMargin=20,
                                rightMargin=20,
                                topMargin=80,
                                bottomMargin=300)

        print("HERE1")

        picture = Image('logo.jpg')
        picture.drawWidth = 150
        picture.drawHeight = 150
        picTable = Table(
            [[picture]],
            150,
            150,
        )

        print('here2')
        picture = Image(picFN)
        picture.drawWidth = 125
        picture.drawHeight = 50
        picTable2 = Table([[picture]], 375, 150, hAlign="BOTTOM")

        info_table = Table(info, 200, 20)
        print('here2')
        # add style
        info_style = TableStyle([('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                                 ('FONTSIZE', (0, 0), (-1, -1), 15),
                                 ('BOTTOMPADDING', (0, 0), (-1, -1), 5)
                                 # ('BOTTOMPADDING', (0, -1), (-1, -1), 5)
                                 ])

        product_style1 = TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('BOTTOMPADDING', (0, 0), (-1, -1), -5),
        ])

        # 3) Add borders('GRID', (0, 0), (-1, -1), 1, colors.purple),
        product_style2 = TableStyle([
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('GRID', (0, 0), (-1, -1), 1, colors.black)
        ])
        """
        product_table.setStyle(product_style2)
        amount_table.setStyle(product_style1)"""

        # print("Style created")

        picTable.setStyle(info_style)
        info_table.setStyle(info_style)
        infopic = Table([[info_table, picTable]], [400, 150])
        picTable2.setStyle(product_style1)
        infopic.setStyle(info_style)
        mainTable = Table([[infopic], [picTable2, " "]])
        elems = []
        elems.append(mainTable)
        # print("Appended")

        print('here')

        pdf.build(elems)
        # wb.open_new(r'{}/{}'.format(os.getcwd(), buffer))

        pdf_file = "WM.pdf"
        watermark = buffer
        merged_file = fileName
        input_file = open(pdf_file, 'rb')
        input_pdf = PyPDF2.PdfFileReader(pdf_file)
        watermark_file = open(watermark, 'rb')
        watermark_pdf = PyPDF2.PdfFileReader(watermark_file)
        pdf_page = input_pdf.getPage(0)
        watermark_page = watermark_pdf.getPage(0)
        pdf_page.mergePage(watermark_page)
        output = PyPDF2.PdfFileWriter()
        output.addPage(pdf_page)
        merged_file = open(fileName, 'wb')
        output.write(merged_file)
        merged_file.close()
        watermark_file.close()
        input_file.close()

        wb.open_new(r'{}/{}'.format(os.getcwd(), fileName))
Ejemplo n.º 45
0
def write():
    st.header("Stregkodegenererator til delehold")

    if st.checkbox(
            "Vis hjælp til at lokalisere elevoversigt fra Cicero og Lectio"):
        st.info(
            "__Elevoversigt fra Cicero:__  \n"
            "Start med at uploade en elevoversigt fra cicero.  \n"
            "Åben Cicero og gå til 'Cirkulation' --> 'Låner'.  \n"
            "Angiv alle klasser under 'Lånergrupper' og søg.  \n"
            "Tryk på 'Print og eksporter' i venstre hjørne og vælg 'Eksporter viste: CSV'.  \n"
            "  \n"
            "__Elevoversigt fra Lectio:__  \n"
            "Log ind på Lectio.  \n"
            "Gå til 'Hovedmenu' og vælg 'Importer/Eksporter data'.  \n"
            "Tryk på 'Excel' under kolonnen 'Eksporter' ud fra rækken 'Elever'."
        )

    # upload fra Cicero
    st.write("__Upload elevoversigt fra Cicero__")
    Elever_Cicero_file = st.file_uploader(
        "Uploade eksport af fuld elevoversigt fra Cicero i csv-format",
        type="csv")

    if Elever_Cicero_file is not None:
        Elever_Cicero_data = pd.read_csv(Elever_Cicero_file,
                                         sep=';',
                                         na_filter=False)
        Elever_Cicero_data.drop(
            ["Adresse", "Postnummer & by", "Telefon", "E-mail"],
            axis=1,
            inplace=True)
        Elever_Cicero_data = Elever_Cicero_data.rename(
            columns={"Lånergrupper": "Stamklasse"})

        if st.checkbox("Vis elevoversigt fra Cicero"):
            st.write(Elever_Cicero_data)

    # upload fra Lectio
    st.write("__Upload elevoversigt fra Lectio__")
    Elever_Lectio_file = st.file_uploader(
        "Uploade eksport af fuld elevoversigt fra Lectio i xlsx-format",
        type="xlsx")

    if Elever_Lectio_file is not None:
        Elever_Lectio_data = pd.read_excel(Elever_Lectio_file,
                                           sep=';',
                                           na_filter=False)
        Elever_Lectio_data.drop([
            "Id", "PNr", "Afdeling", "Brugernavn", "CPR-NUMMER", "TELEFON 1",
            "TELEFON 2", "Adresse CO", "Adresse", "Stednavn", "Postnummer",
            "Kommunenr", "Email"
        ],
                                axis=1,
                                inplace=True)
        Elever_Lectio_data = Elever_Lectio_data.rename(
            columns={"KaldeNavn": "Navn"})

        if st.checkbox("Vis elevoversigt fra Lectio"):
            st.write(Elever_Lectio_data)

        st.write("__Hvilke holdoversigter ønskes genereret?__")
        # Lav oversigt over alle delehold
        Hold = set()
        for line in Elever_Lectio_data["Hold"]:
            Hold_temp = line.split(",")
            for elem in Hold_temp:
                if elem.startswith(" "):
                    Hold.add(elem[1:])
                else:
                    Hold.add(elem)
        Hold = list(Hold)
        Hold.sort()
        Valgte_hold = st.multiselect("Du kan vælge flere hold på én gang.",
                                     options=Hold)

        st.write("__Hvilke stamklasseoversigter ønskes genereret?__")
        # Lav oversigt over alle stamklasser
        Stamklasse = set()
        for line in Elever_Lectio_data["Stamklasse"]:
            Stamklasse_temp = line.split(",")
            for elem in Stamklasse_temp:
                if elem.startswith(" "):
                    Stamklasse.add(elem[1:])
                else:
                    Stamklasse.add(elem)
        Stamklasse = list(Stamklasse)
        Stamklasse.sort()
        Valgte_Stamklasse = st.multiselect(
            "Du kan vælge flere stamklasser på én gang.", options=Stamklasse)

    # Generer stregkoder
    if Elever_Cicero_file and Elever_Lectio_file is not None and len(
            Hold) != 0:
        #generate_barcodes(Elever_Cicero_data, Elever_Lectio_data, Valgte_hold)

        # Lav en sammensat dataframe af de to uploadede filer
        Elever_merged_data = pd.merge(Elever_Cicero_data,
                                      Elever_Lectio_data,
                                      on=["Navn"])
        #Elever_merged_data = pd.merge(Elever_Cicero_data,Elever_Lectio_data, on=["Navn", "Stamklasse"])
        Elever_merged_data = Elever_merged_data.sort_values("Navn", axis=0)
        #Elever_merged_data = Elever_merged_data.sort_values("Navn", axis=0, ignore_index=True)
        if st.checkbox("Vis samlet elevoversigt"):
            st.write(Elever_merged_data)

        # Find elever som ikke eksisterer i begge filer
        Elever_med_fejl = pd.concat([Elever_Cicero_data, Elever_Lectio_data
                                     ]).drop_duplicates(subset=['Navn'],
                                                        keep=False)
        #Elever_med_fejl = pd.concat([Elever_Cicero_data,Elever_Lectio_data]).drop_duplicates(subset = ['Navn','Stamklasse'], keep=False)

        if len(Elever_med_fejl) == 0:
            st.info(
                "Der var ingen elever som kun var at finde i en enkelt fil.")
        elif len(Elever_med_fejl) != 0:
            st.warning("__Følgende elever var ikke at finde i begge filer:__")
            st.write(Elever_med_fejl)

        # Den resterende kode sættes i gang når brugeren ønsker det
        if st.button("Generer filer med stregkoder for de valgte hold"):
            # Genereate folder to barcodes
            try:
                os.mkdir('Barcodes')
            except OSError:
                print("Creation of the directory %s failed" % path)

            # Generer stregkodeark for hvert af de valgte hold
            for hold in range(0, len(Valgte_Stamklasse)):

                # Generer dataframe hvor hvert af de valgte hold
                Valgt_hold_temp = pd.DataFrame(
                    columns=["Navn", "Lånernummer", "Stamklasse", "Hold"])
                for row in range(0, len(Elever_merged_data["Stamklasse_y"])):
                    if Valgte_Stamklasse[hold] in Elever_merged_data[
                            "Stamklasse_y"][row]:
                        if len(Valgt_hold_temp) == 0:
                            Valgt_hold_temp = Elever_merged_data.loc[[row]]
                        elif len(Valgt_hold_temp) != 0:
                            Valgt_hold_temp = Valgt_hold_temp.append(
                                Elever_merged_data.loc[[row]],
                                sort=False,
                                ignore_index=True)

                # Generer stregkolder for hvert af de valgte hold
                code39_class = barcode.get_barcode_class('code39')
                opts = {
                    'module_width': 0.2,
                    'module_height': 8.0,
                    'font_size': 15,
                    'text_distance': 1
                }
                for elem in range(0, len(Valgt_hold_temp['Lånernummer'])):
                    Loannumber = Valgt_hold_temp['Lånernummer'][elem]
                    code39 = code39_class(str(Loannumber),
                                          writer=ImageWriter(),
                                          add_checksum=False)
                    save_code = code39.save('Barcodes/' + str(Loannumber),
                                            options=opts)

                ### Generer tom PDF ###
                dato = dt.date.today()
                Filnavn = str(
                    Valgte_Stamklasse[hold]) + ' - ' + str(dato) + '.pdf'
                save_name = os.path.join(os.path.expanduser("~"), "Desktop",
                                         Filnavn)
                pdf = SimpleDocTemplate(save_name,
                                        pagesize=A4,
                                        rightMargin=15,
                                        leftMargin=15,
                                        topMargin=15,
                                        bottomMargin=15)

                # Data for header
                header_data = [[
                    'Antal elever: ' + str(len(Valgt_hold_temp)),
                    str(dato),
                    str(Valgte_Stamklasse[hold])
                ]]

                # List of list med navne og barcodes
                names = []
                images = []
                for elem in range(0, len(Valgt_hold_temp['Lånernummer'])):
                    # Data om navne
                    Navn = Valgt_hold_temp["Navn"][elem]
                    names.append(Navn)
                    # Data om barcodes
                    Loannumber = Valgt_hold_temp['Lånernummer'][elem]
                    image = PIL.Image.open('Barcodes/' + str(Loannumber) +
                                           '.png')
                    width, height = image.size
                    image_Loannumber = Image('Barcodes/' + str(Loannumber) +
                                             '.png')
                    image_Loannumber.drawWidth = width / 4
                    image_Loannumber.drawHeight = height / 4
                    images.append(image_Loannumber)

                # Generer tabel ud fra List of list med navne og barcodes
                data = []
                start = 0
                s**t = 3
                for elem in range(0, len(names), 3):
                    data += [names[start:s**t], images[start:s**t]]
                    start += 3
                    s**t += 3

                # Generer tabeller
                header = Table(header_data, colWidths=2.55 * inch)
                table = Table(data, colWidths=2.55 * inch)

                # table style header
                ts = TableStyle([('FONTSIZE', (0, 0), (-1, -1), 12),
                                 ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                                 ('LEFTPADDING', (0, 0), (-1, -1), 1),
                                 ('RIGHTPADDING', (0, 0), (-1, -1), 1),
                                 ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
                                 ('TOPPADDING', (0, 0), (-1, -1), 5)])
                header.setStyle(ts)

                # table style til stregkoder og navne
                ts = TableStyle([('FONTSIZE', (0, 0), (-1, -1), 9),
                                 ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                                 ('LEFTPADDING', (0, 0), (-1, -1), 1),
                                 ('RIGHTPADDING', (0, 0), (-1, -1), 1),
                                 ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
                                 ('TOPPADDING', (0, 0), (-1, -1), 1)])
                table.setStyle(ts)

                # Tilføj elemter til pdf
                elems = []
                elems.append(header)
                elems.append(table)
                pdf.build(elems)

            if len(Valgte_Stamklasse) == 1:
                st.success(
                    'Succes!  \n' + str(len(Valgte_Stamklasse)) +
                    ' PDF-fil er genereret. Filerne er placeret på skrivebordet.'
                )
            elif len(Valgte_Stamklasse) > 1:
                st.success(
                    'Succes!  \n' + str(len(Valgte_Stamklasse)) +
                    ' PDF-filer er genereret. Filerne er placeret på skrivebordet.'
                )
            elif len(Valgte_Stamklasse) == 0:
                st.error(
                    'Du mangler at vælge hvilke holdoversigter som ønskes genereret.'
                )

            # Delete barcodes
            shutil.rmtree('Barcodes')
	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
Ejemplo n.º 47
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 materiale</b><br/>", styNormal)
        else:
            elenco_inv_tip_rep = Paragraph(
                "<b>Elenco N. Inv. / Tipo materiale</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
Ejemplo n.º 48
0
def print_string(pdf_canvas):
    pdfmetrics.registerFont(UnicodeCIDFont('HeiseiKakuGo-W5'))  # フォント
    width, height = A4  # 用紙サイズ

    # (1)履歴書 タイトル
    font_size = 24  # フォントサイズ
    pdf_canvas.setFont('HeiseiKakuGo-W5', font_size)
    pdf_canvas.drawString(90, 770, '履  歴  書')  # 書き出し(横位置, 縦位置, 文字)

    # (2)作成日
    year = '2020'
    month = '12'
    day = '16'
    font_size = 10
    pdf_canvas.setFont('HeiseiKakuGo-W5', font_size)
    pdf_canvas.drawString(285, 770, f'{year}年   {month}月   {day}日現在')

    # (3)証明写真
    # tableを作成
    a = Image(
        f'/Users/stevenzhang/PycharmProjects/python-study/WechatIMG2344.jpeg')
    a.drawHeight = 32 * mm
    a.drawWidth = 25 * mm

    data = [
        [a],
    ]
    table = Table(data, colWidths=30 * mm, rowHeights=40 * mm)  # tableの大きさ
    table.setStyle(
        TableStyle([  # tableの装飾
            ('FONT', (0, 0), (0, 0), 'HeiseiKakuGo-W5', 12),  # フォントサイズ
            ('BOX', (0, 0), (0, 0), 1, colors.black),  # 罫線
            ('VALIGN', (0, 0), (0, 0), 'MIDDLE'),  # フォント位置
        ]))
    table.wrapOn(pdf_canvas, 145 * mm, 235 * mm)  # table位置
    table.drawOn(pdf_canvas, 145 * mm, 235 * mm)

    # (4) プロフィール
    data = [
        ['ふりがな  '
         'チョウ リョウヒ', '   男  ・  女'],
        ['氏名 Steven 張りょうひ', ''],
        ['生年月日             1980  年 12  月 16  日生 (満 40歳)', ''],
    ]
    table = Table(data,
                  colWidths=(100 * mm, 20 * mm),
                  rowHeights=(7 * mm, 20 * mm, 7 * mm))
    table.setStyle(
        TableStyle([
            ('FONT', (0, 0), (1, 2), 'HeiseiKakuGo-W5', 8),
            ('BOX', (0, 0), (1, 2), 1, colors.black),
            ('INNERGRID', (0, 0), (1, 2), 1, colors.black),
            ('SPAN', (0, 2), (1, 2)),
            ('SPAN', (1, 0), (1, 1)),
            ('VALIGN', (0, 0), (1, 2), 'MIDDLE'),
            ('VALIGN', (0, 1), (0, 1), 'TOP'),
        ]))
    table.wrapOn(pdf_canvas, 20 * mm, 232 * mm)
    table.drawOn(pdf_canvas, 20 * mm, 232 * mm)

    # (5)住所
    data = [
        ['ふりがな', '電話'],
        [
            '連絡先(〒120ー0021 )   \n銀河系連邦皇帝大街\nSteven Zhang壹号院\n香山御景台官邸',
            'E-mail \[email protected]'
        ],
        ['ふりがな', '電話'],
        ['連絡先(〒   ー    )', 'E-mail'],
    ]
    table = Table(data,
                  colWidths=(100 * mm, 60 * mm),
                  rowHeights=(7 * mm, 20 * mm, 7 * mm, 20 * mm))
    table.setStyle(
        TableStyle([
            ('FONT', (0, 0), (1, 3), 'HeiseiKakuGo-W5', 9),
            ('BOX', (0, 0), (1, 3), 1, colors.black),
            ('INNERGRID', (0, 0), (1, 3), 1, colors.black),
            ('VALIGN', (0, 0), (1, 2), 'MIDDLE'),
            ('VALIGN', (0, 1), (1, 1), 'TOP'),
            ('VALIGN', (0, 3), (1, 3), 'TOP'),
        ]))
    table.wrapOn(pdf_canvas, 20 * mm, 178 * mm)
    table.drawOn(pdf_canvas, 20 * mm, 178 * mm)

    # (6)学歴・職歴
    data = [[
        '        年', '   月',
        '                                            学歴・職歴'
    ], ['2002 ', '12 ', '木星戦争学院 文学物理系 '], ['1992 ', '12 ', '冥王星げい術学院 ピアノ化学系 '],
            [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '],
            [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '],
            [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '],
            [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '],
            [' ', ' ', ' '], [' ', ' ', ' ']]
    table = Table(data,
                  colWidths=(25 * mm, 14 * mm, 121 * mm),
                  rowHeights=7.5 * mm)
    table.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, -1), 'HeiseiKakuGo-W5', 11),
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    table.wrapOn(pdf_canvas, 20 * mm, 20 * mm)
    table.drawOn(pdf_canvas, 20 * mm, 20 * mm)

    # 1枚目終了
    pdf_canvas.showPage()

    # (7)学歴・職歴、免許・資格
    data = [
        [
            '        年', '   月',
            '                                            学歴・職歴'
        ],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [
            '        年', '   月',
            '                                            免許・資格'
        ],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
        [' ', ' ', ' '],
    ]
    table = Table(data,
                  colWidths=(25 * mm, 14 * mm, 121 * mm),
                  rowHeights=7.5 * mm)
    table.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, -1), 'HeiseiKakuGo-W5', 11),
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    table.wrapOn(pdf_canvas, 20 * mm, 132 * mm)
    table.drawOn(pdf_canvas, 20 * mm, 132 * mm)

    # (8)そのほか

    # orig_sentence = 'NHKは、放送法に基づく特殊法人として1950年に設立された。設立目的は、放送法により「公共の福祉のために、あまねく日本全国で受信できるように豊かで、' \
    #                 '且つ良い放送番組による国内基幹放送を行うと同時に放送およびその受信の進歩発達に必要な業務を行い、' \
    #                 '合わせて国際放送および協会国際衛星放送を行うこと」となっている(法15条、定款3条)。また、同法の規定により1926年に設立された社団法人日本放送協会の業務' \
    #                 'を継承している(法附則第13項)。なお、社団法人日本放送協会は、1925年に日本で初めて放送業務を開始した社団法人東京放送局、社団法人名古屋放送局、社団法人大阪放送局(' \
    #                 '現:NHK放送センター、NHK名古屋放送局、NHK大阪放送局)の業務を統合して設立されたものである'
    orig_sentence = '所属事務所によると、速水さんは3日に発熱症状がみられ、その後も咽頭痛や咳、痰、体の痛み等の症状が続いたことから、6日に医療機関を受診。胸部レントゲンでは所' \
                    '見なしの診断だったものの、PCR検査を受けることになり、7日午後に陽性が確認されたという。速水さんは現在、' \
                    '所属事務所によると、速水さんは3日に発熱症状がみられ、その後も咽頭痛や咳、痰、体の痛み'\
                    '症状は安定しているものの自宅待機をしており、受け入れ先の病院が手配でき次第入院する予定だということだ。なお、3月17日以降はスタッフやキ' \
                    'ャストとの濃厚接触はなかったという。速水さんは所属事務所を通じ、「この度はご心配、ご迷惑をおかけして誠に申し訳ありません。今は、症状も快方に向かってきており、' \
                    'このまま完全復活できるよう快復に努めます。そしてまた元気になって歌う姿を必ずお見せしたいと思います」とコメントしている。'

    print(len(orig_sentence))

    final_text = return_split_text_by_characterencode(orig_sentence)

    data = [[
        '志望の動機、自己PR、趣味、特技など \n'
        'For accurate long-term ephemerides, please instead\n '
        'use our Horizons system. This orbit viewer was\n'
        'implemented using two-body and hence should not \n'
        'used for determining accurate long-term \n'
        'trajectories (over several years or decades) \n'
        'or planetary encounter circumstances.', '通勤時間', ''
    ], ['', '                        約  2時間  23分', ''],
            ['', '扶養家族(配偶者を除く)', ''],
            ['', '                                          人', ''],
            ['', '配偶者', '配偶者の扶養義務'],
            ['', '       有    ・    無', '       有    ・    無'],
            ['本人希望記入欄(特に待遇・職種・勤務時間・その他についての希望などがあれば記入)', '', ''], [final_text]]
    print(
        len('and hence should not be used for determining accurate long-term trajectories trajectories \n '
            ))
    table = Table(data,
                  colWidths=(90 * mm, 35 * mm, 35 * mm),
                  rowHeights=(8 * mm, 10 * mm, 8 * mm, 10 * mm, 8 * mm,
                              10 * mm, 8 * mm, 50 * mm))
    table.setStyle(
        TableStyle([
            ('FONT', (0, 0), (2, 7), 'HeiseiKakuGo-W5', 10),
            ('BOX', (0, 0), (2, 7), 1, colors.black),
            ('LINEBEFORE', (1, 0), (1, 5), 1, colors.black),
            ('LINEBEFORE', (2, 4), (2, 5), 1, colors.black),
            ('LINEABOVE', (1, 2), (2, 2), 1, colors.black),
            ('LINEABOVE', (1, 4), (2, 4), 1, colors.black),
            ('LINEABOVE', (0, 6), (2, 6), 1, colors.black),
            ('LINEABOVE', (0, 7), (2, 7), 1, colors.black),
            ('VALIGN', (0, 0), (2, 5), 'TOP'),
            ('VALIGN', (0, 6), (2, 6), 'MIDDLE'),
        ]))
    table.wrapOn(pdf_canvas, 20 * mm, 20 * mm)
    table.drawOn(pdf_canvas, 20 * mm, 20 * mm)

    # 2枚目終了
    pdf_canvas.showPage()
Ejemplo n.º 49
0
    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] ,
             [123, 'Hora 2', 5465, 123465, 1, 2, 3, 4, False],
	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
Ejemplo n.º 51
0
#            "第一个解决重复消费问题的数字货币。比特币的设计已经成为其他应用程序的灵感来源。<br/>&nbsp&nbsp 2014年,区块链2.0成为一个关于去中心" \
#            "化区块链数据库的术语。对这个第二代可编程区块链,经济学家们认为它是一种编程语言,可以允许用户写出更精密和智能的协议 " \
#            "[7]  。因此,当利润达到一定程度的时候,就能够从完成的货运订单或者共享证书的分红中获得收益。区块链2.0技术跳过了交易" \
#            "和“价值交换中担任金钱和信息仲裁的中介机构”。它们被用来使人们远离全球化经济,使隐私得到保护,使人们“将掌握的信息兑换" \
#            "成货币”,并且有能力保证知识产权的所有者得到收益。第二代区块链技术使存储个人的“永久数字ID和形象”成为可能,并且对“潜在" \
#            "的社会财富分配”不平等提供解决方案 [8]  。<br/>&nbsp&nbsp 2016年1月20日,中国人民银行数字货币研讨会宣布对数字货币研究取得阶段性成果。" \
#            "会议肯定了数字货币在降低传统货币发行等方面的价值,并表示央行在探索发行数字货币。中国人民银行数字货币研讨会的表达大大" \
#            "增强了数字货币行业信心。这是继2013年12月5日央行五部委发布关于防范比特币风险的通知之后,第一次对数字货币表示明确的态度" \
#            "。 [9] <br/>&nbsp&nbsp 2016年12月20日,数字货币联盟——中国FinTech数字货币联盟及FinTech研究院正式筹建 [10]  。<br/>&nbsp&nbsp如今,比特币仍是" \
#            "数字货币的绝对主流,数字货币呈现了百花齐放的状态,常见的有bitcoin、litecoin、dogecoin、dashcoin,除了货币的应用" \
#            "之外,还有各种衍生应用,如以太坊Ethereum、Asch等底层应用开发平台以及NXT,SIA,比特股,MaidSafe,Ripple等行业应用 [11]  。"

# Table 表格

image = Image('./1.png')
image.drawWidth = 160
image.drawHeight = 100
table_data = [
    ['year我是标题行,\n\n比较特殊,不能上下居中\n', '我的背景色被绿了', '我是标题,我比别人大\n'],
    ['2017\n我是换行符,\n单元格中的字符串只能用我换行', '3', '12'],
    [Paragraph('指定了列宽,可以在单元格中嵌入paragraph进行自动换行,不信你看我', body), '4', '13'],
    ['2017', '5', '我们是表格'],
    ['2017', '我是伪拆分单元格,\n通过合并前hou两个兄弟得到', '15'],
    ['2018', '7', '16'],
    [
        Paragraph(content1, body), '8',
        [image, Paragraph('这样我可以在一个单元格内同时显示图片和paragraph', body)]
    ],
    ['2018', '我们被合并了,合并的值为右上角单元格的值', '18'],
    ['我被绿了', '10', '19'],
]
    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
Ejemplo n.º 53
0
    def createDocument(self):
        """"""
        voffset = 30

        # create header data
        header = """<font size="9">
        5 Year Maintenance Certificate<br/>
        %s_C%s<br/>
        Rev%s</font>
        """ % (self.job, self.report, self.revision)
        p = Paragraph(header, myStyle)

        # create header logo and size it
        logo = Image("img/image1.png")
        logo.drawHeight = 0.75 * inch
        logo.drawWidth = 3.43 * inch

        # combine logo and header data into array for table creation
        data = [[logo, p]]

        # create table for placement in header region, and define location
        table = Table(data, colWidths=4 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("VALIGN", (-1, -1), (-1, -1), "CENTER"),
                        ("ALIGN", (-1, -1), (-1, -1), "RIGHT")])
        table.wrapOn(self.c, self.width - 100, self.height)
        table.drawOn(self.c, *self.coord(5, 25, mm))

        # create Certificate title
        ptext = "<b>Certificate of Inspection & Compatibility</b>"
        self.createParagraph(ptext, 0, voffset + 8, TitleStyle)

        # create body text of the certificate and style
        if self.isRemote == 'no':
            ptext = """
            <b><i>Offshore Technical Compliance LLC</i></b> was present for the following 5 Year Maintenance Inspection of the equipment listed below. 
             The inspections were conducted per <b>%s’s</b> Preventative Maintenance (PM) program and the equipment 
             manufacture’s guidelines.
            """ % self.organization
        else:
            ptext = """
            <b><i>Offshore Technical Compliance LLC</i></b> has verified the following 5 Year Maintenance Inspection of the equipment listed below. 
             The inspections were conducted per <b>%s’s</b> Preventative Maintenance (PM) program and the equipment 
             manufacture’s guidelines.
            """ % self.organization
        p = Paragraph(ptext, self.styles["Normal"])
        p.wrapOn(self.c, self.width - 70, self.height)
        p.drawOn(self.c, *self.coord(15, voffset + 25, mm))

        # create first table
        # create data structure for table parsing
        data = self.dataPrepTable1(self.jobdata, self.certdata)
        table = Table(data, colWidths=3.6 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("ALIGN", (0, 0), (0, 0), "CENTER"),
                        ('BACKGROUND', (0, 0), (0, 0), HexColor(0x3a3b3d)),
                        ('BACKGROUND', (0, 7), (0, 7), HexColor(0x595959)),
                        ('SPAN', (0, 0), (1, 0)),
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(15, voffset + 80, mm))

        # create second table
        data = self.dataPrepTable2(self.certdata)
        table = Table(data, colWidths=3.6 * inch)
        if len(self.certdata[1]) > 45:
            table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                            ("ALIGN", (0, 0), (0, 0), "CENTER"),
                            ('BACKGROUND', (0, 0), (0, 0), HexColor(0x3a3b3d)),
                            ('SPAN', (0, 0), (1, 0)),
                            ('INNERGRID', (0, 0), (-1, -1), 0.25,
                             colors.black), ('FONTSIZE', (1, 1), (1, 1), 8),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])
        else:
            table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                            ("ALIGN", (0, 0), (0, 0), "CENTER"),
                            ('BACKGROUND', (0, 0), (0, 0), HexColor(0x3a3b3d)),
                            ('SPAN', (0, 0), (1, 0)),
                            ('INNERGRID', (0, 0), (-1, -1), 0.25,
                             colors.black),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(15, voffset + 130, mm))

        # # create third table
        # data = self.dataPrepTable3(self.certdata)
        # table = Table(data, colWidths=3.6 * inch)
        # table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
        #                 ("ALIGN", (0, 0), (0, 0), "CENTER"),
        #                 ('BACKGROUND', (0, 0), (0, 0), HexColor(0x3a3b3d)),
        #                 ('SPAN', (0, 0), (1, 0)),
        #                 ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        #                ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])
        # table.wrapOn(self.c, self.width, self.height)
        # table.drawOn(self.c, *self.coord(15, voffset + 167, mm))

        # create signature area (table)
        if self.isRemote == 'no':
            data = [[
                'Witness:', self.Witness, 'Date:',
                datetime.date.today().strftime('%d %b %Y')
            ], [],
                    [
                        'Engineering Approval:', self.Engineering, 'Date:',
                        datetime.date.today().strftime('%d %b %Y')
                    ]]
        else:
            data = [[
                'Verification:', self.Witness, 'Date:',
                datetime.date.today().strftime('%d %b %Y')
            ], [],
                    [
                        'Engineering Approval:', self.Engineering, 'Date:',
                        datetime.date.today().strftime('%d %b %Y')
                    ]]
        table = Table(data,
                      colWidths=(1.5 * inch, 3.75 * inch, 0.6 * inch,
                                 1.35 * inch))
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("ALIGN", (0, 0), (0, 1), "RIGHT"),
                        ("ALIGN", (1, 0), (1, 2), "RIGHT")])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(15, voffset + 200, mm))

        # add in signatures
        logo = Image("img/signatures/" + self.WitnessSig)
        logo.drawHeight = .5 * inch
        logo.drawWidth = 1.5 * inch
        logo.wrapOn(self.c, self.width, self.height)
        logo.drawOn(self.c, *self.coord(65, voffset + 187, mm))

        logo = Image("img/signatures/" + self.EngineeringSig)
        logo.drawHeight = .5 * inch
        logo.drawWidth = 1.5 * inch
        logo.wrapOn(self.c, self.width, self.height)
        logo.drawOn(self.c, *self.coord(65, voffset + 202, mm))

        # create footer area (table)
        data = [['www.otcompliance.com', 'PROPRIETARY/CONFIDENTIAL', '1']]
        table = Table(data, colWidths=(2.7 * inch, 2.7 * inch, 2.7 * inch))
        table.setStyle([
            ("VALIGN", (0, 0), (0, 0), "TOP"),
            ("ALIGN", (1, 0), (1, 0), "CENTER"),
            ("ALIGN", (-1, -1), (-1, -1), "RIGHT"),
        ])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(5, voffset + 245, mm))
        self.drawLine()
    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 DI UNIT&Agrave; TOPOGRAFICA<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
        progetto = Paragraph("<b>Progetto</b><br/>" + str(self.progetto),
                             styNormal)
        UT = Paragraph("<b>Nr. UT</b><br/>" + str(self.nr_ut), styNormal)
        UTletterale = Paragraph(
            "<b>UT letterale<br/>" + str(self.ut_letterale), styNormal)

        # 2 row
        descrizione_ut = Paragraph(
            "<b>Descrizione UT</b><br/>" + self.descrizione_ut, styNormal)
        interpretazione_ut = Paragraph(
            "<b>Intepretazione UT</b><br/>" + self.interpretazione_ut,
            styNormal)

        # 3 row
        nazione = Paragraph("<b>Nazione</b><br/>" + self.nazione, styNormal)
        regione = Paragraph("<b>Regione</b><br/>" + self.regione, styNormal)
        provincia = Paragraph("<b>Provincia</b><br/>" + self.provincia,
                              styNormal)
        comune = Paragraph("<b>Comune</b><br/>" + self.comune, styNormal)
        frazione = Paragraph("<b>Frazione</b><br/>" + self.frazione, styNormal)
        localita = Paragraph("<b>Localizzazione</b><br/>" + self.localita,
                             styNormal)
        indirizzo = Paragraph("<b>Indirizzo</b><br/>" + self.indirizzo,
                              styNormal)
        nr_civico = Paragraph("<b>Nr civico</b><br/>" + self.nr_civico,
                              styNormal)
        carta_topo_igm = Paragraph("<b>IGM</b><br/>" + self.carta_topo_igm,
                                   styNormal)
        carta_ctr = Paragraph("<b>CTR</b><br/>" + self.carta_ctr, styNormal)
        coord_geografiche = Paragraph(
            "<b>Coordinate geografiche</b><br/>" + self.coord_geografiche,
            styNormal)
        coord_piane = Paragraph(
            "<b>Coordinate piane</b><br/>" + self.coord_piane, styNormal)
        quota = Paragraph("<b>Quota</b><br/>" + self.quota, styNormal)
        andamento_terreno_pendenza = Paragraph(
            "<b>Pendenza</b><br/>" + self.andamento_terreno_pendenza,
            styNormal)
        utilizzo_suolo_vegetazione = Paragraph(
            "<b>Utilizzo suolo</b><br/>" + self.utilizzo_suolo_vegetazione,
            styNormal)
        descrizione_empirica_suolo = Paragraph(
            "<b>Descrizione empirica suolo</b><br/>" +
            self.descrizione_empirica_suolo, styNormal)
        descrizione_luogo = Paragraph(
            "<b>Descrizione suolo</b><br/>" + self.descrizione_luogo,
            styNormal)
        metodo_rilievo_e_ricognizione = Paragraph(
            "<b>Tipo ricognizione</b><br/>" +
            self.metodo_rilievo_e_ricognizione, styNormal)
        geometria = Paragraph("<b>Geometria</b><br/>" + self.geometria,
                              styNormal)
        bibliografia = Paragraph(
            "<b>Bibliografia</b><br/>" + self.bibliografia, styNormal)
        data = Paragraph("<b>Data</b><br/>" + self.data, styNormal)
        ora_meteo = Paragraph("<b>Ora e Meteo</b><br/>" + self.ora_meteo,
                              styNormal)
        responsabile = Paragraph(
            "<b>Responsabile</b><br/>" + self.responsabile, styNormal)
        dimensioni_ut = Paragraph(
            "<b>Dimensioni UT</b><br/>" + self.dimensioni_ut, styNormal)
        rep_per_mq = Paragraph(
            "<b>Q.t&agrave; per mq </b><br/>" + self.rep_per_mq, styNormal)
        rep_datanti = Paragraph(
            "<b>Q.t&agrave; datanti</b><br/>" + self.rep_datanti, styNormal)
        periodo_I = Paragraph("<b>Periodo I</b><br/>" + self.periodo_I,
                              styNormal)
        datazione_I = Paragraph("<b>Datazione I</b><br/>" + self.frazione,
                                styNormal)
        interpretazione_I = Paragraph(
            "<b>Interpretazione I</b><br/>" + self.interpretazione_I,
            styNormal)
        periodo_II = Paragraph("<b>Periodo II</b><br/>" + self.periodo_II,
                               styNormal)
        datazione_II = Paragraph(
            "<b>Datazione II</b><br/>" + self.datazione_II, styNormal)
        interpretazione_II = Paragraph(
            "<b>Interpretazione II</b><br/>" + self.interpretazione_II,
            styNormal)
        documentazione = Paragraph(
            "<b>Documentazione II</b><br/>" + self.documentazione, styNormal)
        enti_tutela_vincoli = Paragraph(
            "<b>Ente tutela vincoli</b><br/>" + self.enti_tutela_vincoli,
            styNormal)
        indagini_preliminari = Paragraph(
            "<b>Indagini preliminari</b><br/>" + self.indagini_preliminari,
            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
            [
                progetto, '01', '02', '03', '04', UT, '06', '07', UTletterale,
                '09'
            ],  # 1 row ok
            [descrizione_ut, '01', '02', '03', '04'],
            [
                interpretazione_ut, '01', '02', '03', '04', '05', '06', '07',
                '08'
            ],  # 2 row ok
            [nazione, '01', provincia, '03', regione, '06', comune, '9'],  # 3
            [
                frazione, '01', localita, '03', indirizzo, '05', nr_civico,
                '08', '09'
            ],  # 4
            [
                carta_topo_igm, '01', carta_ctr, '03', coord_geografiche, '05',
                coord_piane, '08', '09'
            ],  # 5
            [
                quota, '01', andamento_terreno_pendenza, '03',
                utilizzo_suolo_vegetazione, '05', descrizione_empirica_suolo,
                '08', '09'
            ],
            # 6
            [
                descrizione_luogo, '01', metodo_rilievo_e_ricognizione, '03',
                geometria, '05', bibliografia, '08', '09'
            ],
            [
                data, '01', ora_meteo, '03', responsabile, '05', dimensioni_ut,
                '08', '09'
            ],  # 7
            [
                rep_per_mq, '01', rep_datanti, '03', periodo_I, '05',
                datazione_I, '08', '09'
            ],  # 8
            [
                interpretazione_I, '01', periodo_II, '03', datazione_II, '05',
                interpretazione_II, '08', '09'
            ],
            # 9
            [
                documentazione, '01', '02', enti_tutela_vincoli, '03', '04',
                indagini_preliminari, '09'
            ]
            # 10 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), (9, 1)),  # dati identificativi

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

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

            # 4 row
            ('SPAN', (0, 5), (1, 5)),  # conservazione - consistenza - colore
            ('SPAN', (2, 5), (3, 5)),  # conservazione - consistenza - colore
            ('SPAN', (4, 5), (5, 5)),  # conservazione - consistenza - colore
            ('SPAN', (6, 5), (9, 5)),  # conservazione - consistenza - colore
            # 5 row
            ('SPAN', (0, 6), (1, 6)),  # conservazione - consistenza - colore
            ('SPAN', (2, 6), (3, 6)),  # conservazione - consistenza - colore
            ('SPAN', (4, 6), (5, 6)),  # conservazione - consistenza - colore
            ('SPAN', (6, 6), (9, 6)),  # conservazione - consistenza - colore
            # 6 row
            ('SPAN', (0, 7), (1, 7)),  # conservazione - consistenza - colore
            ('SPAN', (2, 7), (3, 7)),  # conservazione - consistenza - colore
            ('SPAN', (4, 7), (5, 7)),  # conservazione - consistenza - colore
            ('SPAN', (6, 7), (9, 7)),  # conservazione - consistenza - colore
            # 7 row
            ('SPAN', (0, 8), (1, 8)),  # conservazione - consistenza - colore
            ('SPAN', (2, 8), (3, 8)),  # conservazione - consistenza - colore
            ('SPAN', (4, 8), (5, 8)),  # conservazione - consistenza - colore
            ('SPAN', (6, 8), (9, 8)),  # conservazione - consistenza - colore
            # 8 row
            ('SPAN', (0, 9), (1, 9)),  # conservazione - consistenza - colore
            ('SPAN', (2, 9), (3, 9)),  # conservazione - consistenza - colore
            ('SPAN', (4, 9), (5, 9)),  # conservazione - consistenza - colore
            ('SPAN', (6, 9), (9, 9)),  # conservazione - consistenza - colore
            # 9 row
            ('SPAN', (0, 10), (1, 10)),  # conservazione - consistenza - colore
            ('SPAN', (2, 10), (3, 10)),  # conservazione - consistenza - colore
            ('SPAN', (4, 10), (5, 10)),  # conservazione - consistenza - colore
            ('SPAN', (6, 10), (9, 10)),  # conservazione - consistenza - colore
            # 10 row
            ('SPAN', (0, 11), (1, 11)),  # conservazione - consistenza - colore
            ('SPAN', (2, 11), (3, 11)),  # conservazione - consistenza - colore
            ('SPAN', (4, 11), (5, 11)),
            ('SPAN', (6, 11), (9, 11)),  # conservazione - consistenza - colore
            ('SPAN', (0, 12), (2, 12)),  # conservazione - consistenza - colore
            ('SPAN', (3, 12), (5, 12)),  # conservazione - consistenza - colore
            ('SPAN', (6, 12), (9, 12)),  # conservazione - consistenza - colore
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

        # 4 row

        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 STRUTTURA<br/>" + str(self.datestrfdate()) + "</b>", styNormal)
        # intestazione2 = Paragraph("<b>pyArchInit</b><br/>www.pyarchinit.blogspot.com", 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/Nr.</b><br/> %s%s" % (str(self.sigla_struttura), str(self.numero_struttura)), styNormal)

        # 2 row
        categoria = Paragraph("<b>Categoria</b><br/>" + self.categoria_struttura, styNormal)
        tipologia = Paragraph("<b>Tipologia</b><br/>" + self.tipologia_struttura, styNormal)
        definizione = Paragraph("<b>Definizione</b><br/>" + self.definizione_struttura, styNormal)

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

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

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

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

        finale = Paragraph("<b>FINALE</b>", styNormal)

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

            # 6 row
        datazione_estesa = Paragraph("<b>DATAZIONE ESTESA</b><br/>" + self.datazione_estesa, styNormal)

        # 7 row
        materiali_impiegati = ''
        if eval(self.materiali_impiegati) > 0:
            for i in eval(self.materiali_impiegati):
                if materiali_impiegati == '':
                    try:
                        materiali_impiegati += ("%s") % (str(i[0]))
                    except:
                        pass
                else:
                    try:
                        materiali_impiegati += (", %s") % (str(i[0]))
                    except:
                        pass

        materiali_impiegati = Paragraph("<b>Materiali impiegati</b><br/>" + materiali_impiegati, styNormal)

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

        elementi_strutturali = Paragraph("<b>Elementi strutturali</b><br/>" + elementi_strutturali, styNormal)

        # 9 row
        rapporti_struttura = ''
        if eval(self.rapporti_struttura) > 0:
            for i in eval(self.rapporti_struttura):
                if rapporti_struttura == '':
                    try:
                        rapporti_struttura += ("Tipo rapporto: %s, sito: %s, sigla: %s, nr.: %s") % (
                        str(i[0]), str(i[1]), str(i[2]), str(i[3]))
                    except:
                        pass
                else:
                    try:
                        rapporti_struttura += ("<br/>Tipo rapporto: %s, sito: %s, sigla: %s, nr.: %s") % (
                        str(i[0]), str(i[1]), str(i[2]), str(i[3]))
                    except:
                        pass

        rapporti_struttura = Paragraph("<b>Rapporti struttura</b><br/>" + rapporti_struttura, styNormal)

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

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

        # 19 row
        quote_struttura = Paragraph("<b>QUOTE</b><br/>", styNormal)

        # 20 row
        quota_min = Paragraph("<b>Quota min</b><br/>" + str(self.quota_min), styNormal)
        quota_max = Paragraph("<b>Quota max</b><br/>" + str(self.quota_max), 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', sigla_struttura, '09'],  # 1 row ok
            [categoria, '01', '02', '03', tipologia, '05', '06', '07', definizione, '09'],  # 2 row ok
            [descrizione, '01', '02', '03', '04', interpretazione, '06', '07', '08', '09'],  # 3 row ok
            [periodizzazione, '02', '03', '04', '05', '06', '06', '07', '08', '09'],  # 4 row
            [iniziale, '01', periodo_iniziale, '03', fase_iniziale, finale, '06', periodo_finale, '08', fase_finale],
            # 5 row
            [datazione_estesa, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 6 row
            [rapporti_struttura, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 7 row
            [materiali_impiegati, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 8 row
            [elementi_strutturali, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 9 row
            [misure_struttura, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 10 row
            [quote_struttura, '01', '02', '03', '04', '07', '06', '07', '08', '09'],  # 19 row ok
            [quota_min, '01', '02', '03', quota_max, '06', '07', '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), (7, 1)),  # dati identificativi
            ('SPAN', (8, 1), (9, 1)),  # dati identificativi

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

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

            # 4 row
            ('SPAN', (0, 4), (9, 4)),  # inclusi - campioni - formazione

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

            # 6 row
            ('SPAN', (0, 6), (9, 6)),  # Attivita - Struttura - Quota min - Quota max

            # 7 row
            ('SPAN', (0, 7), (9, 7)),  # Attivita - Struttura - Quota min - Quota max

            # 8 row
            ('SPAN', (0, 8), (9, 8)),  # Attivita - Struttura - Quota min - Quota max

            # 9 row
            ('SPAN', (0, 9), (9, 9)),  # Attivita - Struttura - Quota min - Quota max

            # 10 row
            ('SPAN', (0, 10), (9, 10)),  # Attivita - Struttura - Quota min - Quota max

            # 10 row
            ('SPAN', (0, 11), (9, 11)),  # Attivita - Struttura - Quota min - Quota max

            # 10 row
            ('SPAN', (0, 12), (3, 12)),  # conservazione - consistenza - colore
            ('SPAN', (4, 12), (9, 12)),  # conservazione - consistenza - colore

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

        ]

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

        return t
Ejemplo n.º 56
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 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', '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
Ejemplo n.º 57
0
def Output(Input):
    doc = SimpleDocTemplate("result.pdf", pagesize=letter, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
    elements = []
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = 'CJK'
    s.fontsize = 8
    s.alignment = TA_CENTER
    for pages in Input:
             I = Image(pages[0])
             w,h = letter
             I.drawHeight = w*0.8*I.drawHeight/I.drawWidth
             I.drawWidth = w*0.8
             elements.append(I)
             elements.append(PageBreak())
             plots = pages[1]
             for plot in plots:
                 Plot_Caption = plot[0]
                 x_caption = plot[1]
                 y_caption = plot[2]
                 lines = plot[3]
                 data = [[Plot_Caption]]
                 style = TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black),('ALIGN',(0,-1),(-1,-1),'CENTER')])
                 s.textColor = 'black'
                 data2 = [[Paragraph(cell, s) for cell in row] for row in data]
                 t=Table(data2) 
                 t.setStyle(style)
                 elements.append(t)
                 data = [[x_caption,y_caption,"Line"]]
                 style = TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                           ('BOX', (0,0), (-1,-1), 0.25, colors.black)])
                 s.textColor = 'black'
                 data2 = [[Paragraph(cell, s) for cell in row] for row in data]
                 t=Table(data2) 
                 t.setStyle(style)
                 elements.append(t)
                 elements.append(Spacer(width=0, height=0.1*cm))
                 for line in lines:
                     line_caption = line[0][0]
                     line_color = line[0][1]
                     points = line[1]
                     data = []
                     for point in points:
                        data.append([str(point[0]) ,str(point[1]),line_caption])
                     style = TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),('BOX', (0,0), (-1,-1), 0.25, colors.black),('TEXTCOLOR',(0,0),(-1,-1),colors.blue)])
                     #line_color = cv2.cvtColor(line_color,cv2.COLOR_HSV2BGR)
                     r = line_color[2]
                     g = line_color[1]
                     b = line_color[0]
                     col = '#'
                     col += '%02x' %r
                     col += '%02x' %g
                     col += '%02x' %b
                     s.textColor = col
                     data2 = [[Paragraph(cell, s) for cell in row] for row in data]
                     t=Table(data2) 
                     t.setStyle(style)
                     elements.append(t)
                     elements.append(Spacer(width=0, height=0.1*cm))
                 elements.append(Spacer(width=0, height=0.8*cm))
             elements.append(PageBreak())
    doc.build(elements)
Ejemplo n.º 58
0
def generate_pdf_landscape_structure(reports):
    """
    Returns the elements object for the report to be generated in PDF
    for reports in landscape format
    Accepts a schema of the report
    """
    def numtoStr(s):
        """Convert string to either int or float."""
        try:
            ret = int(s)
        except ValueError:
            ret = float(s)
        return ret

    elements = []
    for report in reports:
        data = []
        height, width = A4

        report_content = getSampleStyleSheet()
        report_content.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=8))

        report_title = getSampleStyleSheet()

        report_title.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans-Bold',
                           fontSize=12,
                           leading=20))
        report_title.add(
            ParagraphStyle(name='Left',
                           alignment=TA_LEFT,
                           fontName='DroidSans-Bold',
                           fontSize=12,
                           leading=20))

        report_sub_title = getSampleStyleSheet()
        report_sub_title.add(
            ParagraphStyle(name='Left',
                           alignment=TA_LEFT,
                           fontName='DroidSans',
                           fontSize=10))
        report_sub_title.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=10))

        report_section_titles = getSampleStyleSheet()
        report_section_titles.add(
            ParagraphStyle(name='Left',
                           alignment=TA_LEFT,
                           fontName='DroidSans',
                           fontSize=8))
        report_signature = getSampleStyleSheet()
        report_small_captions = getSampleStyleSheet()
        report_small_captions.add(
            ParagraphStyle(name='Left',
                           alignment=TA_LEFT,
                           fontName='DroidSans',
                           fontSize=6))
        report_small_captions.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=6))

        report_normal_captions_9 = getSampleStyleSheet()
        report_normal_captions_9.add(
            ParagraphStyle(name='Left',
                           alignment=TA_LEFT,
                           fontName='DroidSans',
                           fontSize=9))
        report_normal_captions_9.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=9))

        report_normal_captions = getSampleStyleSheet()
        report_normal_captions.add(
            ParagraphStyle(name='Left',
                           alignment=TA_LEFT,
                           fontName='DroidSans',
                           fontSize=11))
        report_normal_captions.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=11))

        report_table_style = getSampleStyleSheet()
        signature = getSampleStyleSheet()

        heading_style = getSampleStyleSheet()
        heading_style.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans-Bold',
                           fontSize=12))
        heading_style.add(
            ParagraphStyle(name='Spacer',
                           spaceBefore=5,
                           spaceAfter=5,
                           fontName='DroidSans-Bold',
                           fontSize=12))
        signature.add(
            ParagraphStyle(name='Center',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=12))
        signature.add(
            ParagraphStyle(name='Spacer',
                           alignment=TA_CENTER,
                           fontName='DroidSans',
                           fontSize=12,
                           leading=40))

        tbl_style = getSampleStyleSheet()
        tbl_style.add(
            ParagraphStyle(name='Left',
                           alignment=TA_LEFT,
                           fontName='DroidSans',
                           fontSize=12))
        tbl_style.add(
            ParagraphStyle(name='Right',
                           alignment=TA_RIGHT,
                           fontName='DroidSans',
                           fontSize=12))
        tbl_style.add(
            ParagraphStyle(name='BoldLeft',
                           alignment=TA_LEFT,
                           fontName='DroidSans-Bold',
                           fontSize=12))
        tsl = [('ALIGN', (0, 0), (-1, -1), 'CENTER'),
               ('VALIGN', (0, 0), (-1, -1), 'TOP'),
               ('FONT', (0, 0), (-1, 0), 'DroidSans'),
               ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
               ('TOPPADDING', (0, 0), (-1, -1), 0),
               ('VALIGN', (-1, -1), (-1, -1), 'MIDDLE')]

        tsh = [('ALIGN', (1, 1), (-1, -1), 'LEFT'),
               ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
               ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
               ('TOPPADDING', (0, 0), (-1, -1), 0)]

        ts = [('ALIGN', (1, 1), (-1, -1), 'LEFT'),
              ('VALIGN', (1, 1), (-1, -1), 'MIDDLE'),
              ('FONT', (0, 0), (-1, 0), 'DroidSans'),
              ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
              ('GRID', (0, 0), (-1, -1), 0.5, colors.black)]

        tsf = [('ALIGN', (1, 1), (-1, -1), 'CENTER')]

        elements.append(
            Table([[
                Paragraph('ΣΤΟΙΧΕΙΑ ΕΡΓΟΔΟΤΗ - ΦΟΡΕΑ',
                          report_sub_title['Left'])
            ]],
                  style=tsl,
                  colWidths=[28 * cm]))

        data = []
        somedata = [
            [
                Paragraph(
                    u'ΔΙΕΥΘΥΝΣΗ ΔΕΥΤΕΡΟΒΑΘΜΙΑΣ ΕΚΠΑΙΔΕΥΣΗΣ %s' %
                    SETTINGS['dide_place_caps'],
                    report_normal_captions['Left'])
            ], [Paragraph(u'Επωνυμία', report_small_captions['Left'])],
            [Paragraph(u'ΔΗΜΟΣΙΑ ΥΠΗΡΕΣΙΑ', report_sub_title['Left'])],
            [Paragraph(u'Είδος επιχείρησης', report_small_captions['Left'])],
            [
                Paragraph(
                    u'%s, %s' %
                    (SETTINGS['address'],
                     SETTINGS['economics_contact_telephone_number']),
                    report_sub_title['Left'])
            ],
            [
                Paragraph(u'Δ/νση: Οδός - Αριθ. - Τ.Κ. - Πόλη - Αριθ. Τηλ.',
                          report_small_captions['Left'])
            ],
            [
                Paragraph(u'ΑΦΜ: %s' % SETTINGS['afm_dide'],
                          report_title['Left'])
            ]
        ]
        table = Table(somedata, style=tsh, colWidths=[14.5 * cm])

        headdata = [[
            table,
            [
                Paragraph('ΒΕΒΑΙΩΣΗ ΑΠΟΔΟΧΩΝ', report_title['Center']),
                Paragraph(
                    u'που καταβλήθηκαν από 01/01/%s μέχρι 31/12/%s' %
                    (report['year'], report['year']),
                    report_normal_captions['Center']),
                Paragraph('(ΠΑΡΑΓΡΑΦΟΣ 3 ΑΡΘΡΟΥ 83 Ν 2238/1994)',
                          report_small_captions['Center'])
            ]
        ]]

        table0 = Table(headdata, style=tsl, colWidths=[14.5 * cm, 13.5 * cm])
        elements.append(table0)
        elements.append(Paragraph(' ', heading_style['Spacer']))
        elements.append(
            Table([[
                Paragraph('Ι. ΣΤΟΙΧΕΙΑ ΤΟΥ ΔΙΚΑΙΟΥΧΟΥ ΜΙΣΘΩΤΟΥ ή ΣΥΝΤΑΞΙΟΥΧΟΥ',
                          report_sub_title['Left'])
            ]],
                  style=tsl,
                  colWidths=[28 * cm]))

        headdata = [[
            Paragraph('%s' % report['lastname'],
                      report_normal_captions['Left']),
            Paragraph('%s' % report['firstname'],
                      report_normal_captions['Left']),
            Paragraph('%s' % report['fathername'],
                      report_normal_captions['Left']),
            Paragraph('%s' % report['vat_number'],
                      report_normal_captions['Left'])
        ],
                    [
                        Paragraph('Επώνυμο', report_small_captions['Left']),
                        Paragraph('Όνομα', report_small_captions['Left']),
                        Paragraph('Όνομα Πατέρα',
                                  report_small_captions['Left']),
                        Paragraph('Αριθμ. Φορολ. Μητρώου',
                                  report_small_captions['Left'])
                    ]]
        table1 = Table(headdata,
                       style=tsh,
                       colWidths=[5.5 * cm, 9 * cm, 8 * cm, 5.5 * cm])
        elements.append(table1)
        headdata = [[
            Paragraph(u'%s' % report['address'] or '-',
                      report_normal_captions['Left']),
            Paragraph(u'%s' % report['telephone_number1'] or '-',
                      report_normal_captions['Left']),
            Paragraph(u'%s' % report['tax_office'] or '-',
                      report_normal_captions['Left'])
        ],
                    [
                        Paragraph(
                            'Διεύθυνση κατοικίας: Οδός - Αριθ. - Τ.Κ. - Πόλη',
                            report_small_captions['Left']),
                        Paragraph('Αρ. Τηλ.', report_small_captions['Left']),
                        Paragraph('Αρμόδια για τη φορολογία του ΔΟΥ',
                                  report_small_captions['Left'])
                    ]]
        table1 = Table(headdata,
                       style=tsh,
                       colWidths=[14.5 * cm, 8 * cm, 5.5 * cm])
        elements.append(table1)

        org = report.get('organization_serving', u'') or u''

        headdata = [[
            Paragraph(
                ' '.join(
                    (u'%s' % (report['profession'] or '-'), u'στο %s' % org)),
                report_normal_captions['Left'])
        ], [Paragraph('Είδος υπηρεσίας', report_small_captions['Left'])]]
        table1 = Table(headdata, style=tsh, colWidths=[28 * cm])
        elements.append(table1)

        elements.append(Paragraph(' ', heading_style['Spacer']))
        elements.append(
            Table([[
                Paragraph('ΙΙ. ΑΜΟΙΒΕΣ ΠΟΥ ΦΟΡΟΛΟΓΟΥΝΤΑΙ',
                          report_sub_title['Left'])
            ]],
                  style=tsl,
                  colWidths=[28 * cm]))

        del data
        data = []
        headdata = []
        for line in report['payment_categories']:

            w = 28.00 / len(line)
            d = [w * cm for x in range(len(line))]
            l = []
            for i in line:
                if to_float(unicode(i)) is None:
                    l.append(Paragraph('%s' % i, report_content['Center']))
                else:
                    if float(i) == 0:
                        l.append(Paragraph('-', report_content['Center']))
                    else:
                        l.append(
                            Paragraph('%.2f' % round(float(i), 2),
                                      report_content['Center']))

            headdata.append(l)

        table1 = Table(headdata, style=ts, colWidths=d)
        elements.append(table1)

        elements.append(Paragraph(' ', heading_style['Spacer']))
        elements.append(
            Table([[
                Paragraph(
                    'ΙIΙ. ΑΜΟΙΒΕΣ ΠΟΥ ΑΠΑΛΛΑΣΣΟΝΤΑΙ ΑΠΟ ΤΟ ΦΟΡΟ ή ΔΕ ΘΕΩΡΟΥΝΤΑΙ ΕΙΣΟΔΗΜΑ ή ΦΟΡΟΛΟΓΟΥΝΤΑΙ ΑΥΤΟΤΕΛΩΣ',
                    report_sub_title['Left'])
            ]],
                  style=tsl,
                  colWidths=[28 * cm]))

        today = datetime.date.today()
        del somedata
        somedata = []
        somedata = [[
            Paragraph(u'Είδος αμοιβής', report_normal_captions_9['Center']),
            Paragraph(
                u'Διάταξη Νόμου που παρέχει την απαλλαγή ή επιβάλλει αυτοτελή φορολογία',
                report_normal_captions_9['Center']),
            Paragraph(u'Ακαθάριστο ποσό', report_normal_captions_9['Center']),
            Paragraph(
                u'Σύνολο κρατήσεων που αφορούν τις αμοιβές που απαλλάσσονται',
                report_normal_captions_9['Center']),
            Paragraph(u'Καθαρό ποσό', report_normal_captions_9['Center']),
            Paragraph(u'Φόρος που παρακρατήθηκε (για την αυτοτελή φορολογία)',
                      report_normal_captions_9['Center'])
        ],
                    [
                        Paragraph(u'-', report_normal_captions['Left']),
                        Paragraph(u'-', report_normal_captions['Left']),
                        Paragraph(u'-', report_normal_captions['Left']),
                        Paragraph(u'-', report_normal_captions['Left']),
                        Paragraph(u'-', report_normal_captions['Left']),
                        Paragraph(u'-', report_normal_captions['Left'])
                    ]]

        table_1 = Table(
            somedata,
            style=ts,
            colWidths=[3 * cm, 4 * cm, 2 * cm, 4 * cm, 2 * cm, 3 * cm])
        del somedata
        somedata = []
        somedata = [[
            Paragraph(u'ΣΥΝΟΛΟ', report_normal_captions['Center']),
            Paragraph(u'-', report_normal_captions['Left']),
            Paragraph(u'-', report_normal_captions['Left']),
            Paragraph(u'-', report_normal_captions['Left']),
            Paragraph(u'-', report_normal_captions['Left'])
        ]]

        table_2 = Table(somedata,
                        style=ts,
                        colWidths=[7 * cm, 2 * cm, 4 * cm, 2 * cm, 3 * cm])

        data = []

        del headdata
        sign = os.path.join(settings.MEDIA_ROOT, "signature.png")
        im = Image(sign)
        im.drawHeight = 3.2 * cm
        im.drawWidth = 6.5 * cm

        headdata = [[
            [table_1, table_2],
            [
                Paragraph(
                    u'Ρόδος, %s / %s / %s' %
                    (today.day, today.month, today.year), signature['Center']),
                Paragraph(' ', heading_style['Spacer']), im
            ],
        ]]

        table0 = Table(headdata, style=tsl, colWidths=[18 * cm, 10 * cm])
        elements.append(table0)
        elements.append(PageBreak())
    return elements
Ejemplo n.º 59
0
def html_to_pdf(file_tmp, r_value, pw, leftnone=False):
    linux = None
    if sys.platform == 'linux':
        linux = True
    size_css = f"""
    html, body {{
        width: {1000 if leftnone else 1300}px;
    }}
    """

    css = """
    html, body, div,
    h1, h2, h3, h4, h5, h6 {
        margin: 0;
        padding: 0;
        border: 0;
        font-family: sans-serif;
        font-size: 14px;
    }

    body {
        padding-left: 15px;
    }

    table {
        width: 100%;
        table-layout: fixed;
        border-collapse: collapse;
    }

    table, th, td {
        border: 1px solid black;
    }

    th, td {
        word-break: break-word;
        white-space: normal;
    }

    td {
        padding: 2px;
    }

    td p, li p {
        margin: 0;
    }

    h1 {
        font-size: 24px;
    }

    h2 {
        font-size: 20px;
    }

    h3 {
        font-size: 18px;
    }
                                        """
    if linux:
        display = Display(visible=0, size=(800, 600))
        display.start()
    imgkit.from_string(
        f"""
    <html>
        <head>
            <meta name="imgkit-format" content="png"/>
            <meta name="imgkit-quality" content="100"/>
            <meta name="imgkit-zoom" content="3"/>
            <meta charset="utf-8">
            <style>
                {size_css}
                {css}
            </style>
        </head>
        <body>
            {r_value}
        </body>
    </html>
                                        """,
        file_tmp,
    )
    if linux:
        display.stop()

    i = Image(file_tmp)
    i.drawHeight = i.drawHeight * (pw / i.drawWidth)
    i.drawWidth = pw

    return i
Ejemplo n.º 60
0
            hdat=[]
            parts.append(Spacer(1, 0.2 * inch))
            for keyh,valh in dich.items():
                hdat.append([keyh,":  "+valh])
            htbl = Table(hdat)
            htbl.setStyle(TableStyle([('VALIGN', (0, 0), (1, 0), 'TOP')])) 
            parts.append(htbl)
            flag=1
    if flag==0:
        parts.append(Spacer(1, 0.2 * inch))
        parts.append(Paragraph("\tNo hosts Connected to Device", style))
    parts.append(PageBreak())

#plotting comparison of uptime of differnet devices
df.set_index('Device', inplace=True)
df.plot.barh(figsize=(20,10))
plt.savefig('fig.jpg')
#saving the plot as summary
parts.append(PageBreak())
parts.append(Paragraph("SUMMARY",stylet))
parts.append(Spacer(1, 0.1 * inch))
I=Image('fig.jpg')
parts.append(I)
I.drawHeight =  12*cm
I.drawWidth = 20*cm
del df    
#building final pdf
doc.multiBuild(parts)
f=open('fig.jpg','rb')
f.close()
os.remove(f.name)