Esempio n. 1
0
    def buildReport(self):
        print("Generating report to %s" % self.reportFilename)
        doc = SimpleDocTemplate(self.reportFilename)
        Story = [Spacer(1, 1 * inch)]
        headingStyle = reportlab.lib.styles.getSampleStyleSheet()["Heading1"]
        normalStyle = reportlab.lib.styles.getSampleStyleSheet()["Normal"]

        sections = [[
            "High Achievement Examples", self.highLinks, self.highDescription
        ],
                    [
                        "Medium Achievement Examples", self.mediumLinks,
                        self.mediumDescription
                    ],
                    [
                        "Low Achievement Examples", self.lowLinks,
                        self.lowDescription
                    ]]

        p = Paragraph(self.title, headingStyle)
        Story.append(p)
        p = Paragraph(self.description, normalStyle)
        Story.append(p)
        Story.append(PageBreak())

        for title, links, description in sections:
            if len(links) < 1:
                print("  No links in section: %s" % description)
                continue

            p = Paragraph(title, headingStyle)
            Story.append(p)

            if description:
                p = Paragraph(description, normalStyle)
                Story.append(p)
                Story.append(Spacer(1, 0.25 * inch))

            for link in links:
                if link is None:
                    continue
                print("Adding link %s" % link)
                text = "URL: <a href='%s'>%s</a>" % (link, link)
                #text = "URL: %s" % link
                p = Paragraph(text, normalStyle)

                imageFilename = self.screenshotFilenameForURL(link)
                image = Image(imageFilename)
                image._restrictSize(7 * inch, 5 * inch)

                Story.append(KeepTogether([p, image]))
                Story.append(Spacer(1, 0.2 * inch))

            Story.append(PageBreak())

        print("  Building report")
        doc.build(Story,
                  onFirstPage=self.reportPage,
                  onLaterPages=self.reportPage)
        print("  Saved report to %s" % self.reportFilename)
Esempio n. 2
0
def image_from_mpl_fig(mpl_fig):
    image_data = BytesIO()
    mpl_fig.savefig(image_data, format='png', dpi=200)
    image_data.seek(0)
    image = Image(image_data)
    image._restrictSize(*A4)
    return image
    def createPlotWithCol(self, dataFrames, column, args, doc):
        fig = plt.figure(figsize=(10, 5))
        ax = fig.add_subplot(111)
        ax.set_position([0.1, 0.35, .85, .6])

        fishes_names = [i for i in itertools.chain.from_iterable(args.values())]
        colors = cmx.hsv(np.linspace(0, 1, len(fishes_names)))

        if column == 'Area' or column == 'Circularity':
            for fishName, color in zip(fishes_names, colors):
                data_len = len(getDataByColumn(fishName, column, dataFrames))
                x_perc = np.linspace(0, 100, data_len)
                ax.plot(x_perc, getDataByColumn(fishName, column, dataFrames), label=fishName, color=color)

            x_axix_format = '%.0f%%'
            xticks = mtick.FormatStrFormatter(x_axix_format)
            ax.xaxis.set_major_formatter(xticks)
            ax.grid(True)

            plt.xlabel('Number of slice (%)', labelpad=5)
            plt.ylabel(self.unitsInfo[column])
            
            ax.legend(loc='center', bbox_to_anchor=(0.5, -0.35), ncol=6, prop={'size': 12})

        imgdata = BytesIO()
        fig.savefig(imgdata, format='png')
        imgdata.seek(0)
        img = Image(imgdata)
        img._restrictSize(doc.width, doc.height)

        return img
Esempio n. 4
0
    def __build_attachments(self,uuids):
        try:
            arcpy.AddMessage("BUILD ATTACHMENTS")
            data = []
            file_img = []
            df = []
        
            for uuid in uuids:
                uuid_name = uuid['name']
                uuid_df = uuid['display_field']
                files_attach = self.data_access.get_attachments_in_folder(uuid_name)
                for file in files_attach:
                    path_img = '{}{}\\{}'.format(arcpy.env.scratchWorkspace,uuid_name,file)
                    img_attach = Image( path_img)
                    img_attach._restrictSize(3*inch, 3*inch)
                    file_img.append(img_attach)
                    df.append(uuid_df)

                    if len(file_img) == 2:
                        data.append(file_img)
                        data.append(df)
                        file_img = []
                        df = []

                if len(file_img) > 0:
                    data.append(file_img)
                    data.append(df)
        
                if len(data) > 0:
                    self.__set_position_attach(data)
        except Exception as ex:
            print(ex)
            arcpy.AddMessage(ex.message)
Esempio n. 5
0
    def create_logo(self, absolute_path):
        try:
            image = Image(absolute_path)

            image._restrictSize(2.5 * inch, 2.5 * inch)
        except:

            image = Image('http://' + self.base_url +
                          '/static/images/img-404.jpg')
            image._restrictSize(1.5 * inch, 1.5 * inch)
        return image
Esempio n. 6
0
 def print_image(self, input_image, width, height):
     """
     Purpose:
         Pushes an imgage into the story so it can be printed in the report
     Arguments:
         input_image: string
             full name of the image file
         X: int
             Determines the scale of image in the horizontal
         Y: int
             Determines the scale of image in the vertical
     Return Value: None
         Appends an image into the "story" list to be printed later
     """
     try:
         img = Image(input_image)
         if width * inch > 8 and height * inch > 9:
             img._restrictSize(7 * inch, 8 * inch)
             self.story.append(img)
         elif width * inch > 8 and height * inch < 9:
             img._restrictSize(7 * inch, height * inch)
             self.story.append(img)
         elif width * inch < 8 and height * inch > 9:
             img._restrictSize(width * inch, 8 * inch)
             self.story.append(img)
         else:
             img._restrictSize(width * inch, height * inch)
             self.story.append(img)
     except ValueError:
         self.print_line("The image did not print")
Esempio n. 7
0
    def _header_footer(self, canvas, doc):
        # Save the state of our canvas so we can draw on it
        canvas.saveState()

        style_right = ParagraphStyle(name='right',
                                     parent=self.bodystyle,
                                     fontName='arialuni',
                                     fontSize=10,
                                     alignment=TA_RIGHT)

        fieldsight_logo = Image('http://' + self.base_url +
                                '/static/images/fs1.jpg')
        fieldsight_logo._restrictSize(1.5 * inch, 1.5 * inch)

        # headerleft = Paragraph("FieldSight", self.bodystyle)
        headerright = Paragraph(self.project_name, style_right)

        # w1, h1 = headerleft.wrap(doc.width, doc.topMargin)
        w2, h2 = headerright.wrap(doc.width, doc.topMargin)

        textWidth = stringWidth(self.project_name,
                                fontName='arialuni',
                                fontSize=10)

        fieldsight_logo.drawOn(canvas, doc.leftMargin,
                               doc.height + doc.topMargin + 12)
        headerright.drawOn(canvas, doc.leftMargin,
                           doc.height + doc.topMargin + 20)
        try:
            project_logo = Image(self.project_logo)
            project_logo._restrictSize(0.4 * inch, 0.4 * inch)
            project_logo.drawOn(
                canvas,
                headerright.width + doc.leftMargin - 0.5 * inch - textWidth,
                doc.height + doc.topMargin + 10)
        except:
            pass
        # header.drawOn(canvas, doc.leftMargin + doc.width, doc.height + doc.topMargin +20)

        # Footer
        footer = Paragraph('Page no. ' + str(canvas._pageNumber), style_right)
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, h + 40)

        # Release the canvas
        canvas.restoreState()
    def _header_footer(canvas, doc):
        canvas.saveState()
        styles = getSampleStyleSheet()
        canvas.setFont("DejaVu Sans", 7)

        im = Image('assets/images/TaT_DF_LOGO.png')
        im._restrictSize(1000 * mm, 30 * mm)
        im.drawOn(canvas, doc.leftMargin, doc.height - 20 * mm)

        # Footer
        canvas.drawRightString(
            doc.width + doc.rightMargin, 10 * mm,
            'Falls Probleme auftreten, schreiben Sie eine E-Mail an [email protected]'
        )

        # Release the canvas
        canvas.restoreState()
Esempio n. 9
0
	def gerarCabecalho(self):
		textoLateral, linTexto = 'sua visão, perfeita', 1
		estiloCabecalho = [
			("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
			("HALIGN", (0, 0), (-1, -1), "LEFT"),
			('FONTNAME', (0, linTexto), (-1, linTexto), 'Times-Bold'),
			('ALIGN', (0, linTexto), (-1, linTexto), 'RIGHT'),
			('FONTSIZE', (0,linTexto), (-1,linTexto), 13),			
			("VALIGN", (0, linTexto), (-1, linTexto), "TOP"),
			]
		imgLogo = Image(dirname(abspath(sys.executable)) + "/famotica.jpg")
		# tamanho original: 360x86
		imgLogo._restrictSize(200, 47)
		tabCabecalho = Table([ [imgLogo], [textoLateral] ])
		tabCabecalho.setStyle(estiloCabecalho)
		tabCabecalho.hAlign = 'LEFT'
		return tabCabecalho
Esempio n. 10
0
def createPlotWithCol(dataFrames, column, args, doc):
    fig = plt.figure(figsize=(10, 4))
    ax = fig.add_subplot(111)

    for fishClass, fishNames in args.items():
        for fishName in fishNames:
            dataFrames[fishName][column].plot(label=fishName)

    plt.legend(loc="upper right")
    plt.xlabel('Number of slice (%)')
    plt.ylabel('Units')
    plt.grid(True)
    plt.tight_layout()

    imgdata = BytesIO()
    fig.savefig(imgdata, format='png')
    imgdata.seek(0)
    img = Image(imgdata)
    img._restrictSize(doc.width, doc.height * 0.3)

    return img
def add_article(article_dir):
    with open(os.path.join(article_dir, 'meta.json'), encoding='utf-8') as data_file:
        post = json.loads(data_file.read())

    title = Paragraph('{}'.format(post['title']), styles["Heading3"])

    article_items = [title]

    if len(post['text']) > 0:
        text = Paragraph(post['text'], styles["Normal"])
        text.keepWithNext = True
        article_items.append(text)
        if len(post['images']) > 0:
            article_items.append(Spacer(1, 0.5 * cm))

    for image in post['images']:
        im = Image(os.path.join(article_dir, image))
        im._restrictSize(25 * cm, 17 * cm)
        article_items.append(im)

    Story.append(KeepTogether(article_items))
file.close()

styleSheet = getSampleStyleSheet()
style = styleSheet['BodyText']

styleN = styleSheet['Normal']
styleH = styleSheet['Heading1']
story = []

PW = 10 * inch
PH = 5.63 * inch

styles = getSampleStyleSheet()

IA = Image(os.path.join(data_dirA, "waterfall.png"))
IA._restrictSize((PW - 2.1 * inch) / 2, (PH - 2.1 * inch))

IB = Image(os.path.join(data_dirB, "waterfall.png"))
IB._restrictSize((PW - 2.1 * inch) / 2, (PH - 2.1 * inch))

myTable = Table([[IA, IB]], spaceAfter=inch * 0.1)
myTable.setStyle(
    TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))
story.append(myTable)

i = 0
while True:
    fName = "RSSSensitivity" + str(i) + ".png"
    fileA = os.path.join(data_dirA, fName)
    fileB = os.path.join(data_dirB, fName)
Esempio n. 13
0
file.close()

styleSheet = getSampleStyleSheet()
style = styleSheet['BodyText']

styleN = styleSheet['Normal']
styleH = styleSheet['Heading1']
story = []

PW = 10 * inch
PH = 5.63 * inch

styles = getSampleStyleSheet()

IAC = Image(os.path.join(data_dirA, "fig3Cont.png"))
IAC._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.1 * inch) / 2)
IAGi = Image(os.path.join(data_dirA, "fig3GI.png"))
IAGi._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.1 * inch) / 2)

IBC = Image(os.path.join(data_dirB, "fig3Cont.png"))
IBC._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.1 * inch) / 2)
IBGi = Image(os.path.join(data_dirB, "fig3GI.png"))
IBGi._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.1 * inch) / 2)

IO = Image(os.path.join(supAlPath, "Figure_3.jpg"))
IO._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.3 * inch))

myTable = Table([[IO, [IAC, IAGi], [IBC, IBGi]]], spaceAfter=inch * 0.1)
myTable.setStyle(
    TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))
def createPdfReport(cliente, fileName, data, headers, operacion):

    doc = SimpleDocTemplate(fileName,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

    Story = []

    image = Image('bull_logo2.png', hAlign='LEFT')
    image._restrictSize(2 * inch, 3 * inch)
    Story.append(image)

    Story.append(Spacer(1, 12))

    fecha_hoy = datetime.today().strftime('%d-%m-%Y')

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

    ptext = '<font size=12>%s</font>' % fecha_hoy

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

    # Create return address
    full_name = "BullEstate"
    ptext = '<font size=12>%s</font>' % full_name
    Story.append(Paragraph(ptext, styles["Normal"]))

    web = '<link href="' + 'http://www.bullestate.cl' + '" color="blue">' + 'www.bullestate.cl' + '</link>'
    Story.append(platypus.Paragraph(web, PS('body')))

    mail = '<a href="mailto:[email protected]" color="blue">[email protected]</a>'
    Story.append(platypus.Paragraph(mail, PS('body')))

    Story.append(Spacer(1, 12))
    ptext = '<font size=12>Estimada/o %s:</font>' % cliente.split()[0].strip()
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>Según los requerimientos presentados por Ud, las oportunidades inmobiliarias encontradas con ' \
            'fecha %s, son las siguientes:</font>' % fecha_hoy
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    nrCols = 11
    nrRows = len(data) + 1

    data = [list(elem) for elem in data]

    #creacion de precios, porcentajes y link
    for i, prop in enumerate(data):
        #porcentaje
        rent = float(prop[9])
        rent = int(rent * 1000)
        rent = float(rent / 10)
        rent = str(rent) + "%"
        prop[9] = rent
        if (operacion == "venta"):
            rent = float(prop[11])
            rent = int(rent * 1000)
            rent = float(rent / 10)
            rent = str(rent) + "%"
            prop[11] = rent

        #arreglar precio
        precio = prop[0]
        if operacion == "venta":
            unf = uf.getUf()
            precio = precio / unf
            precio = int(precio)
            precioStr = format(precio, ',.2f')
            precioStr = precioStr[:-3]
            precioStr = "UF " + precioStr.replace(",", ".")
        else:
            precioStr = format(precio, ',.2f')
            precioStr = precioStr[:-3]
            precioStr = "$ " + str(precioStr)

        prop[0] = precioStr
        ufn = uf.getUf()
        #quitar decimales a valores
        prop[1] = int(prop[1])
        prop[2] = int(prop[2])
        prop[3] = int(prop[3])
        prop[4] = int(prop[4])
        prop[5] = int(prop[5])
        prop[7] = int(prop[7])

        if (operacion == "venta"):
            prop[8] = int(prop[8] / ufn)
            prop[8] = format(prop[8], ',.2f')
            prop[8] = prop[8][:-3]
            prop[8] = "UF " + str(prop[8])
            prop[10] = int(prop[10])
            prop[10] = format(prop[10], ',.2f')
            prop[10] = prop[10][:-3]
            prop[10] = "$ " + str(prop[10])
            #link
            link = str(prop[12])
            linkHtml = '<link href="' + link + '" color="blue">' + "Link" + '</link>'
            prop[12] = platypus.Paragraph(linkHtml, PS('body'))

        else:

            prop[8] = int(prop[8])
            prop[8] = format(prop[8], ',.2f')
            prop[8] = prop[8][:-3]
            prop[8] = "$ " + str(prop[8])
            #link
            link = str(prop[10])
            linkHtml = '<link href="' + link + '" color="blue">' + "Link" + '</link>'
            prop[10] = platypus.Paragraph(linkHtml, PS('body'))

        #agregar numerador
        data[i] = [i + 1] + prop

    headers = ["Nº"] + headers
    data = [headers] + data
    #t=Table(data,nrCols*[0.6*inch], nrRows*[0.25*inch])
    t = Table(data)
    t.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
        ]))

    Story.append(t)
    Story.append(Spacer(2, 24))

    ptext = '<font size=12>*D=Dormitorios  B=Baños  E=Estacionamientos  P.P=Precio venta predicho  Rent.P=Rentabilidad Venta  Rent.A=Rentabilidad Arriendo </font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>Si ud. esta interesada/o en visitar algunas de las propiedades señaladas, le solicitamos escribirnos a la brevedad ' \
            'para agendar una visita.</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>Sin otro particular, se despide atentamente:</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    image = Image('firmaSergei.jpg', hAlign='LEFT')
    image._restrictSize(2 * inch, 3 * inch)
    Story.append(image)

    ptext = '<font size=12>Sergei Schkolnik</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))

    doc.build(Story)
Esempio n. 15
0
 def handle_receipt(self, img_receipt):
     """Read receipt into reportlab compatible Image format and make it smaller."""
     img = Image(BytesIO(img_receipt))
     img._restrictSize(12 * cm, 15 * cm)
     return img
    def print_vouchers(self):
        buffer = self.buffer
        styles = self.styles

        doc = SimpleDocTemplate(buffer,
                                rightMargin=15 * mm,
                                leftMargin=15 * mm,
                                topMargin=0 * mm,
                                bottomMargin=15 * mm,
                                pagesize=self.pagesize)

        # Our container for 'Flowable' objects
        elements = []

        for i, voucher in enumerate(self.vouchers):
            #qrcode = QRFlowable('http://redirect.wlan.tuerantuer.org/?voucher=' + voucher)
            #elements.append(qrcode)

            #elements.append(Paragraph('1. Deaktiviere deine mobilen Daten  2. Scannen  3. Du wirst eingeloggt!', styles['Voucher_Subtitle']))

            elements.append(Spacer(0, 40 * mm))
            self.print_table(elements, voucher)
            elements.append(Spacer(0, 10 * mm))

            elements.append(
                ListFlowable([
                    ListItem(Paragraph(
                        'Verbinden Sie sich mit dem WLAN-Netzwerk (z.B. "net2otto", "net2wind"...)',
                        styles['Text']),
                             value='circle'),
                    ListItem(Paragraph(
                        'Öffnen Sie ihren Webbrowser (Firefox, Chrome, Internet Explorer...)',
                        styles['Text']),
                             value='circle'),
                    ListItem(Paragraph('Öffnen Sie eine beliebige Website',
                                       styles['Text']),
                             value='circle'),
                    ListItem(Paragraph('Die folgende Seite wird angezeigt:',
                                       styles['Text']),
                             value='circle')
                ],
                             style=styles['list_default']))

            elements.append(Spacer(0, 2 * mm))
            im = Image('assets/images/example.png')
            im._restrictSize(50 * mm, 50 * mm)
            elements.append(im)
            elements.append(Spacer(0, 2 * mm))

            elements.append(
                ListFlowable([
                    ListItem(Paragraph(
                        'Geben Sie ihren persönlichen Voucher Code ein (Groß-/Kleinschreibung ist wichtig)',
                        styles['Text']),
                             value='circle'),
                    ListItem(Paragraph('Klicken Sie auf "Submit"',
                                       styles['Text']),
                             value='circle'),
                    ListItem(Paragraph(
                        'Die Internetverbindung funktioniert jetzt.',
                        styles['Text']),
                             value='circle')
                ],
                             style=styles['list_default']))

            elements.append(Spacer(0, 10 * mm))
            elements.append(
                Paragraph(
                    '''
                <b>Geben Sie den Voucher Code nicht weiter! Sie können das Internet 
                nicht mehr normal Nutzen, falls jemand anderes Ihren Voucher Code kennt!</b>
            ''', styles["Text"]))
            elements.append(Spacer(0, 5 * mm))
            elements.append(
                Paragraph(
                    '''
                Sie können den Voucher Code für mehrere Geräte benutzen, allerdings nur für
                maximal ein Gerät gleichzeitig.
            ''', styles["Text"]))
            elements.append(Spacer(0, 5 * mm))
            elements.append(
                Paragraph(
                    '''
                <b>Erinnern Sie sich immer daran</b>, dass der Internetverkehr vom
                Internetanbieter protokolliert wird. Sie sind verantwortlich für jeglichen
                Missbrauch. Verstöße werden nach deutschem Gesetz verfolgt.
            ''', styles["Text"]))
            elements.append(PageBreak())

        doc.build(elements,
                  onFirstPage=self._header_footer,
                  onLaterPages=self._header_footer)
Esempio n. 17
0
def LATTE_DV(tic,
             indir,
             syspath,
             transit_list,
             sectors_all,
             target_ra,
             target_dec,
             tessmag,
             teff,
             srad,
             bls_stats1,
             bls_stats2,
             tpf_corrupt,
             astroquery_corrupt,
             FFI,
             bls=False,
             model=False,
             mpi=False,
             test='no'):
    '''
	funtion that makes compiles all of the information and figures into a comprehensive pdf summary document.

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

	'''

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

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

    TCE_links = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Story = []

    fig_count = 0
    table_count = 0

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

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

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

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

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

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

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

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

    Story.append(logo_table)

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

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

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

    fig_count += 1

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

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

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

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

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

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

    data_len = len(data_stellar)

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

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

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

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

    # ------

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

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

    table_count += 1

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

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

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

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

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

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

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

    Story.append(im2)

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

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

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

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

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

        Story.append(im3)

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

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

        Story.append(Spacer(1, 5))

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

        Story.append(Spacer(1, 13))

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

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

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

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

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

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

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

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

        Story.append(im45)

        fig_count += 1

        Story.append(Spacer(1, 10))

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

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

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

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

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

        Story.append(im5)

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

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

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

            Story.append(Spacer(1, 12))

            im6 = Image(tess_stars_name)

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

            Story.append(im6)

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

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

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

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

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

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

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

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

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

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

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

    if len(transit_list) > 1:

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

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

        Story.append(impf)

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

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

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

    if bls == True:

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

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

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

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

        Story.append(bls_table)

        fig_count += 1

        if FFI == False:

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

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

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

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

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

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

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

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

        # ------

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

        data_len = len(data_bls)

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

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

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

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

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

    if model == True:

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

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

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

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

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

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

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

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

        Story.append(im_model)
        fig_count += 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            data_len = len(data_params)

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

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

            Story.append(table_model)

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

    doc.build(Story, onFirstPage=addPageNumber, onLaterPages=addPageNumber)
 def create_logo(self, absolute_path):
     image = Image(absolute_path)
     image._restrictSize(2.5 * inch, 2.5 * inch)
     return image
def crearPdfFicha(fileName, id, propiedad, lenfotos, pro, datospro, interna,
                  datosinterna, regionP, links):
    #Propiedad:
    #DatosPro: Preciov/RentV/PrecioA/RentA, o bien solo PrecioA
    headerslocalizacion = []
    headerspropiedad = []
    headersrentabilidad = []
    headerscontacto = []
    datoslocalizacion = []
    datospropiedad = []
    datosrentabilidad = []
    datoscontacto = []

    uf1 = uf.getUf()
    for x, p in enumerate(propiedad):
        if p is None:
            propiedad[x] = 0
    nombre = str(propiedad[0])
    region = str(propiedad[1])
    comuna = str(propiedad[14])
    operacion = str(propiedad[2])
    tipo = str(propiedad[3])

    headerslocalizacion.append("Operación")
    headerslocalizacion.append("Tipo de Prop.")
    headerslocalizacion.append("Región")
    headerslocalizacion.append("Comuna")

    datoslocalizacion.append(operacion.capitalize())
    datoslocalizacion.append(tipo.capitalize())
    datoslocalizacion.append(regionP.capitalize())
    datoslocalizacion.append(comuna.capitalize())

    precio = int(propiedad[4])

    preciouf = (int(precio / uf1))
    preciouf = str(format(preciouf, ','))
    preciouf = preciouf.replace(',', '.')

    precio = str(format(precio, ','))
    precio = precio.replace(',', '.')

    dormitorios = str(int(propiedad[5]))
    banos = str(int(propiedad[6]))

    metrosmin = str(int(propiedad[7]))
    metrosmax = str(int(propiedad[8]))

    estacionamientos = str(int(propiedad[9]))
    bodegas = str(int(propiedad[10]))

    lat = str(propiedad[11])
    lon = str(propiedad[12])
    link = str(propiedad[13])

    headerspropiedad.append("Precio $")
    if operacion == 'venta':
        headerspropiedad.append("Precio UF")
    headerspropiedad.append("Sup. Util")
    headerspropiedad.append("Sup. Total")
    headerspropiedad.append("Dormitorios")
    headerspropiedad.append("Baños")
    headerspropiedad.append("Estacionamientos")
    headerspropiedad.append("Bodegas")

    datospropiedad.append(precio)
    if operacion == 'venta':
        datospropiedad.append(preciouf)
    datospropiedad.append(metrosmin)
    datospropiedad.append(metrosmax)
    datospropiedad.append(dormitorios)
    datospropiedad.append(banos)
    datospropiedad.append(estacionamientos)
    datospropiedad.append(bodegas)

    descripcion = propiedad[15]

    if pro:
        if operacion == 'venta':
            precioV = datospro[0]
            precioV = precioV / uf1
            precioV = int(precioV)
            precioV = str(format(precioV, ','))
            precioV = precioV.replace(',', '.')
            precioV = 'UF ' + precioV
            rentV = float(datospro[1])
            rentV = int(rentV * 1000)
            rentV = float(rentV / 10)
            rentV = str(rentV) + "%"
            precioA = datospro[2]
            precioA = str(format(precioA, ','))
            precioA = precioA.replace(',', '.')
            precioA = '$ ' + precioA
            rentA = float(datospro[3])
            rentA = int(rentA * 1000)
            rentA = float(rentA / 10)
            rentA = str(rentA) + "%"

            headersrentabilidad.append("Tasación Venta")
            headersrentabilidad.append("Rent. Venta")

            headersrentabilidad.append("Tasación Arriendo")
            headersrentabilidad.append("Rent. Arriendo")

            datosrentabilidad.append(precioV)
            datosrentabilidad.append(rentV)

            datosrentabilidad.append(precioA)
            datosrentabilidad.append(rentA)

        else:
            precioA = datospro[0]
            precioA = str(format(precioA, ','))
            precioA = precioA.replace(',', '.')
            precioA = '$ ' + precioA
            headersrentabilidad.append("Tasación Arriendo")
            datosrentabilidad.append(precioA)

    if interna:
        mail = datosinterna[0]
        headerscontacto.append("Mail")
        datoscontacto.append(mail)

        telefono = datosinterna[1]
        headerscontacto.append("Telefono")
        if 'yapo' in link and telefono != 'NN':
            try:
                image = Image("auxphone.gif")
                image._restrictSize(1.2 * inch, 1.7 * inch)
                datoscontacto.append(image)
            except:
                datoscontacto.append('NN')
        else:
            datoscontacto.append(telefono)

        dueno = datosinterna[2]
        headerscontacto.append("Dueño")
        datoscontacto.append(dueno.capitalize())

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              leading=16))

    doc = SimpleDocTemplate(fileName,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

    Story = []

    tabla = []
    tabla.append(headerslocalizacion)
    tabla.append(datoslocalizacion)

    t1 = Table(tabla, hAlign='LEFT')
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34BAAF')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ]))
    tabla = []
    tabla.append(headerspropiedad)
    tabla.append(datospropiedad)

    t2 = Table(tabla, hAlign='LEFT')
    t2.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 11),
            ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ]))
    if pro:
        tabla = []
        tabla.append(headersrentabilidad)
        tabla.append(datosrentabilidad)

        t3 = Table(tabla, hAlign='LEFT')
        t3.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))
    if interna:
        tabla = []
        tabla.append(headerscontacto)
        tabla.append(datoscontacto)

        t4 = Table(tabla, hAlign='LEFT')
        t4.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))

    image = Image('bull_logo2.png', hAlign='LEFT')
    image._restrictSize(2 * inch, 3 * inch)
    Story.append(image)
    Story.append(Spacer(1, 16))

    if interna:
        ptext = '<font size=11><b>FICHA PROPIEDAD</b>: ' + str(id) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 14))

    else:
        ptext = '<font size=11><b>FICHA PROPIEDAD</b></font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 14))

    Story.append(t1)
    Story.append(Spacer(1, 16))
    Story.append(t2)
    Story.append(Spacer(1, 16))
    if pro:
        Story.append(t3)
        Story.append(Spacer(1, 16))
    if interna:
        Story.append(t4)
        Story.append(Spacer(1, 16))

    ptext = '<font size=11><b>Descripción:</b></font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    if not interna:
        imagenDescripcion = Image('imagenDescripcion.png')
        Story.append(imagenDescripcion)
        Story.append(PageBreak())
    else:
        ptext = '<font size=11>' + str(descripcion) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(PageBreak())

    if len(links) > 0 and interna:
        print("entro en crear tabla de links")
        print(links)
        data = []
        n = 0
        headers = [
            "N°", "UF", "Precio", "UF/mt2", "MtsMin", "MtsMax", "Dorms",
            "Baños", "Link", "Disponibilidad"
        ]
        for l in links:
            if "portal" in l:
                d = []
                n += 1
                d.append(str(n))
                avaible = pubPortalExiste.publicacionExiste(l)
                id = botPropertyConnector.obtenerIdConLink(
                    l, "www.portalinmobiliario.com")
                id = id[0]
                prop = reportes.precio_from_portalinmobiliario(id)
                prop = prop[0]
                print("Arreglo de propiedad:")
                print(prop)
                print("1er dato de propiedad de propiedad:")
                print(prop[0])
                ufn = int(prop[0] / (uf.getUf()))
                d.append(ufn)
                d.append(prop[0])
                d.append((int(20 * ufn / (prop[1] + prop[2]))) / 10)
                d.append(int(prop[1]))
                d.append(int(prop[2]))
                d.append(prop[5])
                d.append(prop[6])
                print(d)
                print("appendeo bien datos")
                linkHtml = '<link href="' + l + '" color="blue">' + "Link" + '</link>'
                print(linkHtml)
                linkHtml = platypus.Paragraph(linkHtml, PS('body'))
                d.append(linkHtml)
                if avaible:
                    d.append("Disponible")
                else:
                    d.append("No disponible")
                print(str(n) + " intento de agregar prop a data")
                print(d)
                data.append(d)
            else:
                pass

        data = [headers] + data
        #t=Table(data,nrCols*[0.6*inch], nrRows*[0.25*inch])
        t = Table(data)
        t.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 9),
            ]))

        Story.append(t)
        Story.append(PageBreak())

    for x in range(0, lenfotos):

        image = Image(str(x) + " foto.jpg", hAlign='LEFT')
        image._restrictSize(6 * inch, 9 * inch)
        Story.append(image)
        Story.append(Spacer(1, 4))

    Story = list(Story)
    doc.build(Story)
Esempio n. 20
0
def person_report(codename, filename):
    codename_id = ensa.db.select_subject(codename)
    # pdb.set_trace()
    infos = ensa.db.get_informations(
        no_composite_parts=False, force_no_current_subject=True)
    # pdb.set_trace()
    infos = [i + ([x[1] for x in ensa.db.get_keywords_for_informations(
        i[0],
        force_no_current_subject=True)],)
             for i in infos]

    images = get_valid_by_keyword(infos, 'image')
    own_images = get_valid_by_keyword(infos, 'image', codename_id)
    composites = [i for i in infos if i[3] == Database.INFORMATION_COMPOSITE]
    own_composites = [i for i in infos if i[3] ==
                      Database.INFORMATION_COMPOSITE and i[1] == codename_id]

    # for info in infos:
    #    print(info)

    doc = SimpleDocTemplate(filename, pagesize=A4)
    font_file = 'source/symbola.ttf'
    symbola_font = TTFont('Symbola', font_file)
    styles['BodyText'].fontName = 'Symbola'
    styles['BodyText'].fontSize = 12
    pdfmetrics.registerFont(symbola_font)

    entries = []

    # infos_dict = {info[4]: info for info in infos}
    """TITLE"""
    entries.append(Paragraph(
        '<para align=center>Person Report</para>',
        styles['Title']))
    entries.append(par('<para align=center spaceAfter=20>reference %s, created %s</para>'
                       % (datetime_to_str(),
                          datetime_to_str(datetime.now()))))

    """basic info"""
    name = ' '.join([i[11] for i in get_valid(infos, 'firstname', codename_id)]
                    + [i[11]
                        for i in get_valid(infos, 'middlename', codename_id)]
                    + [i[11] for i in get_valid(infos, 
                                                'lastname', 
                                                codename_id)])
    try:
        sex = get_valid(infos, 'sex', codename_id)[0][11]
        sex_symbol = ('\u2642' if sex == 'male' else
                      ('\u2640' if sex == 'female' else ''))
    except:
        sex_symbol = ''
    try:
        orientation = get_valid(infos, 'orientation', codename_id)[0][11]
        if orientation == 'heterosexual':
            orientation_symbol = '\u26a4'
        elif orientation == 'bisexual':
            orientation_symbol = '\u26a5'
        elif orientation == 'homosexual':
            orientation_symbol = ('\u26a3' if sex == 'male' else
                                  ('\u26a2' if sex == 'female' else ''))
        else:
            orientation_symbol = ''
    except:
        orientation_symbol = ''
    '''
    # racial_modifiers = '\U0001f3fb\U0001f3fc\U0001f3fd\U0001f3fe\U0001f3ff'
    # http://unicode.org/charts/nameslist/n_2600.html
    # http://xahlee.info/comp/unicode_plants_flowers.html
    font_testing = ('\u2642\u2640\u26a4\u26a5\u26a3\u26a2\u2620\u26ad\u2694'
                    '\u2695\u2625\u26ad\u26ae\u26af\u267f\u271d'
                    # + ''.join('%s\U0001f46e' % r for r in racial_modifiers)
                    '\u23f0\U0001f570\u231a\u23f1\u23f2\u231b\u23f3\u29d7'
                    '\u29d6\U0001f550\U0001f5d3\U0001f4c5\U0001f4c6' # clocks
                    '\U0001f464\U0001f468'  # people
                    '\U0001f30b\U0001fb5b\U0001f5fa\U0001f30d\U0001f30e\U0001f30f'  # locations
                    '\U0001f4d1\U0001f4f0\U0001f4da\U0001f4dd\U0001f4dc\U0001f4c3\U0001f4c4'  # informations
                    '\U0001f418\U0001f98f\U0001f42b\U0001f427\U0001f40b\U0001f420\U0001f42c\U0001f426\U0001f428\U0001f405\U0001f406\U0001f40e\U0001f981\U0001f98a\U0001f42f\U0001f412'  # animals
                    '\U0001f4e6\U0001f4bc'  # items
                    '\u26bf\U0001f5dd\U0001f511\U0001f50f\U0001f510\U0001f512\U0001f513'  # security
                    '\U0001f3e2\U0001f3ed\U0001f3e0\U0001f3d8\U0001f3db'  # buildings
                    + ''.join(set(religion_symbols.values()))
                    + ''.join(set(horoscope_symbols.values()))
                    + ''.join(set(politics_symbols.values())))
    entries.append(par(font_testing))
    entries.append(par(''))
    # '''
    try:
        religion = get_valid_by_level(infos, 'religion', codename_id)[0][11]
    except:
        religion = ''

    try:
        politics = get_valid_by_level(infos, 'politics', codename_id)[0][11]
    except:
        politics = ''

    codename_tuple = get_valid(infos, 'codename', codename_id)[0]
    info_codename_id = codename_tuple[0]
    # codename = codename_tuple[10]

    """Birth, death"""
    # pdb.set_trace()
    time_events = {}
    for event in ['birth', 'death']:
        event_str = ''
        event_value = None
        description = '%s\'s %s' % (codename.title(), event)
        time_assocs = [a for a in ensa.db.get_associations_by_subject(codename)
                       if a[0][6] == description]
        # find association with time entry
        for time_assoc in time_assocs:
            # time entry present and valid?
            if time_assoc[2] and time_assoc[2][0][3]:
                event_str = time_assoc[2][0][1].partition(' ')[0]
                event_value = datetime_from_str(event_str)#.strptime(event_str, '%Y-%m-%d')
                event_str = datetime_to_str(event_value, only_date=True)#datetime.strftime(event_value, '%-d. %-m. %Y')
                break
        # get partial info from Information
        if not event_value:
            try:
                year = get_valid(infos, '%s_year' % event, codename_id)[0][11]
            except:
                year = None
            try:
                month = get_valid(infos, '%s_month' %
                                  event, codename_id)[0][11]
                real_month = month
            except:
                month = '01'
                real_month = '??'
            try:
                day = get_valid(infos, '%s_day' % event, codename_id)[0][11]
                real_day = day
            except:
                day = '01'
                real_day = '??'
            if year:  # at least
                event_str = '-'.join(filter(None, [year, month, day]))
                try:
                    event_value = datetime_from_str(event_str)#datetime.strptime(event_str, '%Y-%m-%d')
                except:
                    pass
                event_str = '-'.join(filter(None,
                                            [year, real_month, real_day]))

        if event_str:
            time_events[event] = (event_str, event_value)

    # compute age if birth, add to birth or death
    birth_sign = ''
    if 'birth' in time_events.keys():
        # and also get the zodiac sign
        if '?' not in time_events['birth'][0]:
            for i in range(len(horoscope)):
                sign, m, d_limit = horoscope[i]
                if time_events['birth'][1].month == m:
                    if time_events['birth'][1].day < d_limit:
                        birth_sign = horoscope_symbols[sign]
                    else:
                        birth_sign = horoscope_symbols[horoscope[(
                            i+1) % 12][0]]
                    break
        else:
            birth_sign = ''

        if 'death' in time_events.keys():
            age = relativedelta(
                time_events['death'][1], time_events['birth'][1]).years
            time_events['death'] = '%s (age %s)' % (
                time_events['death'][0], age)
            time_events['birth'] = '%s %s' % (
                time_events['birth'][0], birth_sign)
        else:
            age = relativedelta(datetime.now(), time_events['birth'][1]).years
            time_events['birth'] = '%s %s (age %s)' % (
                time_events['birth'][0], birth_sign, age)

    # just keep the string version
    for k, v in time_events.items():
        if type(v) == tuple:
            time_events[k] = v[0]

    """ compose basic info """
    basic_info = OrderedDict([
        ('Codename', codename),
        ('Name', name),
        ('Identifier', list(par(i[11])
                            for i in get_valid(infos, 'identifier', codename_id))),
        ('Birth', time_events.get('birth')),
        ('Death', time_events.get('death')),
        ('Known as', list(par(i[11])
                          for i in get_valid(infos, 'nickname', codename_id))),
        ('Characteristics', ' '.join((sex_symbol,
                                      orientation_symbol,
                                      religion_symbols.get(
                                          religion) or religion,
                                      politics_symbols.get(politics) or politics)
                                     ).strip()),
        ('Phone', list(par(i[11])
                       for i in get_valid(infos, 'phone', codename_id))),
        ('Email', list(par(i[11])
                       for i in get_valid(infos, 'email', codename_id))),
        ('Website', list(par('<link href="%s">%s</link>' % (i[11], i[11]))
                         for i in get_valid(infos, 'website', codename_id))),
    ])
    portrait_path = 'files/binary/%d' % info_codename_id
    if os.path.isfile(portrait_path):
        portrait = Image(portrait_path)
    else:
        log.warn('No portrait available.')
        import PIL.Image
        from io import BytesIO
        white = PIL.Image.new('RGB', (150, 200), (255, 255, 255))
        portrait_str = BytesIO()
        white.save(portrait_str, format='PNG')
        portrait = Image(portrait_str)
    portrait._restrictSize(7*cm, 10*cm)

    """Add basic info and portrait to the report"""
    entries.append(Table(
        [[Table(
            [[Paragraph('Basic information', styles['Heading2'])],
             [Table(
                 [[par(k),
                     par(v) if type(v) == str else v]
                  for k, v in basic_info.items() if v],
                 colWidths=[3.5*cm, 9*cm],
                 style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ])
                 # style=test_style(2),
             )]],
            # style=test_style(1),
            hAlign='LEFT'),
          portrait]],
        colWidths=[10*cm, 7.5*cm],
        style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                          # ('BACKGROUND', (0, 0), (-1, -1), test_colors[0]),
                          # ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
                          ]),
        hAlign='CENTER',
        vAlign='TOP'))

    """Address"""
    description = '%s\'s home' % codename.title()
    """find address that is not part of a composite (e.g. work address)"""
    try:
        # pdb.set_trace()
        address = [a for a in infos
                   if a[0] not in [x for i in own_composites for x in i[11]]
                   and a[1] == codename_id
                   and a[3] == Database.INFORMATION_COMPOSITE
                   and a[4] == 'address']
        if address:
            address_id = address[0][0]
            address_lines = format_address(
                get_valid_by_ids(infos, address[0][11], codename_id))
            """get map"""
            # get associations with address
            address_map = None
            address_assocs = [a for a in ensa.db.get_associations_by_information(address_id)
                              if a[0][6] == description]
            # find association with location entry
            for address_assoc in address_assocs:
                if address_assoc[3]:
                    address_locations = [x for x in address_assoc[3]
                                         if x[2] is not None and x[3] is not None]
                    if address_locations:
                        # write lat&lon to address
                        lat, lon = address_locations[0][2:4]
                        lat_str = '%.6f\u00b0 %c' % (
                            abs(lat), 'N' if lat > 0 else 'S')
                        lon_str = '%.6f\u00b0 %c' % (
                            abs(lon), 'E' if lon > 0 else 'W')
                        address_lines.append('%s %s' % (lat_str, lon_str))
                        # create map, load as image
                        with tempfile.NamedTemporaryFile() as f:
                            address_map = get_map([(lat, lon)],
                                                  [description])
                            address_map.savefig(
                                f.name + '.png', bbox_inches='tight', pad_inches=0)
                            address_map = Image(f.name + '.png')
                            address_map._restrictSize(12*cm, 12*cm)
            if address_lines:
                entries.append(Table([[[Paragraph('Address', styles['Heading2'])]
                                       + [par(line) for line in address_lines],
                                       address_map]],
                                     style=TableStyle([
                                         ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                     ]),
                                     colWidths=[5.5*cm, 12*cm],
                                     ))
    except:
        traceback.print_exc()
        address = ['']

    """Likes, skills etc."""
    for category, category_name in (
        ('skill', 'Skills'),
        ('likes', 'Likes'),
        ('dislikes', 'Dislikes'),
        ('trait', 'Traits'),
        ('asset', 'Assets'),
        ('medical', 'Medical conditions'),
    ):
        valids = get_valid(infos, category, codename_id)
        if valids:
            valids_levels = [(k, [x[11] for x in v])
                             for k, v in get_level_sort(valids)]
            t = Table([[par(str(level or '')),
                        par('' + ', '.join(sorted(set(valids))))]
                       for level, valids in valids_levels],
                      colWidths=[cm, 15*cm],
                      # style=test_style(3),
                      )
            entries.append(KeepTogether([
                Paragraph(category_name, styles['Heading2']),
                t]))

    """ Quotations """
    valids = get_valid(infos, 'quotation', codename_id)
    if valids:
        entries.append(Paragraph('Quotations', styles['Heading2']))
        for valid in valids:
            entries.append(Paragraph('<i>%s</i>' %
                                     valid[11], 
                                     getSampleStyleSheet()['BodyText']))

    """Credentials"""
    # get valid credentials for systems
    credentials = []
    credential_tuples = get_valid_by_keyword(infos, 'credentials', codename_id)
    for c in credential_tuples:
        system = c[4]
        creds = get_valid_by_ids(infos, c[11], codename_id)
        try:
            username = [c[11] for c in creds if c[4] == 'username'][0]
            password = [c[11] for c in creds if c[4] == 'password'][0]
        except:
            continue
        credentials.append((system, '%s:%s' % (username, password)))

    if credentials:
        entries.append(KeepTogether([
            Paragraph('Credentials', styles['Heading2']),
            Table(credentials,
                  colWidths=[4*cm, 12*cm],
                  style=TableStyle([
                      ('GRID', (0, 0), (-1, -1), 0.5, 'black'),
                  ])
                  )
        ]))
    # get all usernames, passwords (even invalid)
    usernames = [i[11]
                 for i in infos if i[1] == codename_id and i[4] == 'username']
    if usernames:
        entries.append(KeepTogether([
            Paragraph('Usernames', styles['Heading3']),
            Table([[u] for u in usernames], colWidths=[16*cm])]))

    passwords = [i[11]
                 for i in infos if i[1] == codename_id and i[4] == 'password']
    if passwords:
        entries.append(KeepTogether([
            Paragraph('Passwords', styles['Heading3']),
            Table([[u] for u in passwords], colWidths=[16*cm])]))

    # TODO suggest possible (by family etc.)
    """Job"""
    organization_list = []  # for later map drawing
    # pdb.set_trace()
    jobs = [a for a in ensa.db.get_associations_by_subject(
        codename) if a[0][6].endswith('employee')]
    # TODO sort by start time desc
    job_tables = []
    # for j in jobs:
    #    print(j)
    for job in jobs:
        # pdb.set_trace()
        # skip invalid
        # if not job[0][4]:
        #    print('INVALID')
        #    continue
        job_id = job[0][0]
        try:
            start_date = [x[1].partition(' ')[0]
                          for x in job[2] if 'start date as employee' in x[5]][0]
        except:
            start_date = None
        try:
            end_date = [x[1].partition(
                ' ')[0] for x in job[2] if 'end date as employee' in x[5]][0]
        except:
            end_date = None

        # find the organization
        try:
            info_organization = [i for i in infos if i[0] in [
                i2[0] for i2 in job[1]] if 'organization' in i[12]][0]
            organization_list.append(info_organization[11])
            organization_id = ensa.db.select_subject(info_organization[11])
            info_organization_id = info_organization[0]
        except:
            traceback.print_exc()
            log.warn(
                'Found employee association without organization (#%d).' % job_id)
            continue

        information_row = []
        positions = [i for i in job[1] if i[1] ==
                     codename_id and i[4] == 'position']
        # print(positions, organization)
        # pdb.set_trace()
        try:
            organization_name = get_valid(infos, 'name', organization_id)[0]
            # organization_websites = get_valid(
            #    infos, 'website', organization_id)
            # organization_identifiers = get_valid(
            #    infos, 'identifier', organization_id)
            # organization_accounts = get_valid(
            #    infos, 'account', organization_id)
            # address, map - not here, just in organization report
        except:
            traceback.print_exc()
            continue

        try:
            logo_path = 'files/binary/%d' % info_organization_id
            logo = Image(logo_path)
            logo._restrictSize(3*cm, 2*cm)
        except:
            # traceback.print_exc()
            logo = None

        information_row.append(
            Paragraph(organization_name[11], styles['Heading3']))
        information_row.append(logo)
        # for identifier in organization_identifiers:
        #    information_row.append(par(identifier[10]))
        for position in positions:
            information_row.append(par(position[11]))
        # for website in organization_websites:
        #    information_row.append(website[10])
        # for account in organization_accounts:
        #    information_row.append(account[10])

        date_string = ('%s - %s' % (start_date or '?', end_date or '?')
                       if start_date or end_date else '')

        # add the complete job entry
        for position in positions:
            job_tables.append(
                Table([
                    [logo, Paragraph(organization_name[11],
                                     styles['Heading3'])],
                    ['', date_string],
                    ['', position[11]],
                ],
                    colWidths=[4*cm, 12*cm],
                    style=TableStyle([
                        ('SPAN', (0, 0), (0, -1)),
                        # ('ALIGN', (0, 0), (0, -1), 'CENTER'),
                        # ('GRID', (0, 0), (-1, -1), 0.5, 'black'),
                    ])
                )
            )
    if job_tables:
        entries.append(KeepTogether([
            Paragraph('Job', styles['Heading2']),
            Table([[jt] for jt in job_tables],
                  colWidths=[16*cm],
                  style=TableStyle([
                      # ('GRID', (0, 0), (-1, -1), 0.5, 'gray'),
                      ('LINEBELOW', (0, 0), (-1, -1), 0.5, 'gray'),
                  ])
                  ),
        ]))

    """Social Network"""
    emblem_categories = [('person', '\U0001f464'),
                         ('organization', '\U0001f3ed'),
                         ('animal', '\U0001f418'),
                         ('item', '\U0001f4e6'),
                         ]
    # pdb.set_trace()
    relationships = [
        # r for r in ensa.db.get_associations_by_information(info_codename_id)
        r for r in ensa.db.get_associations_by_subject(codename)
        if len([info for info in r[1] if info[4] in ('codename', 'position')]) == 2
        and (r[0][6].lower().startswith('%s-%s '
                                        % (ensa.db.get_subject_codename(r[1][0][1]), 
                                           ensa.db.get_subject_codename(r[1][1][1])))
             or r[0][6].lower().startswith('%s-%s '
                                           % (ensa.db.get_subject_codename(r[1][1][1]), 
                                              ensa.db.get_subject_codename(r[1][0][1])))
             )
    ]
    #print('relationships:', relationships)
    '''
    emblems = {}
    for r in relationships:
        print(r[0][6])
    '''
    # prepare dict as (codename, codename): (relationship, level, accuracy, validity)
    relationships = [((ensa.db.get_subject_codename(r[1][0][1]),
                       ensa.db.get_subject_codename(r[1][1][1])),
                      (r[0][6].partition(' ')[2],
                       r[0][2],
                       r[0][3],
                       bool(r[0][4])))
                     for r in relationships]

    # pick all colleagues, add relationships
    jobs = [a for a in ensa.db.get_associations_by_subject(
        codename) if a[0][6].endswith('employee')]
    companies = [info[0] for job in jobs for info in job[1]]
    colleagues = [i for a in ensa.db.get_associations_by_information(companies)
                  if a[0][6].endswith('employee') for i in a[1]]
    #print('companies:', companies)
    #print('col:', colleagues)
    '''
    job_infos = [i for i in infos if i[4] ==
                 'position' and i[1] == codename_id]
    colleagues = [i for a in ensa.db.get_associations_by_information(
        [i[0] for i in job_infos]) for i in a[1]]
    '''
    # get original infos with keywords etc.
    colleagues = [i for i in infos if i[0] in [c[0] for c in colleagues]]
    colleagues_used = []
    for colleague in colleagues:
        if colleague[1] == codename_id:
            continue
        if 'organization' in colleague[12]:
            continue
        colleague_codename = ensa.db.get_subject_codename(colleague[1])
        # TODO average with own?
        level = colleague[5]
        accuracy = colleague[6]
        valid = bool(colleague[7])
        if (colleague[1], valid) in colleagues_used:
            continue
        colleagues_used.append((colleague[1], valid))
        relationships.append(
            ((codename, colleague_codename), ('colleague', level, accuracy, valid)))

    # print(colleagues)
    acquaintances = set(sum([k for k, _ in relationships], ()))
    if acquaintances:
        '''
        """find emblems for each acquaintance"""
        emblems = {}
        for acq_info in [i for i in infos if i[4] == 'codename' and i[10] in acquaintances]:
            for category, emblem in emblem_categories:
                if category in acq_info[11]:
                    emblems[acq_info[10]] = emblem
                    break
        '''
        acquaintances.remove(codename)
        # create network, load as image
        network = None
        network_str = get_relationship_graph(
            codename, acquaintances, relationships)
        # codename, acquaintances, relationships, emblems)
        network = Image(network_str)
        network._restrictSize(17*cm, 35*cm)
        entries.append(KeepTogether([
            Paragraph('Social Network',
                      styles['Heading2']), network, PageBreak()]))

    """ Timeline """
    timeline = ensa.db.get_timeline_by_subject(codename)
    event_tables = []

    for event in timeline:
        # skip invalid
        if not event[0][4]:
            continue
        event_time = event[2][0][1]
        event_name = event[0][6]
        event_id = event[0][0]

        # first times if not the main time; \u23f0 or \U0001f4c6
        time_rows = []
        for time in event[2]:
            description = ('%s (%s)' %
                           (time[5], time[1])) if time[5] else ('%s' % time[1])
            if not time[3]:
                description = '<strike>%s</strike>' % description
            time_rows.append(
                par('\U0001f4c6 %s' % description))

        # then codenames (prefer with image); \U0001f464
        # then informations (prefer with image); \U001f4dd
        codename_rows = []
        information_rows = []
        for info in event[1]:
            # get info from infos (components, keywords, etc. present)...
            info = [i for i in infos if i[0] == info[0]][0]
            try:
                photo_path = 'files/binary/%d' % info[0]
                photo = Image(photo_path)
                photo._restrictSize(2*cm, 3*cm)
            except:
                photo = None
                # TODO codename image if not info image...
            if info[4] == 'codename':
                symbol = ''
                for category, emblem in emblem_categories:
                    if category in info[12]:
                        symbol = emblem
                        break
                rows = codename_rows
            else:
                symbol = '\U0001f4dd &lt;%s&gt; %s:' % (
                    ensa.db.get_subject_codename(info[1]), info[4])
                rows = information_rows
            #  get data if composite
            if info[3] == Database.INFORMATION_COMPOSITE:
                components = [(i[4], i[11])
                              for i in infos if i[0] in info[11]]
                text = '\n'.join([symbol] +
                                 ['%s: %s' % c for c in components])
            else:
                text = '%s %s' % (symbol, info[11])
            # mark invalid
            if not info[7]:
                text = '<strike>%s</strike>' % text
            # rows.append(text, photo))
            rows.append(Table([[photo], [center_par(text)]], style=TableStyle(
                [('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                 # ('GRID', (0, 0), (-1, -1), 0.5, 'black'),
                 # ('BACKGROUND', (0, 0), (-1, -1), 'cornflowerblue'),
                 ])))
        info_columns = 4
        ci_rows = codename_rows + information_rows
        if len(ci_rows) < info_columns:
            ci_rows += [''] * (info_columns - len(ci_rows))

        # then locations (with map if possible, with associated address if possible); \U0001f30d
        coords = []
        location_strings = []
        for location in event[3]:
            location_id = location[0]
            location_name = location[1]
            lat = location[2]
            lon = location[3]
            location_strings.append(par('\U0001f30d %s' % location_name))

            l_assocs = ensa.db.get_associations_by_location(location_id)
            address_found = False
            for l_assoc in l_assocs:
                for info in l_assoc[1]:
                    if info[4] == 'address':
                        # get_associations_by_location does not give components
                        # -> we must manually find the values
                        components = [
                            i for i in infos if i[0] == info[0]][0][11]
                        location_strings += format_address(
                            get_valid_by_ids(infos, components, codename_id))
                        address_found = True
                        break
                if address_found:
                    break

            if lat is not None and lon is not None:
                coords.append((lat, lon, location_name))
                lat_str = '%.6f\u00b0 %c' % (abs(lat), 'N' if lat > 0 else 'S')
                lon_str = '%.6f\u00b0 %c' % (abs(lon), 'E' if lon > 0 else 'W')
                location_strings.append('%s %s' % (lat_str, lon_str))

        # create map, load as image
        location_map = None
        if coords:
            with tempfile.NamedTemporaryFile() as f:
                location_map = get_map([c[:2] for c in coords],
                                       [c[2] for c in coords])
                location_map.savefig(
                    f.name + '.png', bbox_inches='tight', pad_inches=0)
                location_map = Image(f.name + '.png')
                # location_map._restrictSize(10*cm, 10*cm)
                location_map._restrictSize(7*cm, 7*cm)
        if location_strings:
            location_row = [
                Table([[Table([[ls] for ls in location_strings]), location_map]], 
                      colWidths=[8*cm, 7*cm], 
                      style=TableStyle([
                          ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                      ]))]
        else:
            location_row = []

        # pdb.set_trace()
        # add the complete timeline entry
        event_tables.append(
            Table([[Paragraph('%s - %s (#%d)' 
                              % (event_time, event_name, event_id), 
                              styles['Heading3'])]]
                  + [[r] for r in time_rows]
                  + [[Table(
                      [[r for r in ci_rows][i:i+info_columns] 
                        for i in range(0, len(ci_rows), info_columns)], 
                      style=TableStyle([
                          # ('GRID', (0, 0), (-1, -1), 0.5, 'black'),
                      ]))]]
                  + [location_row],
                  # style=TableStyle([
                  #    ('GRID', (0, 0), (-1, -1), 0.5, 'black'),
                  # ])
                  )
        )

    if event_tables:
        entries.append(Paragraph('Timeline', styles['Heading2']))
        entries.append(
            Table([[et] for et in event_tables],
                  colWidths=[16*cm],
                  style=TableStyle([
                      # ('GRID', (0, 0), (-1, -1), 0.5, 'gray'),
                      ('LINEBELOW', (0, 0), (-1, -1), 0.5, 'gray'),
                  ])
                  ),
        )

    """ big map of all associated locations """
    # TODO (also with comments?)
    coords = []
    location_associations = ensa.db.get_associations_by_subject(
        organization_list + [codename])
    for association in location_associations:
        for location in association[3]:
            location_name = location[1]
            lat = location[2]
            lon = location[3]
            if lat is not None and lon is not None:
                coords.append((lat, lon, location_name))
    if coords:
        with tempfile.NamedTemporaryFile() as f:
            location_map = get_map([c[:2] for c in coords],
                                   [c[2] for c in coords])
            location_map.savefig(
                f.name + '.png', bbox_inches='tight', pad_inches=0)
            location_map = Image(f.name + '.png')
            location_map._restrictSize(16*cm, 16*cm)
        entries.append(KeepTogether([
            Paragraph('Action map', styles['Heading2']),
            location_map
        ]))

    """ gallery """
    if own_images:
        entries.append(Paragraph('Gallery', styles['Heading2']))
        images_dict = {}
        for image in own_images:
            key = '%s:%s' % (image[4], image[11])
            if key not in images_dict.keys():
                images_dict[key] = []
            images_dict[key].append(image)
        for key, imgs in sorted(images_dict.items(), key=lambda x: x[0]):
            heading = Paragraph(key, styles['Heading3'])
            imgs_in_category = []
            for img in imgs:
                try:
                    image = Image('files/binary/%d' % img[0])
                    image._restrictSize(3.5*cm, 5*cm)
                    # entries.append(image)
                    imgs_in_category.append(image)
                except:
                    traceback.print_exc()
                    continue
            columns = 4
            if not imgs_in_category:
                continue
            t = (Table([imgs_in_category[i:i+columns]
                        for i in range(0, len(imgs_in_category), columns)],
                       hAlign='LEFT',
                       style=TableStyle([
                           # ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
                           ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                           ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                       ])))
            entries.append(KeepTogether([heading, t]))
    """ all (unused) informations with comments and keywords for codename_id"""
    # TODO

    """ build PDF from individual entries"""
    doc.build(entries)
Esempio n. 21
0
def create_pdf_doc(input_file, output_file):
    pdfmetrics.registerFont(TTFont('FontAwesome', 'font_awesome.ttf'))
    heading_style = ParagraphStyle(name='Normal',
                                   fontName='Helvetica',
                                   spaceAfter=0.25 * cm,
                                   spaceBefore=0.5 * cm,
                                   fontSize=15,
                                   leading=18)
    subheading_style = ParagraphStyle(name='Normal',
                                      fontName='Helvetica',
                                      spaceAfter=0.2 * cm,
                                      spaceBefore=0.4 * cm,
                                      fontSize=13,
                                      leading=18)
    paragraph_style = ParagraphStyle(name='Normal',
                                     fontName='Times-Roman',
                                     fontSize=11,
                                     leading=18)
    small_style = ParagraphStyle(name='Normal',
                                 fontName='Times-Roman',
                                 fontSize=8)
    doc = SimpleDocTemplate(output_file, author=AUTHOR, title=TITLE)
    story = [Spacer(1, 3.5 * cm)]
    link_template = '<link href="{0}" color="blue">{0}</link>'
    # create necessary building blocks for each recipe
    for recipe in parse_xml_file(input_file):
        substory = []
        recipe_heading = Heading('{}'.format(recipe.title.string),
                                 heading_style)
        substory.append(recipe_heading)

        # build block with information about the recipe
        topline = []
        if recipe.source:
            topline.append('Quelle: {}'.format(recipe.source.string))
        if recipe.link:
            topline.append('Link: {}'.format(
                link_template.format(recipe.link.string)))
        if recipe.rating:
            topline.append('Bewertung: {}'.format(
                starify_rating(recipe.rating.string)))
        if recipe.category:
            topline.append('Kategorie: {}'.format(recipe.category.string))
        substory.append(Paragraph('<br/>'.join(topline), small_style))

        # extract image if it exists
        if recipe.image:
            im = Image(io.BytesIO(base64.b64decode(recipe.image.string)))
            im._restrictSize(7 * cm, 7 * cm)
            im.hAlign = 'RIGHT'
        else:
            im = Paragraph('', paragraph_style)

        # extract all ingredient groups with their ingredients
        ingredient_groups = []
        # TODO: Search only in <ingredient-list> tag.
        igroup_tags = recipe.find_all('inggroup')
        if igroup_tags:
            for igroup in igroup_tags:
                ingredient_groups.append(add_ingredients_for_group(igroup))
        else:
            ingredient_groups.append(add_ingredients_for_group(recipe))

        # build two columns for ingredients and image (covering multiple rows!)
        substory.append(Paragraph('Zutaten', subheading_style))
        try:
            data = [[ingredient_groups[0][0], im]]
        except:
            data = [[
                Paragraph('Keine Zutaten für dieses Rezept gegeben!',
                          paragraph_style), im
            ]]
        # add remaining ingredients for first ingredients group
        for i in ingredient_groups[0][1:]:
            data.append([i])
        # add ingredients for all remaining ingredient groups to document
        for g in ingredient_groups[1:]:
            data.append([Spacer(1, 2 * mm)])
            for i in g:
                data.append([i])
        # build table from list of elements
        table = Table(data, splitByRow=True)
        table.setStyle(
            TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                        ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                        ('SPAN', (1, 0), (1,
                                          min(10,
                                              len(ingredient_groups[0]) - 1))),
                        ('ALIGN', (-1, 0), (-1, 0), 'RIGHT')]))
        substory.append(table)
        # build text blocks for instructions and notes
        if recipe.instructions:
            substory.append(Paragraph('Anweisungen', subheading_style))
            s = recipe.instructions.string.replace('\n', '<br/>')
            substory.append(Paragraph('{}'.format(s), paragraph_style))
        if recipe.modifications:
            substory.append(Paragraph('Notizen', subheading_style))
            s = recipe.modifications.string.replace('\n', '<br/>')
            substory.append(Paragraph('{}'.format(s), paragraph_style))
        # break page after each recipe if PAGE_BREAK_AFTER_RECIPE is true
        if PAGE_BREAK_AFTER_RECIPE:
            substory.append(PageBreak())
        else:
            substory.append(
                Paragraph('<br/><br/><br/>', ParagraphStyle(name='Normal')))
        story = story + substory
    doc.build(story,
              onFirstPage=create_first_page,
              onLaterPages=create_later_pages)
def crearPdfFicha(fileName, id, propiedad, lenfotos, pro, datospro, interna,
                  datosinterna, regionP, links):
    #Propiedad:
    #DatosPro: Preciov/RentV/PrecioA/RentA, o bien solo PrecioA
    headerslocalizacion = []
    headerspropiedad = []
    headersrentabilidad = []
    headerscontacto = []
    datoslocalizacion = []
    datospropiedad = []
    datosrentabilidad = []
    datoscontacto = []

    if pro == "financiera":
        pro = True
        financiera = True
    else:
        financiera = False

    uf1 = uf.getUf()
    for x, p in enumerate(propiedad):
        if p is None:
            propiedad[x] = 0
    nombre = str(propiedad[0])
    region = str(propiedad[1])
    comuna = str(propiedad[14])
    operacion = str(propiedad[2])
    tipo = str(propiedad[3])

    headerslocalizacion.append("Operación")
    headerslocalizacion.append("Tipo de Prop.")
    headerslocalizacion.append("Región")
    headerslocalizacion.append("Comuna")

    datoslocalizacion.append(operacion.capitalize())
    datoslocalizacion.append(tipo.capitalize())
    datoslocalizacion.append(regionP.capitalize())
    datoslocalizacion.append(comuna.capitalize())

    precio = int(propiedad[4])
    precioreal = precio
    precioufreal = precio / uf1
    preciouf = (int(precio / uf1))
    preciouf = str(format(preciouf, ','))
    preciouf = preciouf.replace(',', '.')

    precio = str(format(precio, ','))
    precio = precio.replace(',', '.')

    dormitorios = str(int(propiedad[5]))
    banos = str(int(propiedad[6]))

    metrosmin = str(int(propiedad[7]))
    metrosmax = str(int(propiedad[8]))

    estacionamientos = str(int(propiedad[9]))
    bodegas = str(int(propiedad[10]))

    lat = str(propiedad[11])
    lon = str(propiedad[12])
    link = str(propiedad[13])

    headerspropiedad.append("Precio $")
    if operacion == 'venta':
        headerspropiedad.append("Precio UF")
    headerspropiedad.append("Sup. Util")
    headerspropiedad.append("Sup. Total")
    headerspropiedad.append("Dormitorios")
    headerspropiedad.append("Baños")
    headerspropiedad.append("Estacionamientos")
    headerspropiedad.append("Bodegas")

    datospropiedad.append(precio)
    if operacion == 'venta':
        datospropiedad.append(preciouf)
    datospropiedad.append(metrosmin)
    datospropiedad.append(metrosmax)
    datospropiedad.append(dormitorios)
    datospropiedad.append(banos)
    datospropiedad.append(estacionamientos)
    datospropiedad.append(bodegas)

    descripcion = propiedad[15]

    if pro:
        if operacion == 'venta':
            precioV = datospro[0]
            precioVreal = precioV
            precioV = precioV / uf1
            precioV = int(precioV)
            precioV = str(format(precioV, ','))
            precioV = precioV.replace(',', '.')
            precioV = 'UF ' + precioV
            rentV = float(datospro[1])
            rentV = int(rentV * 1000)
            rentV = float(rentV / 10)
            rentV = str(rentV) + "%"
            precioA = datospro[2]
            precioAreal = 10000 * (int(precioA / 10000))
            precioA = int(precioA)
            precioA = str(format(precioA, ','))
            precioA = precioA.replace(',', '.')
            precioA = '$ ' + precioA
            rentA = float(datospro[3])
            rentA = int(rentA * 1000)
            rentA = float(rentA / 10)
            rentA = str(rentA) + "%"

            headersrentabilidad.append("Tasación Venta")
            headersrentabilidad.append("Rent. Venta")

            headersrentabilidad.append("Tasación Arriendo")
            headersrentabilidad.append("Rent. Arriendo")

            datosrentabilidad.append(precioV)
            datosrentabilidad.append(rentV)

            datosrentabilidad.append(precioA)
            datosrentabilidad.append(rentA)

        else:
            precioA = datospro[0]
            precioA = int(precioA[0])
            precioA = str(format(precioA, ','))
            precioA = precioA.replace(',', '.')
            precioA = '$ ' + precioA
            headersrentabilidad.append("Tasación Arriendo")
            datosrentabilidad.append(precioA)

    if interna:
        mail = datosinterna[0]
        headerscontacto.append("Mail")
        datoscontacto.append(mail)

        telefono = datosinterna[1]
        headerscontacto.append("Telefono")
        if 'yapo' in link and telefono != 'NN':
            try:
                image = Image("auxphone.gif")
                image._restrictSize(1.2 * inch, 1.7 * inch)
                datoscontacto.append(image)
            except:
                datoscontacto.append('NN')
        else:
            datoscontacto.append(telefono)

        dueno = datosinterna[2]
        headerscontacto.append("Dueño")
        datoscontacto.append(dueno.capitalize())

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              leading=16))

    doc = SimpleDocTemplate(fileName,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

    Story = []

    tabla = []
    tabla.append(headerslocalizacion)
    tabla.append(datoslocalizacion)

    t1 = Table(tabla, hAlign='LEFT')
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34BAAF')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ]))
    tabla = []
    tabla.append(headerspropiedad)
    tabla.append(datospropiedad)

    t2 = Table(tabla, hAlign='LEFT')
    t2.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 11),
            ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ]))
    if pro:
        tabla = []
        tabla.append(headersrentabilidad)
        tabla.append(datosrentabilidad)

        t3 = Table(tabla, hAlign='LEFT')
        t3.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))
    if interna:
        tabla = []
        tabla.append(headerscontacto)
        tabla.append(datoscontacto)

        t4 = Table(tabla, hAlign='LEFT')
        t4.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))

    try:
        image = Image('bull_logo2.png', hAlign='LEFT')
        image._restrictSize(2 * inch, 3 * inch)
        Story.append(image)
        Story.append(Spacer(1, 16))
    except:
        try:
            image = Image('bull_logo.jpg', hAlign='LEFT')
            image._restrictSize(2 * inch, 3 * inch)
            Story.append(image)
            Story.append(Spacer(1, 16))
        except:
            pass

    if interna:
        ptext = '<font size=11>FICHA PROPIEDAD: ' + str(id) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 14))

    else:
        ptext = '<font size=11>FICHA PROPIEDAD</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 14))

    Story.append(t1)
    Story.append(Spacer(1, 16))
    Story.append(t2)
    Story.append(Spacer(1, 16))
    if pro:
        Story.append(t3)
        Story.append(Spacer(1, 16))
    if interna:
        Story.append(t4)
        Story.append(Spacer(1, 16))

    ptext = '<font size=11>Descripción:</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    if not interna:
        imagenDescripcion = Image('imagenDescripcion.png')
        Story.append(imagenDescripcion)
        Story.append(PageBreak())
    else:
        ptext = '<font size=11>' + str(descripcion) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(PageBreak())

    if len(links) > 0 and interna:
        print("entro en crear tabla de links")
        print(links)
        data = []
        n = 0
        headers = [
            "N°", "UF", "Precio", "UF/mt2", "MtsMin", "MtsMax", "Dorms",
            "Baños", "Link", "Disponibilidad"
        ]
        for l in links:
            if "portal" in l:
                d = []
                n += 1
                d.append(str(n))
                avaible = pubPortalExiste.publicacionExiste(l)
                id = botPropertyConnector.obtenerIdConLink(
                    l, "www.portalinmobiliario.com")
                id = id[0]
                prop = reportes.precio_from_portalinmobiliario(id)
                prop = prop[0]
                print("Arreglo de propiedad:")
                print(prop)
                print("1er dato de propiedad de propiedad:")
                print(prop[0])
                ufn = int(prop[0] / (uf.getUf()))
                d.append(ufn)
                d.append(prop[0])
                d.append((int(20 * ufn / (prop[1] + prop[2]))) / 10)
                d.append(int(prop[1]))
                d.append(int(prop[2]))
                d.append(prop[5])
                d.append(prop[6])
                print(d)
                print("appendeo bien datos")
                linkHtml = '<link href="' + l + '" color="blue">' + "Link" + '</link>'
                print(linkHtml)
                linkHtml = platypus.Paragraph(linkHtml, PS('body'))
                d.append(linkHtml)
                if avaible:
                    d.append("Disponible")
                else:
                    d.append("No disponible")
                print(str(n) + " intento de agregar prop a data")
                print(d)
                data.append(d)
            else:
                pass

        data = [headers] + data
        #t=Table(data,nrCols*[0.6*inch], nrRows*[0.25*inch])
        t = Table(data)
        t.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))

        Story.append(t)
        Story.append(PageBreak())
    print("Antes de entrar a datos financieros")
    if pro and financiera and operacion == 'venta':

        print("entro datos financieros")
        tasacion = datospro[0]
        tasacionUF = (precioVreal / uf1)

        ftext = '<font size=11>Propuesta de Compra Arriendo y Posterior Venta en un Período de 7 Meses, ofertando 95% Valor propiedad, Revendiendo a 95%  del valor de tasación:</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        Story.append(Spacer(1, 14))
        rent = (
            1 +
            (((0.95 * tasacionUF - ((0.95) * precioufreal)) * 0.81 -
              ((0.95) * precioufreal) * 0.031) - 25 + precioAreal * 7 / uf1) /
            ((0.95) * precioufreal * 1.031 + 25) - 0.25 *
            ((((0.95 * tasacionUF - ((0.95) * precioufreal)) * 0.81 -
               ((0.95) * precioufreal) * 0.031) - 25 + precioAreal * 7 / uf1) /
             ((0.95) * precioufreal * 1.031 + 25) - 0.05))**(12 / 7) - 1
        data = [
            ["Item", "Valor"],
            [
                "Rent. de arriendo(1)",
                str(
                    int(1000 * (precioAreal * 12 / uf1 /
                                ((0.95) * precioufreal * 1.031 + 14))) / 10) +
                "%"
            ],
            [
                "Rent. Capital (2)",
                str(
                    int(1000 * (((0.95 * tasacionUF -
                                  ((0.95) * precioufreal)) * 0.81 -
                                 ((0.95) * precioufreal) * 0.031) - 14) /
                        ((0.95) * precioufreal * 1.031 + 14)) / 10) + "%"
            ],
            [
                "Rent. Total(3)",
                str(
                    int(1000 * (((0.95 * tasacionUF -
                                  ((0.95) * precioufreal)) * 0.81 -
                                 ((0.95) * precioufreal) * 0.031) - 14 +
                                precioAreal * 7 / uf1) /
                        ((0.95) * precioufreal * 1.031 + 14)) / 10) + "%"
            ],
            [
                "Rentabilidad Neta(4)",
                str(int(1000 * ((1 + rent)**(7 / 12) - 1)) / 10) + "%"
            ],
            [
                "Rentabilidad Neta UF (5)",
                str(
                    int(((int((0.95) * precioufreal * 1.031 + 25)) *
                         ((1 + rent)**(7 / 12) - 1)))) + " UF"
            ],
            ["Rentabilidad Anual Neta(6)",
             str(int(1000 * rent) / 10) + "%"], ["Costos Legales(7)", "25 UF"],
            [
                "Costos de Corretaje(8)",
                str(int(0.02 * 0.95 * precioufreal)) + " UF"
            ],
            [
                "IVA(9)",
                str(int((0.95 * tasacionUF -
                         ((0.95) * precioufreal)) * 0.19)) + " UF"
            ],
            [
                "Total Inversión Inicial(10)",
                str(int((0.95) * precioufreal * 1.031 + 25)) + " UF"
            ],
            [
                "Comisión BullEstate(11)",
                str(
                    int(0.25 * ((((0.95 * tasacionUF -
                                   ((0.95) * precioufreal)) * 0.81 -
                                  ((0.95) * precioufreal) * 0.031) - 25 +
                                 precioAreal * 7 / uf1) - 0.05 *
                                ((0.95) * precioufreal * 1.031 + 25)) +
                        0.01 * 0.95 * precioufreal)) + " UF"
            ]
        ]

        t = Table(data)
        table_style = (TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34BAAF')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
        ]))
        t.setStyle(table_style)
        Story.append(t)
        Story.append(Spacer(1, 14))

        ftext = '<font size=6>(1)Rentabilidad calculada como doce veces el valor de arriendo dividido por el total de inversión.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(2)Rentabilidad calculada como (valor de reventa - total inversión)/total inversión.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(3)Rentabilidad de Arriendo + Rentabilidad de Capital, durante ciclo de inversión.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(4)Rentabilidad neta de un ciclo de inversión, descontando gastos.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(5)Rentabilidad neta en UF de un ciclo de inversión, descontando gastos.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(6)Rentabilidad neta anualizada</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(7)Estudio de títulos, pago de CBR y notaría.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(8)Valor correspondiente al 2% de costos de corretaje, al comprar propiedad</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(9) Valor correspondiente al 19% de la diferencia entre valor compra y valor re-venta</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(10) Valor propiedad más corretaje, gastos legales, y comisión Fija de Bullestate</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(11)Comisión correspondiente al 1% más un 25% de la utilidad obtenida sobre 5% por parte del Cliente.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        Story.append(Spacer(1, 14))
        Story.append(PageBreak())

        reventas = [0.9, 0.925, 0.95, 0.975, 1]

        for rev in reventas:
            ftext = '<font size=11>INFO FINANCIERA (Reventa al ' + (str(
                int(1000 * rev) / 10)).replace('.', ',') + '% - ' + str(
                    format(int(rev * tasacionUF), ',')).replace(
                        ',', '.') + ' UF - $' + str(
                            format(int(rev * tasacion), ',')).replace(
                                ',', '.') + ':</font>'

            Story.append(Paragraph(ftext, styles["Justify"]))
            Story.append(Spacer(1, 14))
            data = []
            headers = ["Valor UF:", "Valor Pesos", "% Oferta"]
            for i in range(1, 16):
                headers.append(str(i))

            for n in range(0, 9):
                row = []
                row.append(
                    (str(format(int((0.8 + 0.025 * n) * precioufreal),
                                ','))).replace(',', '.'))
                row.append(
                    (str(format(int((0.8 + 0.025 * n) * precioreal),
                                ','))).replace(',', '.'))
                row.append(str(80 + 2.5 * n) + "%")
                for i in range(1, 16):
                    tasacionUF = float(tasacionUF)
                    precioufreal = float(precioufreal)
                    precioAreal = float(precioAreal)
                    uf1 = float(uf1)
                    rev = float(rev)
                    rent = (1 + (((rev * tasacionUF -
                                   ((0.8 + 0.025 * n) * precioufreal)) * 0.81 -
                                  ((0.8 + 0.025 * n) * precioufreal) * 0.031) -
                                 25 + precioAreal * i / uf1) /
                            ((0.8 + 0.025 * n) * precioufreal * 1.031 + 25) -
                            0.25 *
                            ((((rev * tasacionUF -
                                ((0.8 + 0.025 * n) * precioufreal)) * 0.81 -
                               ((0.8 + 0.025 * n) * precioufreal) * 0.031) -
                              25 + precioAreal * i / uf1) /
                             ((0.8 + 0.025 * n) * precioufreal * 1.031 + 25) -
                             0.05))**(12 / i) - 1
                    rent = str((int(1000 * rent)) / 10) + "%"
                    row.append(rent)
                data.append(row)

            data = [headers] + data
            #t=Table(data,nrCols*[0.6*inch], nrRows*[0.25*inch])
            t = Table(data)
            table_style = (TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34BAAF')),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 6.5),
            ]))
            t.setStyle(table_style)
            for row, values, in enumerate(data):
                for column, value in enumerate(values):
                    try:
                        print(value)
                        intvalue = float(value[:-1])
                        print(intvalue)
                        if intvalue < 0:
                            table_style.add('BACKGROUND', (column, row),
                                            (column, row), colors.red)
                        if intvalue > 0.2:
                            table_style.add('BACKGROUND', (column, row),
                                            (column, row), colors.limegreen)
                        if intvalue > 0.5:
                            table_style.add('BACKGROUND', (column, row),
                                            (column, row), colors.darkgreen)
                    except:
                        pass
            Story.append(t)
            Story.append(Spacer(1, 14))
        Story.append(PageBreak())

    for x in range(0, lenfotos):

        image = Image(str(x) + " foto.jpg", hAlign='LEFT')
        image._restrictSize(6 * inch, 9 * inch)
        Story.append(image)
        Story.append(Spacer(1, 4))

    Story = list(Story)
    doc.build(Story)
Esempio n. 23
0
        tabList.append(
            ["Species:", ", ".join([i for i in df.columns if i != "Time"])])
        tabList.append(["Reference:", newRefs[ID2]])
        return Table(tabList)
    return Table([["fig:", ID]])


styles = getSampleStyleSheet()
"""
tempPar = Paragraph("test text", style = styles["Normal"])
story.append(tempPar)
"""

if not supressHeader:
    tempIm = Image(os.path.join(working_directory, "Tital Card.png"))
    tempIm._restrictSize(PW - 2.2 * inch, PH - 2.2 * inch)
    story.append(tempIm)

    tempIm = Image(os.path.join(working_directory, "motivation.png"))
    tempIm._restrictSize(PW - 2.2 * inch, PH - 2.2 * inch)
    story.append(tempIm)

    tempIm = Image(os.path.join(working_directory, "newModelHandAn.jpg"))
    tempIm._restrictSize(PW - 2.2 * inch, PH - 2.2 * inch)
    story.append(tempIm)

    tempIm = Image(os.path.join(working_directory, "workflow.png"))
    tempIm._restrictSize(PW - 2.2 * inch, PH - 2.2 * inch)
    story.append(tempIm)

for i, imNameAl, imNameNew in zip(range(1,