コード例 #1
0
def atualizarVenda(nomeVend, naturalidadeVend, estadoCivilVend, profissaoVend,
                   rgVend, cpfVend, ruaVend, numVend, bairroVend, cepVend,
                   cidadeVend, estadoVend, nomeComp, naturalidadeComp,
                   estadoCivilComp, profissaoComp, rgComp, cpfComp, ruaComp,
                   numComp, bairroComp, cepComp, cidadeComp, estado, area,
                   registro, valor):
    #Definindo o formato do PDF
    pdf = FPDF('P', 'mm', 'A4')
    #Definindo as margens
    pdf.set_margins(10, 10, 10)
    #Adicionando página
    pdf.add_page()
    #Adicionando configurações de Fonte

    pdf.set_font('Arial', 'B', 16)
    #Inserindo linhas cell by cell.
    contrato = 'CONTRATO E COMPROMISSO DE COMPRA E VENDA DE IMÓVEL'
    utxt1 = unicode(contrato, 'UTF-8')
    stxt1 = utxt1.encode('iso-8859-1')
    pdf.cell(0, 10, stxt1, 1, 1, 'C')
    pdf.ln(10)
    #Dados pessoais das partes interessadas

    pdf.set_font('Arial', '', 8)
    vendedor = 'PROMITENTE VENDEDOR: ' + nomeVend + ', nascido em ' + naturalidadeVend + ', ' + estadoCivilVend + ',' + profissaoVend + ',portador do R.G. nº ' + rgVend + ' ,'
    vendedor += '  e CPF/MF nº ' + cpfVend + ' residente e domiciliado à ' + ruaVend + ', ' + numVend + ', ' + bairroVend + ', ' + cepVend + ', ' + cidadeVend + ', ' + estadoVend + '.'
    utxt2 = unicode(vendedor, 'UTF-8')
    stxt2 = utxt2.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt2, 0, 'J')

    comprador = 'PROMITENTE COMPRADOR: ' + nomeComp + ', ' + naturalidadeComp + ', ' + estadoCivilComp + ', ' + profissaoComp + ', portador do R.G. nº ' + rgComp + ','
    comprador += ' e CPF/MF nº ' + cpfComp + ' residente e domiciliado à ' + ruaComp + ', ' + numComp + ', ' + bairroComp + ', ' + cepComp + ', ' + cidadeComp + ', ' + estado + '.'
    utxt3 = unicode(comprador, 'UTF-8')
    stxt3 = utxt3.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt3, 0, 'J')
    pdf.ln(5)

    pdf.set_font('Arial', 'B', 10)
    clausulas = 'Têm entre os mesmos, de maneira justa e acordada, o presente contrato particular de compromisso de compra e venda de bem imóvel, ficando desde já aceito, pelas cláusulas abaixo descritas:'
    utxt4 = unicode(clausulas, 'UTF-8')
    stxt4 = utxt4.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt4, 0, 'J')
    pdf.ln(3)

    pdf.set_font('Arial', '', 8)
    pdf.ln(1)
    primeira = 'CLÁUSULA PRIMEIRA:'
    utxt5 = unicode(primeira, 'UTF-8')
    stxt5 = utxt5.encode('iso-8859-1')
    pdf.cell(33, 5, stxt5, 1, 1, 'L')
    pdf.ln(1)

    clausulaPrimeira = 'Que a PROMITENTE VENDEDORA é legítima possuidora do imóvel composto por área privativa de ' + area + ' metros quadrados, '
    clausulaPrimeira += 'inscrito no livro de registro de imóveis sob nº ' + registro + ', com as seguintes confrontações:'
    utxt6 = unicode(clausulaPrimeira, 'UTF-8')
    stxt6 = utxt6.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt6, 0, 'J')
    pdf.ln(2)

    segunta = 'CLÁUSULA SEGUNDA:'
    utxt7 = unicode(segunta, 'UTF-8')
    stxt7 = utxt7.encode('iso-8859-1')
    pdf.cell(33, 5, stxt7, 1, 1, 'L')
    pdf.ln(1)

    clausulaSegunda = 'O valor da presente transação é feita pelo preço de R$ ' + valor + ', que serão pagos de acordo com o que as partes acharem cabíveis.'
    utxt8 = unicode(clausulaSegunda, 'UTF-8')
    stxt8 = utxt8.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt8, 0, 'J')
    pdf.ln(2)

    terceira = 'CLÁUSULA TERCEIRA:'
    utxt9 = unicode(terceira, 'UTF-8')
    stxt9 = utxt9.encode('iso-8859-1')
    pdf.cell(33, 5, stxt9, 1, 1, 'L')
    pdf.ln(1)

    clausulaTerceira = 'Que o PROMITENTE VENDEDOR se compromete a entregar o imóvel livre e desembaraçado de todos os débitos até esta data, junto ao Agente Financeiro'
    clausulaTerceira += ', ficando daí a responsabilidade do PROMITENTE COMPRADORE o pagamento mensal da prestação.'
    utxt10 = unicode(clausulaTerceira, 'UTF-8')
    stxt10 = utxt10.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt10, 0, 'J')
    pdf.ln(2)

    quarta = 'CLÁUSULA QUARTA:'
    utxt11 = unicode(quarta, 'UTF-8')
    stxt11 = utxt11.encode('iso-8859-1')
    pdf.cell(33, 5, stxt11, 1, 1, 'L')
    pdf.ln(1)

    clausulaQuarta = 'Fica acordado entre o PROMITENTE VENDEDOR e PROMITENTE COMPRADOR que o imóvel transacionado permanecerá em nome do PROMITENTE VENDEDOR por '
    clausulaQuarta += 'prazo indeterminado, ficando o PROMITENTE VENDEDOR obrigado a apresentar os documentos necessários para transrência a partir do momento em que '
    clausulaQuarta += 'o mesmo for notificado pelo PROMITENTE COMPRADOR a qualquer época. '
    utxt12 = unicode(clausulaQuarta, 'UTF-8')
    stxt12 = utxt12.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt12, 0, 'J')
    pdf.ln(2)

    quinta = 'CLÁUSULA QUINTA:'
    utxt13 = unicode(quinta, 'UTF-8')
    stxt13 = utxt13.encode('iso-8859-1')
    pdf.cell(33, 5, stxt13, 1, 1, 'L')
    pdf.ln(1)

    clausulaQuinta = 'Todos os compromissos assumidos neste contrato são de caráter irrevogável e irrefratével, obrigado as partes, seus herdeiros e sucessores a qualquer'
    clausulaQuinta += 'título fazer sempre boa e valiosa a presente cessão, ficando sujeito às penalidades da lei.'
    utxt14 = unicode(clausulaQuinta, 'UTF-8')
    stxt14 = utxt14.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt14, 0, 'J')
    pdf.ln(2)

    sexta = 'CLÁUSULA SEXTA:'
    utxt15 = unicode(sexta, 'UTF-8')
    stxt15 = utxt15.encode('iso-8859-1')
    pdf.cell(33, 5, stxt15, 1, 1, 'L')
    pdf.ln(1)

    clausulaSexta = 'Fica ainda acordando, que caso haja necessidade de se beneficiar do seguro referente ao imóvel,os beneficiados será o PROMITENTE COMPRADOR,ou filhos.'
    utxt16 = unicode(clausulaSexta, 'UTF-8')
    stxt16 = utxt16.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt16, 0, 'J')
    pdf.ln(2)

    setima = 'CLÁUSULA SÉTIMA:'
    utxt17 = unicode(setima, 'UTF-8')
    stxt17 = utxt17.encode('iso-8859-1')
    pdf.cell(33, 5, stxt17, 1, 1, 'L')
    pdf.ln(1)

    clausulaSetima = 'Em caso de falecimento do PROMITENTE VENDEDOR ,fica acordando entre as partes que todo e qualquer benefício oriundo deste fato,transfere-se'
    clausulaSetima += 'para o PROMITENTE COMPRADOR.'
    utxt18 = unicode(clausulaSetima, 'UTF-8')
    stxt18 = utxt18.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt18, 0, 'J')
    pdf.ln(2)

    oitava = 'CLÁUSULA OITAVA:'
    utxt19 = unicode(oitava, 'UTF-8')
    stxt19 = utxt19.encode('iso-8859-1')
    pdf.cell(33, 5, stxt19, 1, 1, 'L')
    pdf.ln(1)

    clausulaOitava = 'Caso haja manifestação pública por parte do Agente Financeiro, quando à transferência do imóvel citado neste instrumento particular de compra'
    clausulaOitava += 'venda, sem que haja o aumento das prestações fica acordo entre as partes a sua transferência.'
    utxt20 = unicode(clausulaOitava, 'UTF-8')
    stxt20 = utxt20.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt20, 0, 'J')
    pdf.ln(2)

    nona = 'CLÁUSULA NONA:'
    utxt21 = unicode(nona, 'UTF-8')
    stxt21 = utxt21.encode('iso-8859-1')
    pdf.cell(33, 5, stxt21, 1, 1, 'L')
    pdf.ln(1)

    clausulaNona = 'O foro deste contrato é da Comarca de, renunciando as partes quaisquer outro por mais privilegiado que seja.E por estarem assim  juntos e'
    clausulaNona += 'contra  assinam o presente em 03 (Três) vias de igual teor e forma, na presença das testemunhas abaixo.'
    utxt22 = unicode(clausulaNona, 'UTF-8')
    stxt22 = utxt22.encode('iso-8859-1')
    pdf.multi_cell(0, 5, stxt22, 0, 'J')
    pdf.ln(3)

    pdf.cell(
        0, 10,
        '____________________________________________   _____ , _____ , _________',
        0, 1, 'C')
    pdf.ln(10)

    pdf.cell(0, 5, 'PROMITENTE COMPRADOR:', 0, 1, 'C')
    pdf.cell(0, 5, '__________________________________________________', 0, 1,
             'C')
    pdf.cell(0, 5, 'PROMITENTE VENDEDOR:', 0, 1, 'C')
    pdf.cell(0, 5, '__________________________________________________', 0, 1,
             'C')
    pdf.cell(0, 5, 'TESTEMUNHA:', 0, 1, 'C')
    pdf.cell(0, 5, '__________________________________________________', 0, 1,
             'C')
    pdf.cell(0, 5, 'R.G.:', 0, 1, 'C')
    pdf.cell(0, 5, '__________________________________________________', 0, 1,
             'C')
    pdf.cell(0, 5, 'TESTEMUNHA:', 0, 1, 'C')
    pdf.cell(0, 5, '__________________________________________________', 0, 1,
             'C')
    pdf.cell(0, 5, 'R.G.:', 0, 1, 'C')
    pdf.cell(0, 5, '__________________________________________________', 0, 1,
             'C')

    pdf.output('numero%s.pdf' % (registro), 'F')
コード例 #2
0
    def __init__(self, path):
        self.path = path

        self.pdf = FPDF('P', 'mm', 'A4')
        self.page_setup()
コード例 #3
0
    def add_watermark_image_to_pdf(
        self,
        image_path: FilePath,
        output_path: FilePath,
        source_path: Optional[FilePath] = None,
        coverage: float = 0.2,
    ) -> None:
        """Add an image into an existing or new PDF.

        If no source path is given, assume a PDF is already opened.

        **Examples**

        **Robot Framework**

        .. code-block:: robotframework

            ***Settings***
            Library    RPA.PDF

            ***Tasks***
            Example Keyword
                Add Watermark Image To PDF
                ...             image_path=approved.png
                ...             source_path=/tmp/sample.pdf
                ...             output_path=output/output.pdf

        **Python**

        .. code-block:: python

            from RPA.PDF import PDF

            pdf = PDF()

            def example_keyword():
                pdf.add_watermark_image_to_pdf(
                    image_path="approved.png"
                    source_path="/tmp/sample.pdf"
                    output_path="output/output.pdf"
                )

        :param image_path: filepath to image file to add into PDF
        :param source: filepath to source, if not given add image to currently
            active PDF
        :param output_path: filepath of target PDF
        :param coverage: how the watermark image should be scaled on page,
         defaults to 0.2
        """
        # Ensure an active input PDF.
        self.switch_to_pdf(source_path)
        input_reader = self.active_pdf_document.reader

        # Set image boundaries.
        mediabox = input_reader.getPage(0).mediaBox
        img_obj = Image.open(image_path)
        max_width = int(float(mediabox.getWidth()) * coverage)
        max_height = int(float(mediabox.getHeight()) * coverage)
        img_width, img_height = self.fit_dimensions_to_box(
            *img_obj.size, max_width, max_height)

        # Put the image on the first page of a temporary PDF file, so we can merge this
        #  PDF formatted image page with every single page of the targeted PDF.
        # NOTE(cmin764): Keep the watermark image PDF reader open along the entire
        #  process, so the final PDF gets rendered correctly)
        with tempfile.TemporaryFile(suffix=".pdf") as temp_img_pdf:
            # Save image in temporary PDF using FPDF.
            pdf = FPDF()
            pdf.add_page()
            pdf.image(name=image_path, x=40, y=60, w=img_width, h=img_height)
            pdf.output(name=temp_img_pdf)

            # Get image page from temporary PDF using PyPDF2. (compatible with the
            # writer)
            img_pdf_reader = PyPDF2.PdfFileReader(temp_img_pdf)
            watermark_page = img_pdf_reader.getPage(0)

            # Write the merged pages of source PDF into the destination one.
            output_writer = PyPDF2.PdfFileWriter()
            for idx in range(input_reader.getNumPages()):
                page = input_reader.getPage(idx)
                page.mergePage(watermark_page)
                output_writer.addPage(page)

            # Since the input PDF can be the same with the output, make sure we close
            #  the input stream after writing into an auxiliary buffer. (if the input
            #  stream is closed before writing, then the writing is incomplete; and we
            #  can't read and write at the same time into the same file, that's why we
            #  use an auxiliary buffer)
            output_buffer = io.BytesIO()
            output_writer.write(output_buffer)
            self.active_pdf_document.close()
            output_path = self.resolve_output(output_path)
            with open(output_path, "wb") as output_stream:
                output_stream.write(output_buffer.getvalue())
コード例 #4
0
ファイル: PDFmaker.py プロジェクト: tombush0/OSPadmin
def makePDF(printed_values, pdf_save_path):

    report_no = printed_values[0]

    # printing parameters
    # enable generalization
    # currenty set to printing on A4 format (210x297 mm)
    W = 190
    H = 278
    f_size = 5  # font size
    c_height = 0.02 * H  # cell height

    rep = FPDF()
    rep.add_page()

    if find_font_file('segoeui.ttf') != []:
        rep.add_font('Segoe', '', find_font_file('segoeui.ttf')[0], uni=True)
        rep.add_font('Segoe', 'B', find_font_file('segoeuib.ttf')[0], uni=True)
        f_type = "Segoe"  # font type
    if find_font_file('arial.ttf') != []:
        rep.add_font('Arial', '', find_font_file('arial.ttf')[0], uni=True)
        rep.add_font('Arial', 'B', find_font_file('arialbd.ttf')[0], uni=True)
        f_type = "Arial"  # font type
    if find_font_file('DejaVuSans.ttf') != []:
        rep.add_font('DejaVu',
                     '',
                     find_font_file('DejaVuSans.ttf')[0],
                     uni=True)
        rep.add_font('DejaVu',
                     'B',
                     find_font_file('DejaVuSans-Bold.ttf')[0],
                     uni=True)
        f_type = "DejaVu"  # font type

    rep.set_font(f_type, 'B', size=5 * f_size)
    rep.cell(0.8 * W,
             2.5 * c_height,
             txt="OPIS ZDARZENIA",
             align="C",
             border=1,
             ln=0)
    rep.set_font(f_type, 'B', size=3 * f_size)
    rep.cell(0.2 * W,
             2.5 * c_height,
             txt="  LP.   " + str(report_no),
             align="L",
             border=1,
             ln=1)

    rep.ln(c_height)

    rep.set_font(f_type, 'B', size=2 * f_size)
    left_margin = rep.get_x()
    ybefore = rep.get_y()
    rep.multi_cell(0.33 * W,
                   1.2 * c_height,
                   txt=" DATA WYJAZDU:\n " + printed_values[1],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.33 + left_margin, ybefore)
    rep.multi_cell(0.33 * W,
                   1.2 * c_height,
                   txt=" GODZINA WYJAZDU:\n " + printed_values[2],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.66 + left_margin, ybefore)
    rep.multi_cell(0.34 * W,
                   1.2 * c_height,
                   txt=" NA MIEJSCU: \n " + printed_values[3],
                   align="L",
                   border=1)

    ybefore = rep.get_y()
    left_margin = rep.get_x()
    rep.multi_cell(0.33 * W,
                   2 * c_height,
                   txt=" MIEJSCE ZDARZENIA:\n " + printed_values[4],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.33 + left_margin, ybefore)
    rep.multi_cell(0.67 * W,
                   2 * c_height,
                   txt=" RODZAJ ZDARZENIA:\n " + printed_values[5],
                   align="L",
                   border=1)

    rep.ln(c_height)

    ybefore = rep.get_y()
    rep.multi_cell(0.33 * W,
                   1.2 * c_height,
                   txt=" DOWODCA SEKCJI:\n " + printed_values[6],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.33 + left_margin, ybefore)
    rep.multi_cell(0.33 * W,
                   1.2 * c_height,
                   txt=" DOWODCA AKCJI:\n " + printed_values[7],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.66 + left_margin, ybefore)
    rep.multi_cell(0.34 * W,
                   1.2 * c_height,
                   txt=" KIEROWCA: \n " + printed_values[8],
                   align="L",
                   border=1)

    ybefore = rep.get_y()
    rep.multi_cell(0.33 * W,
                   2 * c_height,
                   txt=" SPRAWCA:\n " + printed_values[9],
                   align="L",
                   border=1)
    rep.set_xy(left_margin, ybefore + 4 * c_height)
    rep.multi_cell(0.33 * W,
                   2 * c_height,
                   txt=" POSZKODOWANY:\n " + printed_values[10],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.33 + left_margin, ybefore)
    rep.multi_cell(0.67 * W,
                   4 * c_height,
                   txt=" SEKCJA:\n " + printed_values[11],
                   align="L",
                   border=1)

    rep.ln(c_height)

    rep.multi_cell(1 * W,
                   5 * c_height,
                   txt=" SZCZEGOLY ZDARZENIA:\n " + printed_values[12],
                   align="L",
                   border=1)

    rep.ln(c_height)

    ybefore = rep.get_y()
    rep.multi_cell(0.2 * W,
                   2 * c_height,
                   txt=" DATA POWROTU:\n " + printed_values[13],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.2 + left_margin, ybefore)
    rep.multi_cell(0.35 * W,
                   2 * c_height,
                   txt=" GODZ. ZAKONCZ.:    " + printed_values[14],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.2 + left_margin, ybefore + 2 * c_height)
    rep.multi_cell(0.35 * W,
                   2 * c_height,
                   txt=" GODZ. W REMIZIE.:   " + printed_values[15],
                   align="L",
                   border=1)
    rep.set_xy(W * 0.55 + left_margin, ybefore)
    rep.multi_cell(0.2 * W,
                   2 * c_height,
                   txt=" STAN LICZNIKA: \n " + printed_values[16],
                   align="C",
                   border=1)
    rep.set_xy(W * 0.75 + left_margin, ybefore)
    rep.multi_cell(0.25 * W,
                   2 * c_height,
                   txt=" KM. DO MIEJSCA ZD: \n " + printed_values[17],
                   align="C",
                   border=1)

    modDate = str(printed_values[18])[11:].replace(":", "")
    path = pdf_save_path + "/" + str(report_no) + "_" + str(
        printed_values[4]) + "_" + str(
            printed_values[1]) + "_" + modDate + ".pdf"
    rep.output(path)
コード例 #5
0
def make_bulletin():
    global y_appr
    global p
    p = FPDF('L', 'cm', 'A4')
    p.set_margins(
        marge, marge,
        marge)  # marges (pas de marge_bottom, mais ligne suivante aide)
    p.set_auto_page_break(
        False
    )  # empêcher les page break automatiques (donc ~ pas de marge en bas)
    p.add_page()

    #################################
    #  Logo + coordonnées du lycée  #
    #################################

    # Logo
    p.image('logo_lycée.png', marge, marge, w=w_logo)

    # Adresse
    p.set_font('Arial', '', 7)
    p.set_xy(w_logo + marge, marge)
    adr_lycee = "Académie de Créteil\nLycée Polyvalent Louise Michel\n7 Rue Pierre Marie Derrien\n94500 Champigny-sur-Marne\nTél. : 01.48.82.07.35"
    p.multi_cell(w_adr_lycee, h_cell - 0.1, adr_lycee, aff_bord, 'C', False)

    ###############################
    #  En-tête période + vie sco  #
    ###############################

    # Titres en gras: bulletin de période, vie scolaire
    p.set_font('Arial', 'B', 9)
    p.cell(w_periode, h_cell, "Bulletin du " + periode.lower(), aff_bord, 0,
           'C')
    p.cell(0, h_cell, "Vie scolaire", aff_bord, 0, 'C')

    # ligne horizontale
    x0 = marge + w_logo + w_adr_lycee
    x1 = width - marge
    y0 = marge + h_cell
    y1 = marge + h_cell
    p.line(x0, y0, x1, y1)

    # Infos de la classe
    p.set_font('Arial', '', 9)
    p.set_xy(x0, y0)  # on commence au début de la ligne
    p.cell(w_infos_classe, h_cell, 'Année scolaire: %s' % annee_sco, aff_bord,
           2, 'L')
    p.cell(w_infos_classe, h_cell, 'Classe: %s' % classe, aff_bord, 2, 'L')

    # PP: on peut en avoir plusieurs. Tri des noms et affichage correct.
    if len(prof_principal) == 1:
        PP = prof_principal[0]
    else:
        prof_principal.sort(key=lambda x: x.split(" ")[-1]
                            )  # on trie par nom sans considérer M/Mme
        PP = ''
        for i in range(len(prof_principal)):
            PP += prof_principal[i]
            PP += '\n       '
    p.multi_cell(w_infos_classe, h_cell, 'PP: %s' % PP, aff_bord, 'L')

    p.set_xy(x0 + w_infos_classe, y0)

    # prénom élève
    p.set_font('Arial', 'B', 9)
    p.cell(w_periode - w_infos_classe, h_cell, nom, aff_bord, 2, 'L')

    # Infos persos élève (TODO)
    p.set_font('Arial', '', 9)
    if genre == 'M' or genre == 'I':
        infos_perso = "Né le %s\nINE : %s" % (date_naissance, INE)
    if genre == 'F':
        infos_perso = "Née le %s\nINE : %s" % (date_naissance, INE)
    p.multi_cell(w_periode - w_infos_classe, h_cell, infos_perso, aff_bord,
                 'L')

    # Absences + appréciation vie sco
    # TODO: Appréciation vie scolaire
    p.set_xy(p.get_x(), p.get_y() - h_cell)
    texte_viesco = "Absences : %s demi-journée" % abs
    if int(abs) > 1:
        texte_viesco += "s"
    texte_viesco += " dont %s non-réglée" % abs_non_reglees
    if int(abs_non_reglees) > 1:
        texte_viesco += "s"
    texte_viesco += ".\nAppréciation : %s" % appr_vie_sco

    p.multi_cell(0, h_cell, texte_viesco, aff_bord, 'L')

    ########################
    #  Bloc appréciations  #
    ########################

    # NOTE: On veut faire apparaître les appréciations dans un ordre précis
    # hardcodé dans ordre_matieres

    # Matières du tronc commun
    i = 0
    for matiere in ordre_matieres:
        infos_appr = (matiere, moyennes[matiere].get('prof', ''),
                      moyennes[matiere].get('appreciation', ''))
        ligne_appreciation(x_appr, y_appr + i * height_appr, infos_appr)
        i += 1

    # On vérifie s'il n'y a pas d'option à ajouter
    for m in moyennes:
        if m == "Vie scolaire":
            continue  # L'appréciation vie sco n'apparaît pas ici
        if m not in ordre_matieres:
            infos_appr = (m, moyennes[m].get('prof', ''),
                          moyennes[m].get('appreciation', ''))
            ligne_appreciation(x_appr, y_appr + i * height_appr, infos_appr)
            i += 1

    ###################
    #  Bloc moyennes  #
    ###################

    # Vu qu'on a un template fixe, on va se contenter d'appeler des fonctions bien définies
    # On construit des lignes de 3 blocs, dans l'ordre souhaité des matières.

    # Ligne FR/EN/ES
    temp_dict = {
        ordre_matieres[i]: moyennes[ordre_matieres[i]]['moyennes']
        for i in range(0, 3)
    }
    ligne_eval(x_bloc, y_bloc, temp_dict)

    # Ligne HG/EMC/SES
    temp_dict = {
        ordre_matieres[i]: moyennes[ordre_matieres[i]]['moyennes']
        for i in range(3, 6)
    }
    ligne_eval(x_bloc, y_bloc + 7 * h_cell + h_offset_blocs, temp_dict)

    # Ligne Maths/PC/SVT
    temp_dict = {
        ordre_matieres[i]: moyennes[ordre_matieres[i]]['moyennes']
        for i in range(6, 9)
    }
    ligne_eval(x_bloc, y_bloc + 2 * (7 * h_cell + h_offset_blocs), temp_dict)

    # Selon la maquette, 2 situations:
    # - Soit on a deux blocs sur la dernière ligne (EPS et SNT)
    # - Soit on a trois blocs sur la dernière ligne (EPS, SNT, option)
    temp_dict = {
        ordre_matieres[i]: moyennes[ordre_matieres[i]]['moyennes']
        for i in range(9, 11)
    }
    # On cherche l'option
    skip = 1  # Par défaut, pas d'option donc 1 bloc masqué
    for m in moyennes:
        if m == 'Vie scolaire':  # on ignore la moyenne de vie sco (mais elle existe pour pouvoir mettre une appr à l'élève)
            continue
        if m not in ordre_matieres:  # Si on trouve une option (qui n'est pas dans l'ordre de base)
            # On l'ajoute à temp_dict pour que les moyennes sortent
            temp_dict[m] = moyennes[m]['moyennes']
            skip = 0  # ... et on ne saute pas le dernier bloc

    ligne_eval(x_bloc,
               y_bloc + 3 * (7 * h_cell + h_offset_blocs),
               temp_dict,
               skip=skip)

    # Légende des couleurs sous les blocs
    legende(x_bloc, y_bloc + 4 * (7 * h_cell + h_offset_blocs))

    #############################
    #  Appr. générale/mentions  #
    #############################

    # Appréciation de la direction/PP
    p.set_font('Arial', 'B', 8)
    p.set_xy(x_appr_dir, y_appr_dir)
    p.cell(w_prof, h_cell, 'Appréciation globale :', aff_bord, 0)
    p.set_font('Arial', '', 8)
    p.multi_cell(0, h_cell, appr_dir, aff_bord, 'L')

    # Mention
    # TODO: Question à poser: "mention:" apparaît toujours même si pas de mention ?
    p.set_font('Arial', 'B', 8)
    p.set_xy(x_appr_dir, y_appr_dir + 5 * h_cell)
    p.cell(w_prof / 2, h_cell, 'Mention :', aff_bord, 0)
    p.set_font('Arial', '', 8)
    p.cell(0, h_cell, mention, aff_bord, 0)

    ####################
    #  Signature chef  #
    ####################
    # Mention "le chef d'établissement" + signature
    p.set_xy(x_chef, y_chef)
    p.cell(w_prof, h_cell, "Le chef d'établissement", aff_bord, 0)
    #p.image(signature,p.get_x(),p.get_y()-0.5*h_cell, h=h_signature)

    #####################
    # Adresse du parent #
    #####################
    p.add_page(orientation='P', format="A4")
    p.set_xy(x_parent, y_parent)
    p.set_font('Arial', 'B', 12)
    p.multi_cell(0, h_cell * 1.25, parent_nom, aff_bord, 'L')
    # Le pointeur a besoin de sauter 1 ou 2 lignes
    # selon le nombre de noms affichés (présence de \n si 2 noms)
    if '\n' in parent_nom:
        p.set_xy(x_parent, y_parent + 2.5 * h_cell)
    else:
        p.set_xy(x_parent, y_parent + 1.25 * h_cell)
    p.set_font('Arial', '', 12)
    p.multi_cell(0, h_cell * 1.25, parent_adresse, aff_bord, 'L')

    ### Création du fichier
    fname = nom + str(numero_bulletin)
    try:
        p.output('bulletin/%s.pdf' % fname, 'F')
    except FileNotFoundError as e:
        os.mkdir("bulletin")
        p.output('bulletin/%s.pdf' % fname, 'F')
コード例 #6
0
def create_pdf(input):

    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.add_page()

    pdf.add_font('DGUVMeta-Normal', '', 'DGUVMeta-Normal.ttf', uni=True)
    pdf.add_font('DGUVMeta-Bold', '', 'DGUVMeta-Bold.ttf', uni=True)
    pdf.add_font('DGUVMeta-NormalItalic',
                 '',
                 'DGUVMeta-NormalItalic.ttf',
                 uni=True)

    pdf.image("newtemplate3_seite1.jpg", x=-4, y=-8, w=217, h=313)

    data = {}
    input = input.get("data")

    # Kopffragen

    data["arbeitsstelle"] = input.get('#/properties/arbeitsstelle-arbeitsort')
    data["datum_uhrzeit"] = input.get('#/properties/datum-und-uhrzeit')
    data["person_anlageverantwortlichkeit"] = input.get(
        '#/properties/person-in-der-rolle-des-anlagenverantwortlichen')
    data["person_arbeitsverantwortlichkeit"] = input.get(
        '#/properties/person-in-der-rolle-des-arbeitsverantwortlichen')
    data["person_arbeitsausfuehrung"] = input.get(
        '#/properties/arbeitsausfuhrende-person')

    if 'gegen elektrischen Schlag' in input.get(
            '#/properties/zusatzliche-personliche-schutzausrustung-bei-der-1'):
        data["zusaetzliche_schutzausrüstung_elektrischerschlag"] = "x"
    else:
        data["zusaetzliche_schutzausrüstung_elektrischerschlag"] = ""

    if 'gegen Störlichtbogen' in input.get(
            '#/properties/zusatzliche-personliche-schutzausrustung-bei-der-1'):
        data["zusaetzliche_schutzausrüstung_stoerlichtbogen"] = "x"
    else:
        data["zusaetzliche_schutzausrüstung_stoerlichtbogen"] = ""

    if input.get(
            '#/properties/stehen-andere-anlagenteile-weiterhin-unter') == "ja":
        data["abgrenzung_arbeitsbereich_ja"] = "x"
    else:
        data["abgrenzung_arbeitsbereich_ja"] = ""

    if input.get('#/properties/stehen-andere-anlagenteile-weiterhin-unter'
                 ) == "nein":
        data["abgrenzung_arbeitsbereich_nein"] = "x"
    else:
        data["abgrenzung_arbeitsbereich_nein"] = ""

    # 1

    data["art_der_freischaltung"] = input.get(
        '#/properties/edia35d5a284cfd441c8e85d75491d7b2b0')

    if data["art_der_freischaltung"] == "NH-Sicherungen":
        data["ausloesestrom"] = input.get(
            '#/properties/edi6ac532fc3bb3466bb37bf9fa0fe69723')
    elif data["art_der_freischaltung"] == "NH-Lastschaltleiste":
        data["ausloesestrom"] = input.get(
            '#/properties/edi91a3dd70963646b1a1b97d61c7e4a82a')
    elif data["art_der_freischaltung"] == "Leistungsschalter":
        data["ausloesestrom"] = input.get(
            '#/properties/edia0d7558f2b2742cc93296ecbdaafb6ea')
    elif data["art_der_freischaltung"] == "Trenner geöffnet":
        data["ausloesestrom"] = input.get(
            '#/properties/edi58b116e71fed42d08e9d13d7ccdcd1d7')
    else:
        data["ausloesestrom"] = "/"

    data["ort_der_freischaltung"] = input.get(
        '#/properties/edi5a7f273428f74de489972b6913c66075')

    if data["ort_der_freischaltung"] == "Trafostation":
        data["ort_nroderbezeichnung"] = input.get(
            '#/properties/edi3d04e27bf3ea4b699896ebb282d85cfa')
    elif data["ort_der_freischaltung"] == "Umspannwerk/-anlage":
        data["ort_nroderbezeichnung"] = input.get(
            '#/properties/edicd578854837541c8b00db113e7f28a67')
    elif data["ort_der_freischaltung"] == "Station Niederspannung":
        data["ort_nroderbezeichnung"] = input.get(
            '#/properties/edi51afae6421aa4aa593e6280ae0e87f01')
    elif data["ort_der_freischaltung"] == "Schaltfeld Niederspannung":
        data["ort_nroderbezeichnung"] = input.get(
            '#/properties/edi3859034e0e724ceabb64955eb53fc3d4')
    else:
        data["ort_nroderbezeichnung"] = "/"

    # 2

    data["sicherungsart"] = input.get(
        '#/properties/edicc623be9685e4de8b5963d52533abae5')
    data["schalten_verboten"] = input.get(
        '#/properties/edibc8dd2af0a9446eca50e69cf66ea27c5')

    # 3

    data["spannungspruefer"] = input.get(
        '#/properties/edid0e606c47a8942f3b34084387a472765')

    # 4

    data["euk_wo_eingebaut"] = input.get(
        '#/properties/edi680c885614ec477a8c7c808dfceee698')
    if data["euk_wo_eingebaut"] == "nicht geerdet und kurzgeschlossen":
        data["geerdet_begruendung"] = input.get(
            '#/properties/edi17f2674f513b4061b60db0e7a23e3ab5')
    else:
        data["geerdet_begruendung"] = ""

    # 5

    data["ziel_der_abdeckung"] = input.get(
        '#/properties/edi6aaa1d808e73457eb35f948454814269')

    if data["ziel_der_abdeckung"] == "teilweiser Berührungsschutz":
        data["art_der_abdeckung"] = ', '.join(
            input.get('#/properties/edi2b1edc26849c4438ac6f2d9222d66f80'))
    elif data["ziel_der_abdeckung"] == "vollständiger Berührungsschutz":
        data["art_der_abdeckung"] = ', '.join(
            input.get('#/properties/edib0c92d29081b4298820b32cf6e5764d7'))
    elif data["ziel_der_abdeckung"] == "Abdeckung nicht notwendig":
        data["art_der_abdeckung"] = input.get(
            '#/properties/edieb5d81daecfd41e686b10c4cda28eeac')
        if data.get("art_der_abdeckung") == "die Entfernung beträgt ca.:":
            data["entfernung"] = input.get(
                '#/properties/edi1da040c5a8984862849fb05a585069a6')
    else:
        data["art_der_abdeckung"] = ""

    # Title

    pdf.set_font('DGUVMeta-Bold', '', 20)
    pdf.set_text_color(0, 73, 148)
    pdf.set_xy(12.7, 58.5)
    pdf.cell(0, 0, 'Arbeiten an Schaltanlagen')

    pdf.set_font('DGUVMeta-Bold', '', 20)
    pdf.set_text_color(0, 73, 148)
    pdf.set_xy(12.7, 68)
    pdf.cell(0, 0, 'der Niederspannung')

    pdf.set_font('DGUVMeta-Bold', '', 14)
    pdf.set_text_color(0, 140, 142)
    pdf.set_xy(12.7, 83.5)
    pdf.cell(0, 0, 'Industrie')

    # Kopffragen

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 107)
    pdf.set_text_color(0, 0, 0)
    pdf.cell(0, 0, data.get("arbeitsstelle"))

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 126)
    pdf.cell(0, 0, data.get("datum_uhrzeit"))

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 145)
    pdf.cell(0, 0, data.get("person_anlageverantwortlichkeit"))

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 164)
    pdf.cell(0, 0, data.get("person_arbeitsverantwortlichkeit"))

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 183)
    pdf.cell(0, 0, data.get("person_arbeitsausfuehrung"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_xy(20, 208.5)
    pdf.cell(0, 0, "gegen elektrischen Schlag")

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(14.3, 208.3)
    pdf.cell(0, 0,
             data.get("zusaetzliche_schutzausrüstung_elektrischerschlag"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_xy(78, 208.5)
    pdf.cell(0, 0, "gegen Störlichbogen")

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(72.2, 208.3)
    pdf.cell(0, 0, data.get("zusaetzliche_schutzausrüstung_stoerlichtbogen"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_xy(20, 232)
    pdf.cell(0, 0, "ja")

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(14.4, 231.6)
    pdf.cell(0, 0, data.get("abgrenzung_arbeitsbereich_ja"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_xy(78, 232)
    pdf.cell(0, 0, "nein")

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(72.2, 231.6)
    pdf.cell(0, 0, data.get("abgrenzung_arbeitsbereich_nein"))

    #Adding new page

    pdf.add_page()
    pdf.image("newtemplate1_seite2.jpg", x=-4, y=-8, w=217, h=313)

    # 1 Freigeschaltet

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35, 31, 32)
    pdf.set_xy(12.7, 29.2)
    pdf.cell(0, 0, 'Wie erfolgte die Freischaltung?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 34.2)
    pdf.cell(0, 0, data.get("art_der_freischaltung"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 39.2)
    pdf.cell(0, 0, 'Auslösestrom: %s A' % data.get("ausloesestrom"))

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35, 31, 32)
    pdf.set_xy(12.7, 50)
    pdf.cell(0, 0, 'Wo erfolgte die Freischaltung?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 55)
    pdf.cell(0, 0, data.get("ort_der_freischaltung"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 60)
    pdf.cell(0, 0,
             'Nr. oder Bezeichnung: %s' % data.get("ort_nroderbezeichnung"))

    # 2 Gegen Wiedereinschalten gesichert

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35, 31, 32)
    pdf.set_xy(12.7, 77.5)
    pdf.cell(0, 0, 'Wie wurde gesichert?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 82.5)
    pdf.cell(0, 0, data.get("sicherungsart"))

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35, 31, 32)
    pdf.set_xy(12.7, 89)
    pdf.cell(0, 0,
             'Wurde ein Schild "Schalten verboten" zusätzlich angebracht?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 94)
    pdf.cell(0, 0, data.get("schalten_verboten"))

    # 3 Spannungsfreiheit allpolig festgestellt an der Arbeitsstelle

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35, 31, 32)
    pdf.set_xy(12.7, 136)
    pdf.cell(0, 0, 'Zweipoliger Spannungsprüfer:')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 141)
    pdf.cell(0, 0, data.get("spannungspruefer"))

    # 4 Geerdet und kurzgeschlossen

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35, 31, 32)
    pdf.set_xy(12.7, 189)
    pdf.cell(0, 0, 'Wo wurde die EuK-Vorrichtung eingebaut?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 194)
    pdf.cell(0, 0, data.get("euk_wo_eingebaut"))

    if data["euk_wo_eingebaut"] == "nicht geerdet und kurzgeschlossen":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 200.5)
        pdf.cell(0, 0, 'Begründung:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 205.5)
        pdf.cell(0, 0, data.get("geerdet_begruendung"))

    # 5 Mit der Abdeckung soll erreicht werden

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35, 31, 32)
    pdf.set_xy(12.7, 235)
    pdf.cell(0, 0, 'Mit der Abdeckung soll erreicht werden:')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0, 0, 0)
    pdf.set_xy(12.7, 240)
    pdf.cell(0, 0, data.get("ziel_der_abdeckung"))

    if data["ziel_der_abdeckung"] == "teilweiser Berührungsschutz":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 246.5)
        pdf.cell(0, 0, 'Art der Abdeckung:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 251.5)
        pdf.cell(0, 0, data.get("art_der_abdeckung"))
    elif data["ziel_der_abdeckung"] == "vollständiger Berührungsschutz":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 246.5)
        pdf.cell(0, 0, 'Art der Abdeckung:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 251.5)
        pdf.cell(0, 0, data.get("art_der_abdeckung"))
    elif data["ziel_der_abdeckung"] == "Abdeckung nicht notwendig":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 246.5)
        pdf.cell(0, 0, 'Keine Abdeckung angebracht, weil:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 251.5)
        pdf.cell(0, 0, data.get("art_der_abdeckung"))

        if data.get("art_der_abdeckung") == "die Entfernung beträgt ca.:":
            pdf.set_font('DGUVMeta-Normal', '', 10)
            pdf.set_text_color(35, 31, 32)
            pdf.set_xy(12.7, 256.5)
            pdf.cell(0, 0, str(data.get("entfernung") + " Meter"))

    pdf.output("s141.pdf", "F")
コード例 #7
0
 def __init__(self):
     self.pdf = FPDF(orientation='P', unit='mm', format='A4')
     self.pdf.add_page()
コード例 #8
0
ファイル: download.py プロジェクト: pchae97/examtool
def write_exam(
    response,
    exam,
    template_questions,
    student_questions,
    name_question,
    sid_question,
    dispatch,
    out=None,
    substitute_in_question_text=False,
):
    pdf = FPDF()
    pdf.add_page()

    pdf.set_font("Courier", size=16)
    pdf.multi_cell(200, 20, txt=exam, align="L")
    pdf.multi_cell(200, 20, txt=response.get(name_question, "NO NAME").encode("latin-1", "replace").decode("latin-1"), align="L")
    pdf.multi_cell(200, 20, txt=response.get(sid_question, "NO SID").encode("latin-1", "replace").decode("latin-1"), align="L")

    pdf.set_font("Courier", size=9)

    if out is None:
        def out(text):
            pdf.multi_cell(
                200, 5, txt=text.encode("latin-1", "replace").decode("latin-1"), align="L"
            )

    student_question_lookup = {q["id"]: q for q in student_questions}

    for question in template_questions:
        pdf.add_page()
        out("\nQUESTION")
        if substitute_in_question_text:
            question_for_text = student_question_lookup.get(question["id"], question)
        else:
            question_for_text = question
        for line in question_for_text["text"].split("\n"):
            out(line)

        out("\nANSWER")

        if question.get("type") in ["multiple_choice", "select_all"]:
            selected_options = response.get(question["id"], [])
            if question.get("type") == "multiple_choice" and not isinstance(
                selected_options, list
            ):
                selected_options = [selected_options]
            available_options = sorted(
                [(i, option["text"]) for i, option in enumerate(question["options"])]
            )
            if question["id"] not in student_question_lookup:
                student_options = sorted(
                    [
                        (option.get("index", i), option["text"])
                        for i, option in enumerate(question["options"])
                    ]
                )
            else:
                student_options = sorted(
                    [
                        (option.get("index", i), option["text"])
                        for i, option in enumerate(
                            student_question_lookup[question["id"]]["options"]
                        )
                    ]
                )

            available_options = [
                (*available_option, option)
                for available_option, (j, option) in zip(
                    available_options, student_options
                )
            ]

            available_options.sort(key=lambda x: x[1])

            for i, template, option in available_options:
                if option in selected_options:
                    template = template
                    out("[X] " + template)
                else:
                    out("[ ] " + template)
        else:
            for line in response.get(question["id"], "").split("\n"):
                out(line)

        out("\nAUTOGRADER")
        if question["id"] in student_question_lookup and question["id"] in response:
            out(grade(student_question_lookup[question["id"]], response, dispatch))
        elif question["id"] not in student_question_lookup:
            out("STUDENT DID NOT RECEIVE QUESTION")
        else:
            out("")

    return pdf
コード例 #9
0
sheet1.write(0, 0, "Images")
sheet1.write(0, 1, "Prediction")




#Reslut show window
fig=plt.figure()
i=1
j=0
test_img_counter=0


# Instantiation of inherited class
pdf = FPDF('P','mm',(100,100))
pdf.set_font('Times', '', 12)

image_names = [f for f in os.listdir(TEST_DIR) if os.path.splitext(f)[-1] == '.jpg']

for num,data in enumerate(test_data[:test_data_size]):
	#N:[1,0]
	#Y:[0,1]
	img_num=data[1]
	img_data=data[0]
	y=fig.add_subplot(3,4,num+1)
	orig=img_data
	data=img_data.reshape(IMG_SIZE,IMG_SIZE,1)

	model_out=model.predict([data])[0]
	if np.argmax(model_out)==1: str_label='Corrode'
コード例 #10
0
ファイル: Timekeeper.py プロジェクト: shoabbos/Projects
    def Print(self):
        if(self.ticket_number.get()):
            if(self.dictionarydata['flag']==0):
                DataBase.update(self.ticket_number.get(),self.memo.get(),self.remark.get('1.0','end'),self.date.get(),self.time.get(),self.shift.get(),self.dept_code.get())
                self.dictionarydata = DataBase.load(self.ticket_number.get())
                pdf = FPDF('P','mm','A5')
                pdf.add_page()
                pdf.set_xy(0, 0)
                pdf.set_font('arial', 'B', 10)
                pdf.cell(ln=0, h=5, align='C', w=0, txt="Century Rayon-Time Office", border=0)
                
                pdf.set_font('arial','',10)
                
                #printing ticket numbr
                pdf.set_xy(20,10)
                pdf.cell(ln=0, h=0, w=0, txt="Tkt No. : ", border=0)
                
                pdf.set_xy(60,10)
                pdf.cell(ln=0, h=0, w=0, txt=self.ticket_number.get(), border=0)
                
                
                # Printing full name in pdf
                pdf.set_xy(20,15)
                pdf.cell(ln=0, h=0, w=0, txt="Name : ", border=0)
                
                pdf.set_xy(60,15)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['full_name'] , border=0)
                
                # printing department in pdf
                pdf.set_xy(20,20)
                pdf.cell(ln=0, h=0, w=0, txt="Department :  ", border=0)
                
                pdf.set_xy(60,20)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['department'] , border=0)
                
                # printing department code
                pdf.set_xy(20,25)
                pdf.cell(ln=0, h=0, w=0, txt="Department code:  ", border=0)
                
                pdf.set_xy(60,25)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['department_code'] , border=0)
                
                
                #printing memo in pdf
                pdf.set_xy(20,30)
                pdf.cell(ln=0, h=0, w=0, txt="Memo : ", border=0)
                
                pdf.set_xy(60,30)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['reason_for_memo'] , border=0)
                
                # printing remark in pdf
                pdf.set_xy(20,35)
                pdf.cell(ln=0, h=0, w=0, txt="Remark : ", border=0)
                
                pdf.set_xy(60,35)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['remark'], border=0)
                
                #printing check in time
                pdf.set_xy(10,40)
                pdf.cell(ln=0, h=0, w=0, txt="Check in Time : ", border=0)
                
                pdf.set_xy(60,40)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['check_in'], border=0)
                
                # printing check in date
                pdf.set_xy(10,45)
                pdf.cell(ln=0, h=0, w=0, txt="Check in Date : ", border=0)
                
                pdf.set_xy(60,45)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['date_in'], border=0)
                
                #printing shift
                pdf.set_xy(20,50)
                pdf.cell(ln=0, h=0, w=0, txt="Shift : ", border=0)
                
                pdf.set_xy(60,50)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['shift'], border=0)
                
                
                #printing photo
                pdf.set_xy(20,55)
                pdf.cell(ln=0, h=0, w=0, txt="Photo : ", border=0)
                
                try:
                    pdf.image(self.path, 60, 55, 22,22)
                except Exception as e:
                    #print(e)
                    pdf.set_xy(60,55)
                    pdf.cell(ln=0, h=0, w=0, txt="Photo not available", border=0)
                
                pdf.set_xy(20,100)
                pdf.cell(ln=0, h=0, w=0, txt="Timekeeper: ", border=0)
                
                pdf.set_xy(60,100)
                pdf.cell(ln=0, h=0, w=0, txt=self.username.get(), border=0)
                
                pdf.line(20,90,50,90)
                
                pdf.set_xy(20,95)
                pdf.cell(ln=0, h=0, w=0, txt="sign of employee", border=0)
                
                pdf.line(60,90,100,90)
                pdf.set_xy(60,95)
                pdf.cell(ln=0, h=0, w=0, txt="DEPT. HEAD SIGN", border=0)
                
                # sign
                #pdf.set_font('arial', 'B', 10)

                
                try:
                    pdf.output('Timekeeper.pdf')
                except Exception:
                    tkinter.messagebox.showerror('','Please close the previous pdf file')
                else:
                    wb.open('timekeeper.pdf')
                    fp=open("D:/TimeKeeper_stuffs/Personal Database/Logs/"+str(self.td.date())+".txt",'a') 
                    data = ['5199',self.dictionarydata['date_in'],self.dictionarydata['check_in'],self.ticket_number.get(),'I']
                    fp.write('||'.join(data))
                    fp.write("\n")
                    fp.close()
            else:
                tkinter.messagebox.showwarning('','The print has already been generated')
        else:
            tkinter.messagebox.showwarning('','Enter Ticket number')
コード例 #11
0
ファイル: test.py プロジェクト: SaidShahAhmadi/PythonWorks
from openpyxl.styles import Font
import pyinputplus as pyip
from prettytable import PrettyTable
from prettytable import from_csv

# sheet_name = pyip.inputStr(
#     "Pleas type your Excel (CSV) Format file name to open table: ")
# with open(sheet_name, "r") as csv_file:
#     csv_reader = from_csv(csv_file)
#     print(csv_reader)

path = "/home/ubuntu/Desktop/Netlink/python/resheetr/images/"  # get the path of images

imagelist = listdir(path)  # get list of all images

pdf = FPDF('P', 'mm', 'A4')  # create an A4-size pdf document

x, y, w, h = 0, 0, 200, 250

sheet_name = pyip.inputStr(
    "Pleas type your Excel (CSV) Format file name to open table: ")

with open(sheet_name, "r") as csv_file:
    csv_reader = csv_file
    records = csv_reader
    images = []
    for record in records:
        print(record)
        images.append(record)

        for image in imagelist:
コード例 #12
0
ファイル: Timekeeper.py プロジェクト: shoabbos/Projects
    def PrintData(self):
        self.dictionarydata = NewDataBase.LoadData(self.ticket_number.get())
        pdf = FPDF('P','mm','A5')
        pdf.add_page()
        pdf.set_xy(0, 0)
        pdf.set_font('arial', 'B', 10)
        pdf.cell(ln=0, h=5, align='C', w=0, txt="Century Rayon", border=0)
                
        pdf.set_font('arial','',10)
                
                #printing ticket numbr
        pdf.set_xy(20,10)
        pdf.cell(ln=0, h=0, w=0, txt="Tkt No. : ", border=0)
                
        pdf.set_xy(60,10)
        pdf.cell(ln=0, h=0, w=0, txt=self.ticket_number.get(), border=0)
                
                
                # Printing full name in pdf
        pdf.set_xy(20,15)
        pdf.cell(ln=0, h=0, w=0, txt="Name : ", border=0)
                
        pdf.set_xy(60,15)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['full_name'] , border=0)
                
                # printing department in pdf
        pdf.set_xy(20,20)
        pdf.cell(ln=0, h=0, w=0, txt="Department :  ", border=0)
                
        pdf.set_xy(60,20)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['department'] , border=0)
                
                # printing department code
        pdf.set_xy(20,25)
        pdf.cell(ln=0, h=0, w=0, txt="Memo:  ", border=0)
                
        pdf.set_xy(60,25)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['reason_for_memo'] , border=0)
                
        pdf.set_xy(10,30)
        pdf.cell(ln=0, h=0, w=0, txt="Check in Time : ", border=0)
                
        pdf.set_xy(60,30)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['check_in'], border=0)
                
                # printing check in date
        pdf.set_xy(10,35)
        pdf.cell(ln=0, h=0, w=0, txt="Check in Date : ", border=0)
                
        pdf.set_xy(60,35)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['date_in'], border=0)
                
                #printing shift
        pdf.set_xy(20,40)
        pdf.cell(ln=0, h=0, w=0, txt="Shift : ", border=0)
                
        pdf.set_xy(60,40)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['shift'], border=0)

        #pdf.set_font('arial', 'B', 10)
		
        pdf.line(20,55,50,55)
        pdf.set_xy(20,60)
        pdf.cell(ln=0, h=0, w=0, txt="sign of employee", border=0)
        
        pdf.line(60,55,100,55)
        pdf.set_xy(60,60)
        pdf.cell(ln=0, h=0, w=0, txt="Dept Head SIGN", border=0)
        
        pdf.set_xy(20,70)
        pdf.cell(ln=0, h=0, w=0, txt="Timekeeper: ", border=0)
                
        pdf.set_xy(60,70)
        pdf.cell(ln=0, h=0, w=0, txt=self.username.get(), border=0)
                
        try:
            pdf.output('Timekeeper.pdf')
        except Exception:
            tkinter.messagebox.showerror('','Please close the previous pdf file')
        else:
            wb.open('timekeeper.pdf')
コード例 #13
0
def generate_pdf(id, message):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    pdf.cell(40, 10, message)
    pdf.output(str(id) + '.pdf', 'F')
コード例 #14
0
def mkpdffilenote():
    from fpdf import FPDF
    import os
    import os.path
    try:
        # obtain matter name
        m = request.form.get("mname")
        mname = m.upper()
        # obtain date
        date = now
    except:
        print("failed to set matter name and date")
    try:
        # obtain attendance type
        xax = ""
        for el in attendtype:
            if request.form.get(el) == "on":
                xax += el + ", "
        tp = xax
        type = tp.upper()
    except:
        print("failed to set attend type")
    try:
        # obtain attendance with
        xab = ""
        for el in attendupon:
            if request.form.get(el) == "on":
                xab += el + ", "
        attendon = xab.upper()
        # obtain text of file note
    except:
        print("failed to set attendance with")
    try:
        notes = request.form.get("text")
        # create the pdf using the now set variables
    except:
        print("failed to set notes for pdf")
    try:
        pdf = FPDF()
        pdf.add_page()
        pdf.set_auto_page_break(True, 2)
        pdf.set_font("Arial", size = 20)
        pdf.cell(200,10, txt = "FILE NOTE", ln = 1, align = 'C')
        pdf.set_font("Arial", size = 12)
        pdf.cell(200,10, txt = f"Matter name:    {mname}", ln = 1, align = 'L')
        pdf.cell(200,10, txt = f"Date:             {date}", ln = 1, align = 'l')
        pdf.cell(200,10, txt = f"Attendance Type: {type}", ln = 1, align = 'l')
        pdf.cell(200,10, txt = f"Attendance Upon: {attendon}, ln = 1, align = 'l")
        pdf.cell(200, 10, txt="Author: Harry McDonald", ln=1)
        pdf.cell(200,10, txt = "NOTES:", ln = 1)
        pdf.multi_cell(200,10, txt = notes, align = 'l')
        pdf.ln()
        # save the pdf under the right file name
        for k in range(1,400):
            if not os.path.exists(f"File Note {mname} {date}.pdf"):
                pdf.output(f'File Note {mname} {date}.pdf')
            elif not os.path.exists(f"File Note {mname} {date}({k}).pdf"):
                pdf.output(f"File Note {mname} {date}({k}).pdf")
                break
        # todo use os.mkdir or shutil move to get file notes into folders sorted by matter

        # if you want to save as word documents instead
        # d = docx.Document()
        # d.add_paragraph(f"FILE NOTE\n{mname}\n{date}\n{type}\n{notes}")
        # for k in range(1,400):
        #     if not os.path.exists(f"Test{mname}.docx"):
        #         d.save(f'Test{mname}.docx')
        #     elif not os.path.exists(f"Test{mname}{k}.docx"):
        #         d.save(f'Test{mname}{k}.docx')
        #         break
    except:
        print(f"Failed to save the file note as a PDF")
コード例 #15
0
def create_simple_pdf(name, text):
    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    pdf.cell(200, 10, txt=text, ln=1, align="C")
    pdf.output(basedir + '/static/' + name + '.pdf', dest='F')
コード例 #16
0
def generate_pdf(name, end_date, pr_days):
    #initialise web driver to export fraphs to png
    options = FirefoxOptions()
    web_driver = Firefox(
        executable_path=
        'C:/Users/ABachleda-Baca/AppData/Local/salabs_/WebDriverManager/gecko/v0.27.0/geckodriver-v0.27.0-win64/geckodriver.exe',
        options=options)
    #Define period to be considered using time_period function
    week_times = time_period_extract(days=pr_days, end_date=end_date)

    #Import data from json files in known directory using json_import function and save all recorded alerts#in events array
    path = 'output/Building1/'
    events = import_events_from_json(week_times, path)
    #transform events from json file to list of dictionaries
    total_list = []
    if events:
        total_list = extract_alerts_from_events(events)

    #extract the timestamps for daily energy usage
    if total_list:
        timestamp_daily_energy_gen = []
        energy_daily_modelled_dc = []
        energy_daily_gen_ac = []
    for i in total_list[-1]['daily_energy']:
        i = total_list[-1]['daily_energy'].index(i)
        timestamp_daily_energy_gen.append(
            (total_list[-1]['daily_energy'][i][0])[:10])
        energy_daily_modelled_dc.append(total_list[-1]['daily_energy'][i][1])
        energy_daily_gen_ac.append(total_list[-1]['daily_energy'][i][2])

    #Draw graph Daily energy generation
    #bokeh plot generation mix and DH performance indicator

    #draw a graph
    if not os.path.exists('output/' + name + '/charts/DCvsAC'):
        os.makedirs('output/' + name + '/charts/DCvsAC', mode=0o777)
    output_file('output/' + name + '/charts/DCvsAC/energy_output' +
                end_date[:10] + '.html')
    data = {
        'timestamps': timestamp_daily_energy_gen,
        'energy_DC_modelled': energy_daily_modelled_dc,
        'energy_ac_generated': energy_daily_gen_ac
    }

    source = ColumnDataSource(data=data)
    p = figure(x_range=timestamp_daily_energy_gen,
               plot_width=700,
               plot_height=600,
               title='Daily Energy Output',
               toolbar_location=None,
               tools="")
    p.title.text_font_size = '15pt'
    p.xaxis.axis_label_text_font_size = "15pt"
    p.yaxis.axis_label_text_font_size = "15pt"
    p.yaxis.major_label_text_font_size = '15pt'
    p.xaxis.major_label_text_font_size = '12pt'
    p.yaxis.axis_label = 'Energy output [kWh]'
    a1 = p.vbar(x=dodge('timestamps', 0.0, range=p.x_range),
                top='energy_DC_modelled',
                width=0.25,
                source=source,
                color='#718dbf')
    a2 = p.vbar(x=dodge('timestamps', 0.25, range=p.x_range),
                top='energy_ac_generated',
                width=0.25,
                source=source,
                color='#00008B')
    p.xgrid.grid_line_color = None
    legend = Legend(items=[("Modelled Energy DC ", [a1]),
                           ("Measured Energy AC", [a2])],
                    location=(0, -5))

    p.add_layout(legend, 'below')
    p.y_range.start = 0
    save(p)
    export_png(p,
               filename='output/' + name + '/charts/DCvsAC/energy_output' +
               end_date[:10] + '.png',
               webdriver=web_driver)

    #Extract PR for last 3 month
    system_pr = []
    timestamp_pr = []
    for i in total_list:
        i = total_list.index(i)
        system_pr.append(total_list[i]['system_pr'])
        timestamp_pr.append(total_list[i]['timestamp'][:10])
    #Draw a graph
    if system_pr:
        #create directory for graph
        if not os.path.exists('output/' + name + '/charts/PR'):
            os.makedirs('output/' + name + '/charts/PR', mode=0o777)
        #create directory for report
        if not os.path.exists('output/' + name + '/charts/reports'):
            os.makedirs('output/' + name + '/charts/reports', mode=0o777)
        output_file('output/' + name + '/charts/PR/pr_' + end_date[:10] +
                    '.html')
        #draw graph to compare real energy output and predicted one
        p = figure(plot_height=600,
                   plot_width=1000,
                   title="PR for past 3 months measured in weekly basis",
                   x_range=timestamp_pr,
                   y_range=(min(system_pr) - 0.4, max(system_pr) + 0.4))
        p.title.text_font_size = '15pt'
        p.xaxis.axis_label_text_font_size = "15pt"
        p.yaxis.axis_label_text_font_size = "15pt"
        p.yaxis.major_label_text_font_size = '15pt'
        p.xaxis.major_label_text_font_size = '15pt'
        p.xaxis.major_label_orientation = math.pi / 2
        p.yaxis.axis_label = 'performance in decimals'
        p.line(timestamp_pr,
               system_pr,
               line_width=2,
               color='blue',
               legend_label='PR')
        p.circle(timestamp_pr, system_pr, size=10, color='red', alpha=0.5)
        save(p)
        export_png(p,
                   filename='output/' + name + '/charts/PR/pr_' +
                   end_date[:10] + '.png',
                   webdriver=web_driver)

        #Generation of PDF Report
        pdf = FPDF()
        pdf.add_page()
        pdf.set_xy(0, 0)
        pdf.set_font('arial', 'B', 12)
        pdf.cell(60)
        pdf.cell(75, 10, "Performance of PV System in " + name, 0, 2, 'C')
        pdf.set_font('arial', 'B', 10)
        #extract begining of the week
        #change to string

        start_day = timestamp_pr[-2]
        stop_day = timestamp_pr[-1]
        pdf.cell(
            75, 10, "Report generated on: " +
            datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 0, 2, 'C')
        pdf.cell(75, 10, "Week: From " + start_day + ' to ' + stop_day, 0, 2,
                 'C')
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.cell(60)
        pdf.set_font('arial', '', 10)
        pdf.cell(-60)
        pdf.cell(
            90, 10,
            'Total calculated nominal energy output from PV array(DC Energy): '
            + str(total_list[-1]['total_energy_modelled_dc']) + ' kWh', 0, 2,
            'L')
        pdf.cell(
            90, 10, 'Total energy generated from PV system (AC Energy): ' +
            str(total_list[-1]['total_energy_generated_ac']) + ' kWh', 0, 2,
            'L')
        pdf.cell(90, 10, 'Performance ratio of the PV System , calculated as:',
                 0, 2, 'L')
        pdf.cell(
            90, 10,
            'Total energy generated from PV system/Total calculated nominal energy output from PV array: PR= '
            + str(total_list[-1]['system_pr']), 0, 2, 'L')
        pdf.cell(
            90, 10, 'Total calculated losses of the system  : ' +
            str(round(((1 - total_list[-1]['system_pr']) * 100), 2)) + '%', 0,
            2, 'L')
        pdf.cell(10)
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.image('output/' + name + '/charts/DCvsAC/energy_output' +
                  end_date[:10] + '.png',
                  x=None,
                  y=None,
                  w=150,
                  h=120,
                  type='',
                  link='')
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.image('output/' + name + '/charts/PR/pr_' + end_date[:10] + '.png',
                  x=None,
                  y=None,
                  w=170,
                  h=100,
                  type='',
                  link='')
        pdf.set_font('arial', 'B', 10)
        pdf_report_location = 'output/' + name + '/charts/reports/Pv_performance' + end_date[:
                                                                                             10] + '.pdf'
        pdf.output(pdf_report_location, 'F')

        return pdf_report_location
コード例 #17
0
def mkpdf():

    pdf = FPDF()
    pdf.add_page()

    # Add a DejaVu Unicode font (uses UTF-8)
    # Supports more than 200 languages. For a coverage status see:
    # http://dejavu.svn.sourceforge.net/viewvc/dejavu/trunk/dejavu-fonts/langcover.txt
    pdf.add_font('DejaVu', '', '/font/DejaVuSansCondensed.ttf', uni=True)
    pdf.set_font('DejaVu', '', 14)

    text = u"""
  English: Hello World
  Greek: Γειά σου κόσμος
  Polish: Witaj świecie
  Portuguese: Olá mundo
  Russian: Здравствуй, Мир
  Vietnamese: Xin chào thế giới
  Arabic: مرحبا العالم
  Hebrew: שלום עולם
  """

    for txt in text.split('\n'):
        pdf.write(8, txt)
        pdf.ln(8)

    # Add a Indic Unicode font (uses UTF-8)
    # Supports: Bengali, Devanagari, Gujarati,
    #           Gurmukhi (including the variants for Punjabi)
    #           Kannada, Malayalam, Oriya, Tamil, Telugu, Tibetan
    pdf.add_font('gargi', '', '/font/gargi.ttf', uni=True)
    pdf.set_font('gargi', '', 14)
    pdf.write(8, u'Hindi: नमस्ते दुनिया')
    pdf.ln(20)

    # Add a AR PL New Sung Unicode font (uses UTF-8)
    # The Open Source Chinese Font (also supports other east Asian languages)
    pdf.add_font('fireflysung', '', '/font/fireflysung.ttf', uni=True)
    pdf.set_font('fireflysung', '', 14)
    pdf.write(8, u'Chinese: 你好世界\n')
    pdf.write(8, u'Japanese: こんにちは世界\n')
    pdf.ln(10)

    # Add a Alee Unicode font (uses UTF-8)
    # General purpose Hangul truetype fonts that contain Korean syllable
    # and Latin9 (iso8859-15) characters.
    pdf.add_font('eunjin', '', '/font/Eunjin.ttf', uni=True)
    pdf.set_font('eunjin', '', 14)
    pdf.write(8, u'Korean: 안녕하세요')
    pdf.ln(20)

    # Add a Fonts-TLWG (formerly ThaiFonts-Scalable) (uses UTF-8)
    pdf.add_font('waree', '', '/font/Waree.ttf', uni=True)
    pdf.set_font('waree', '', 14)
    pdf.write(8, u'Thai: สวสดชาวโลก')
    pdf.ln(20)

    # Select a standard font (uses windows-1252)
    pdf.set_font('Arial', '', 14)
    pdf.ln(10)
    pdf.write(5, 'This is standard built-in font')

    pdf.output("/tmp/unicode.pdf", 'F')
コード例 #18
0
def fetch_images_and_return_response(deck_code: str):
    code = deck_code
    file_name = deck_code

    # html = requests.get("https://www.pokemon-card.com/deck/deck.html?deckID=11F1Fw-VNG8m4-fk1bVF").content
    html = requests.get("https://www.pokemon-card.com/deck/deck.html?deckID=" + code).content

    soup = BeautifulSoup(html, "html.parser")

    card_data_script_text = soup.find_all("script")[-1].contents[0]

    # deck_pke_list の例: [["33525", "3"], ["33525", "3"]]
    deck_pke_list = [elem.split("_")[:2] for elem in soup.find(id="deck_pke")["value"].split("-")]
    deck_gds_list = [elem.split("_")[:2] for elem in soup.find(id="deck_gds")["value"].split("-")] \
        if soup.find(id="deck_gds")["value"] != "" else []
    deck_sup_list = [elem.split("_")[:2] for elem in soup.find(id="deck_sup")["value"].split("-")] \
        if soup.find(id="deck_sup")["value"] != "" else []
    deck_sta_list = [elem.split("_")[:2] for elem in soup.find(id="deck_sta")["value"].split("-")] \
        if soup.find(id="deck_sta")["value"] != "" else []
    deck_ene_list = [elem.split("_")[:2] for elem in soup.find(id="deck_ene")["value"].split("-")] \
        if soup.find(id="deck_ene")["value"] != "" else []
    # deck_ajs_list = [elem.split("_")[:2] for elem in soup.find(id="deck_ajs")["value"].split("-")]\
    #     if soup.find(id="deck_ajs")["value"] != "" else []

    deck_list = deck_pke_list + deck_gds_list + deck_sup_list + deck_sta_list + deck_ene_list  # + deck_ajs_list
    cards_to_print_count = 0

    card_url_list = []

    dl_counter = 0

    for elm in deck_list:
        dl_counter += 1
        pattern = re.compile(r"(/assets/images/card_images/([a-zA-Z]+)/[^\n]*/0+%s_[^\n]+\.jpg)" % elm[0],
                             re.MULTILINE | re.DOTALL)
        match = pattern.search(card_data_script_text)

        if match:
            url = "https://www.pokemon-card.com" + match.group(1)
            elm.append(url)
        #    print(elm)
        else:
            # たまに画像がなくて裏面の画像なことがあるので、その対応
            url = "https://www.pokemon-card.com/assets/images/noimage/poke_ura.jpg"
            elm.append(url)

        try:
            for i in range(int(elm[1])):
                cards_to_print_count += 1
                card_url_list.append(elm[2])
        except ValueError:
            return HttpResponse(
                "デッキコードが正しくないか、ポケモンカード公式のサーバが応答していません。",
                content_type="text/plain; charset=utf-8"
            )

    # キャンバスと出力ファイルの初期化
    pdf = FPDF(orientation='P', unit='mm', format="A4")

    pdf.set_author("PTCG2Win")
    pdf.set_title(deck_code)
    pdf.set_subject("PDF to print")

    card_url_or_image_list = []

    def split_images_and_append_to_list(input_image: Image.Image, x_pieces, y_pieces, output_list):
        imgwidth, imgheight = input_image.size
        height = imgheight // y_pieces
        width = imgwidth // x_pieces
        for j in range(y_pieces):
            for k in range(x_pieces):
                box = (k * width, j * height, (k + 1) * width, (j + 1) * height)
                part = input_image.crop(box)
                output_list.append(part)

    def trim(input_image: Image.Image) -> Image.Image:
        bg = Image.new(input_image.mode, input_image.size, input_image.getpixel((0, 0)))
        diff = ImageChops.difference(input_image, bg)
        diff = ImageChops.add(diff, diff, 2.0, -100)
        bbox = diff.getbbox()
        if bbox:
            return input_image.crop(bbox)

    v_union_filename_pattern: re.Pattern = re.compile(r"[A-Z]VUNION\.jpg$")
    reduced_card_url_list = []
    cards_count = len(card_url_list)
    for i in range(cards_count):
        card_url = card_url_list[i]
        if re.search(v_union_filename_pattern, card_url):
            for j in range(card_url_list.count(card_url) // 4):
                reduced_card_url_list.append(card_url)
            card_url_list = ["" if url == card_url else url for url in card_url_list]
        else:
            reduced_card_url_list.append(card_url)
    filtered_card_url_list = [card_url for card_url in reduced_card_url_list if card_url != ""]

    for card_url in filtered_card_url_list:
        if "/card_images/legend/" in card_url:
            rsp = requests.get(card_url, stream=True)
            rsp.raw.decode_content = True
            img_object = Image.open(rsp.raw)
            img_object = img_object.rotate(90, expand=True)
            card_url_or_image_list.append(img_object)
        elif re.search(v_union_filename_pattern, card_url):
            rsp = requests.get(card_url, stream=True)
            rsp.raw.decode_content = True
            img_object = trim(Image.open(rsp.raw))
            split_images_and_append_to_list(img_object, 2, 2, card_url_or_image_list)
        else:
            card_url_or_image_list.append(card_url)

    # ポケモンカードのサイズは63x88なので、紙を縦置きにした場合、3枚x3枚(189x264)入る。
    for i in range(len(card_url_or_image_list)):
        card_url_or_image = card_url_or_image_list[i]
        # 9枚ごとに改ページ
        if i % 9 == 0:
            pdf.add_page("P")
        #        print("Page", i // 9 + 1)
        # 3枚ごとに改行
        x_pos = (11 + 63 * (i % 3))
        y_pos = (15 + 88 * ((i % 9) // 3))

        pdf.image(
            card_url_or_image,
            x_pos,
            y_pos,
            w=63,
            h=88,
        )

    buffer = BytesIO()

    output = pdf.output()
    buffer.write(output)
    buffer.seek(0)
    # httpレスポンスの作成
    return FileResponse(buffer, filename=f"{deck_code}.pdf", as_attachment=True, content_type='application/pdf')
コード例 #19
0
           fig.text(x=0.45, y=0.95, s=snm[0], fontsize=16, weight='bold', color='#676868')
           fig.text(x=0.05, y=0.5, s="VALUE", fontsize=16, color='#676868', rotation='vertical')
           fig.text(x=0.5, y=0, s="DATE", fontsize=16, color='#676868')
           plt.savefig(folder+'/'+snm[0]+'.png', bbox_inches='tight')
           plt.close(fig)
    return outliers_fix, outliers_not_fix

num_cores = int(options.cores)

results = Parallel(n_jobs=num_cores)(delayed(main_loop)(ts, outliers_fix,outliers_not_fix,all_filtered_data,folder) for ts in id_unique)
outliers_fi=[item[0] for item in results]
outliers_not_fi=[item[1] for item in results]

total_frame = None # delete big variable from memory
imagelist = listdir(folder+'/') # get list of all images

print('## Saving to csv')
total = pd.concat([pd.concat(outliers_not_fi,sort = True), pd.concat(outliers_fi,sort = True)], axis = 1, sort = True)
total.to_csv(folder+'total.csv')


print('## Making pdf')
pdf = FPDF( orientation = 'l', unit = 'mm', format='a4')
for image in imagelist:
    pdf.add_page()
    pdf.image(folder+'/'+image,0, 0, 280, 200)
pdf.output(folder+"images.pdf","f")


print("--- %s min ---" % round(float((time.time() - start_time))/60,2))
コード例 #20
0
class FacturaPdf:

    pdf = FPDF()
    pagina = 0
    yLinea = 0
    saltoPagina = 225
    lineas = []
    jsonDecoded = ""
    textoResiduos = "El responsable de la entrega del residuo o envase usado, para su correcta gestión ambiental es el poseedor final (R.D. 782/98 art.18)"
    textoRegistro = "Inscrita en el Reg.Mercantil de Valencia, Tomo 6.630, Libro 3.934, Folio 205, Sección 8º, Hoja V-71.929, Inscr. 1ª."

    idioma = ""
    textosIdioma = {
        "INGLES": {
            "albaran": "Dlv. Note:",
            "fecha": "Date:",
            "Pedido": "Order Nr.:",
            "bultos": "Total Cases:",
            "pesoBruto": "Gross Weight:",
            "pesoNeto": "Net Weight:",
            "cliente": "CUSTOMER NUMBER",
            "agente": "BROKER",
            "numeroFactura": "INVOICE NUMBER",
            "codigo": "ITEM Nr.",
            "descripcion": "PRODUCT NAME",
            "cantidad": "CASES",
            "precio": "PRICE",
            "importe": "AMOUNT",
            "importeBruto": "GROSS AMOUNT",
            "descuento": "DISCOUNT",
            "descuentoPP": "%ADV PAYMENT",
            "condicionesPago": "PAYMENT TERMS:",
            "totalFactura": "TOTAL INVOICE"
        }
    }

    def __init__(self):

        self.pdf = FPDF()
        self.pdf.set_font("Arial", size=9)

    def __del__(self):
        #del(FPDF)
        print('Destructor called')

    def leerCaracter(self, nombreFichero="factura.json", desde=1, hasta=1):
        with open(nombreFichero) as fileobj:
            i = 1
            for line in fileobj:
                for ch in line:
                    if i >= desde and i <= hasta:
                        print(ch)
                    i += 1

    def leerJSON(self, nombreFichero="E_1270.json"):

        os.chdir(r"C:\ServidorWeb\server\kingCRM\facturas")

        script_dir = os.path.dirname(
            __file__)  #<-- absolute dir the script is in
        rel_path = "facturas/" + nombreFichero
        abs_file_path = os.path.join(script_dir, rel_path)

        f = open(abs_file_path, "r")

        #f = codecs.open(abs_file_path, "r", encoding="cp500")
        content = f.read()

        jsonDecoded = json.loads(content)
        #print(jsonDecoded)

        f.close()
        self.jsonDecoded = jsonDecoded

        lineas = jsonDecoded["lineas"]
        self.lineas = lineas

        if "idioma" in jsonDecoded:
            self.idioma = jsonDecoded["idioma"]

    def anyadirPagina(self):

        self.pagina += 1
        self.pdf.add_page()

        #self.pdf.image("preformatoKr.png", 1, 1)

        self.pdf.image("leon_agua.png", 40, 100, 150, 150)
        self.pdf.image("LOGO_KR.jpg", 10, 1, 50, 50)

        self.pdf.rect(5, 60, 200, 15)
        self.textoImprimir(7, 64, self.idioma, "cliente", "CODIGO CLIENTE")

        self.pdf.line(40, 60, 40, 75)
        self.textoImprimir(42, 64, self.idioma, "agente", "AGENTE")

        self.pdf.line(108, 60, 108, 75)
        self.textoImprimir(110, 64, self.idioma, "fecha", "FECHA")

        self.pdf.line(168, 60, 168, 75)

        self.textoImprimir(175, 64, self.idioma, "numeroFactura", "Nº FACTURA")

        self.pdf.rect(5, 80, 200, 150)

        self.pdf.line(5, 86, 205, 86)
        self.textoImprimir(7, 84, self.idioma, "codigo", "CODIGO")
        self.pdf.line(25, 80, 25, 230)
        self.textoImprimir(42, 84, self.idioma, "descripcion", "DESCRIPCION")
        self.pdf.line(85, 80, 85, 230)
        self.textoImprimir(90, 84, self.idioma, "cantidad", "CANTIDAD")
        self.pdf.line(108, 80, 108, 230)
        self.pdf.text(110, 84, "UxCJ")
        self.pdf.line(118, 80, 118, 230)
        self.pdf.text(120, 84, "T.UDS")
        self.pdf.line(135, 80, 135, 230)
        self.textoImprimir(140, 84, self.idioma, "precio", "PRECIO UNIDAD")
        self.pdf.line(168, 80, 168, 230)
        self.pdf.text(170, 84, "% DTO")
        self.pdf.line(182, 80, 182, 230)

        self.textoImprimir(185, 84, self.idioma, "importe", "IMPORTE")

        self.pdf.rect(5, 235, 200, 30)

        self.yLinea = 239
        self.pdf.set_font("Arial", size=8)
        self.textoImprimir(10, self.yLinea, self.idioma, "importeBruto",
                           "IMPORTE BRUTO")
        self.textoImprimir(40, self.yLinea, self.idioma, "descuento",
                           "DESCUENTO")
        self.textoImprimir(70, self.yLinea, self.idioma, "descuentoPP",
                           "DESCUENTO P.P")

        if self.idioma == "":
            self.pdf.text(110, self.yLinea, "BASE IMPONBLE")
            self.pdf.text(150, self.yLinea, "IVA")
            self.pdf.text(170, self.yLinea, "REC.EQUIVALENCIA")

        self.pdf.set_font("Arial", size=6)
        self.textoImprimir(10, 269, self.idioma, "condicionesPago",
                           "CONDICIONES DE PAGO:")
        self.pdf.rect(5, 270, 140, 20)

        self.pdf.rect(155, 270, 50, 20)
        self.pdf.set_font("Arial", size=10)
        self.textoImprimir(160, 275, self.idioma, "totalFactura",
                           "TOTAL FACTURA")

        self.pdf.set_font("Arial", size=7)
        self.pdf.text(10, 293, self.textoResiduos)
        self.pdf.text(10, 296, self.textoRegistro)

        self.pdf.set_font("Arial", size=10)

    def imprimirCabecera(self):

        self.pdf.set_font("Arial", size=10)

        self.pdf.line(105, 15, 110, 15)
        self.pdf.line(105, 15, 105, 20)

        self.pdf.line(200, 15, 205, 15)
        self.pdf.line(205, 15, 205, 20)

        self.yLinea = 20
        self.pdf.text(110, self.yLinea, self.jsonDecoded["nombre"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["direccion1"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["direccion2"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["direccion3"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["direccion4"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["Nif"])
        if self.jsonDecoded["coa"].strip() == "A":
            self.pdf.text(70, self.yLinea, "** abono **")

        self.yLinea += 6

        self.pdf.line(200, self.yLinea, 205, self.yLinea)
        self.pdf.line(205, self.yLinea - 5, 205, self.yLinea)

        self.pdf.line(105, self.yLinea - 5, 105, self.yLinea)
        self.pdf.line(105, self.yLinea, 110, self.yLinea)

        self.yLinea = 70
        self.pdf.text(10, self.yLinea, self.jsonDecoded["codigoCliente"])
        self.pdf.text(42, self.yLinea, self.jsonDecoded["agente"])
        self.pdf.text(115, self.yLinea, self.jsonDecoded["fecha"])
        self.pdf.text(175, self.yLinea, self.jsonDecoded["factura"])

        print(self.jsonDecoded["codigoCliente"])

    def imprimirPie(self):

        self.yLinea = 246
        self.pdf.set_font("Arial", size=10)
        self.pdf.text(10, self.yLinea, self.jsonDecoded["bruto"])
        self.pdf.text(35, self.yLinea, self.jsonDecoded["descuento"])
        self.pdf.text(50, self.yLinea, self.jsonDecoded["ImporteDtc1"])
        self.pdf.text(70, self.yLinea, self.jsonDecoded["dtoPronto"])
        self.pdf.text(90, self.yLinea, self.jsonDecoded["ImporteDtpp"])

        self.pdf.text(110, self.yLinea, self.jsonDecoded["base1"])
        self.pdf.text(130, self.yLinea, self.jsonDecoded["porcentajeIva1"])
        self.pdf.text(155, self.yLinea, self.jsonDecoded["cuotaIva1"])
        self.pdf.text(170, self.yLinea, self.jsonDecoded["porcentajeRecargo1"])
        self.pdf.text(190, self.yLinea, self.jsonDecoded["cuotaRecargo1"])

        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["base2"])
        self.pdf.text(130, self.yLinea, self.jsonDecoded["porcentajeIva2"])
        self.pdf.text(150, self.yLinea, self.jsonDecoded["cuotaIva2"])
        self.pdf.text(170, self.yLinea, self.jsonDecoded["porcentajeRecargo2"])
        self.pdf.text(190, self.yLinea, self.jsonDecoded["cuotaRecargo2"])

        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["base3"])
        self.pdf.text(130, self.yLinea, self.jsonDecoded["porcentajeIva3"])
        self.pdf.text(150, self.yLinea, self.jsonDecoded["cuotaIva3"])
        self.pdf.text(170, self.yLinea, self.jsonDecoded["porcentajeRecargo3"])
        self.pdf.text(190, self.yLinea, self.jsonDecoded["cuotaRecargo3"])

        self.yLinea = 276

        if "formaPago" in self.jsonDecoded.keys():

            self.pdf.text(40, self.yLinea, self.jsonDecoded["formaPago"])
            self.yLinea += 6

        if "importePlazo1" in self.jsonDecoded.keys():

            if self.jsonDecoded["importePlazo1"].strip() != "":
                self.pdf.text(10, self.yLinea, self.jsonDecoded["fechaPlazo1"])
                self.pdf.text(35, self.yLinea,
                              self.jsonDecoded["importePlazo1"])

            if self.jsonDecoded["importePlazo2"].strip() != "":
                self.pdf.text(65, self.yLinea, self.jsonDecoded["fechaPlazo2"])
                self.pdf.text(85, self.yLinea,
                              self.jsonDecoded["importePlazo2"])

            if self.jsonDecoded["importePlazo3"].strip() != "":
                self.pdf.text(105, self.yLinea,
                              self.jsonDecoded["fechaPlazo3"])
                self.pdf.text(125, self.yLinea,
                              self.jsonDecoded["importePlazo3"])

        if "apagar" in self.jsonDecoded.keys():

            self.pdf.text(175, self.yLinea, self.jsonDecoded["apagar"])

    def textoImprimir(self, x=0, y=0, idioma="", clave="", textoInicial=""):
        texto = textoInicial
        if idioma in self.textosIdioma:
            if clave in self.textosIdioma[idioma]:

                texto = self.textosIdioma[idioma][clave]
        self.pdf.text(x, y, texto)

    def imprimirLineas(self):
        self.yLinea = 90
        self.pdf.set_font("Arial", size=10)

        if self.pagina == 1:
            primeraLineaImpresa = False
            if self.jsonDecoded["albaran"].strip() != "":
                if self.idioma != "":
                    self.pdf.text(32, self.yLinea,
                                  "Dlv. Note:: " + self.jsonDecoded["albaran"])
                else:
                    self.pdf.text(32, self.yLinea,
                                  "Albaran: " + self.jsonDecoded["albaran"])

                primeraLineaImpresa = True
                if self.idioma != "":
                    self.pdf.text(62, self.yLinea,
                                  "Date: " + self.jsonDecoded["fechaAlbaran"])
                else:
                    self.pdf.text(62, self.yLinea,
                                  "Fecha: " + self.jsonDecoded["fechaAlbaran"])

                primeraLineaImpresa = True
            if self.jsonDecoded["pedido"].strip() != "":
                if self.idioma != "":
                    self.pdf.text(102, self.yLinea,
                                  "Order Nr.: " + self.jsonDecoded["pedido"])
                else:
                    self.pdf.text(102, self.yLinea,
                                  "Pedido: " + self.jsonDecoded["pedido"])

                primeraLineaImpresa = True

            if primeraLineaImpresa:
                self.yLinea += 5
        for linea in self.lineas:

            self.pdf.set_font("Arial", size=6)
            self.pdf.text(7, self.yLinea, linea["articulo"])
            self.pdf.set_font("Arial", size=8)
            self.pdf.text(32, self.yLinea, linea["descripcion"])
            self.pdf.text(98, self.yLinea,
                          linea["cantidad"].lstrip(' 0').rjust(7))
            self.pdf.text(110, self.yLinea,
                          linea["factor"].lstrip(' 0').rjust(7))
            self.pdf.text(120, self.yLinea, linea["unidades"])
            self.pdf.text(140, self.yLinea, linea["precio"])
            self.pdf.text(170, self.yLinea, linea["descuento"])
            self.pdf.text(185, self.yLinea, linea["importe"])

            self.yLinea += 5
            self.saltar()

    def imprimirPesos(self):

        self.pdf.set_font("Arial", size=8)

        observaciones = []
        if 'observaciones' in self.jsonDecoded.keys():
            observaciones = self.jsonDecoded["observaciones"]
        for observacion in observaciones:
            if observacion.strip() != "":
                self.yLinea = self.yLinea + 5
                self.saltar()
                self.pdf.text(32, self.yLinea, observacion)

        self.yLinea = self.yLinea + 5
        self.saltar()

        if "bultos" in self.jsonDecoded.keys():
            self.textoImprimir(7, self.yLinea, self.idioma, "bultos",
                               "Bultos: ")
            self.pdf.text(32, self.yLinea, self.jsonDecoded["bultos"])

        if "pesoBruto" in self.jsonDecoded.keys():
            self.textoImprimir(58, self.yLinea, self.idioma, "pesoBruto",
                               "Peso Bruto: ")
            self.pdf.text(80, self.yLinea, self.jsonDecoded["pesoBruto"])

        if "pesoNeto" in self.jsonDecoded.keys():
            self.textoImprimir(120, self.yLinea, self.idioma, "pesoNeto",
                               "Peso Neto: ")
            self.pdf.text(140, self.yLinea, self.jsonDecoded["pesoNeto"])

            print(self.yLinea)

    def saltar(self):
        if self.yLinea > self.saltoPagina:
            self.anyadirPagina()
            self.imprimirCabecera()
            self.yLinea = 90

    def finalizarDocumento(self, documento="factura.pdf"):

        script_dir = os.path.dirname(
            __file__)  #<-- absolute dir the script is in
        rel_path = "facturas\\" + documento
        abs_file_path = os.path.join(script_dir, rel_path)

        print("Fichero a cerrar: " + abs_file_path)
        self.pdf.output(abs_file_path)
コード例 #21
0
def heterozygosity(het_method, std, het_dataframe, thresh, minThresh, population, outDir):
	pdf = FPDF() # create new PDF
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "Heterozygosity", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)

	sample_fails = open(outDir + '/' + population + '/samples_failing_heterozygosity.txt', 'w')
	#het_method of setting min and max thresholds based on F score inbreeding coefficient
	if het_method == 'minMax':
		fail_het = het_dataframe.loc[((het_dataframe['F'] > thresh) | (het_dataframe['F'] < minThresh))]
		fail_het[['FID', 'IID']].to_csv(sample_fails.name, sep='\t', index=False, header=False) # format it FID <tab> IID <new line>


		# sorts inbreeing coeffiecient score to rank for ploting
		het_dataframe.sort_values(by='F', ascending=True, axis=0, inplace=True)
		het_dataframe = het_dataframe.reset_index()
		het_dataframe['rank'] = het_dataframe.index
		
		pdf.set_font('Arial', '', 12)
		pdf.multi_cell(0, 5, 'Heterozygosity is calculated on the merged sample space.  Samples with extreme levels of heterozygosity as measured by \
			the F inbreeding coefficient, may be indicative of a sample exhibiting poor quality.  The current inbreeding coefficient threshold is set \
			to a maximum of ' + str(thresh) + ' and a minimum of ' + str(minThresh) +'.  Any F value above the maximum threshold or below the minimum threshold is filtered out.', 0, 1, 'J')
		pdf.multi_cell(0, 5, '\n', 0, 1, 'J')
		pdf.set_font('Arial', 'B', 16)
		pdf.set_fill_color(200)
		pdf.multi_cell(0, 8, str(population), 1, 'L', True)
		pdf.multi_cell(0, 8, 'Total Number Samples Analyed: '+ str(len(het_dataframe.index)), 1, 'L', True)
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number Samples Failing: '+ str(len(fail_het.index)), 1, 1, 'L')
		pdf.multi_cell(0, 8, str(population), 1, 'L', True)
		het_dataframe.plot(kind='scatter', x='rank', y='F', title='Ranked Inbreeding Coefficient scores', s=7)
		plt.tight_layout(pad=2, w_pad=2, h_pad=2)
		plt.savefig(outDir+'/'+ str(population) + '_heterozygosity_plot.png')
		plt.close()
		pdf.image(outDir+'/'+ str(population) + '_heterozygosity_plot.png', x=10, y=130, w=190, h=150)

		sample_fails.flush()
		sample_fails.close()
	
	elif het_method == 'meanStd':
		het_mean = het_dataframe['het_score'].mean() # calculates the mean of the calculated het_score across all samples
		het_std = het_dataframe['het_score'].std() # calculated the standard deviation of the calculated het_score across all samples
		max_value = het_mean + (float(std)*het_std) # gets the max acceptable het_score give the number of standard deviations allowed from the mean set by the user
		min_value = het_mean - (float(std)*het_std) # gets the min acceptable het_score give the number of standard deviations allowed from the mean set by the user
		fail_het = het_dataframe.loc[((het_dataframe['het_score'] > max_value) | (het_dataframe['het_score'] < min_value))]
		fail_het[['FID', 'IID']].to_csv(sample_fails.name, sep='\t', index=False, header=False) # format it FID <tab> IID <new line>
		pass_het = het_dataframe.loc[((het_dataframe['het_score'] <= max_value) & (het_dataframe['het_score'] >= min_value))]
		pass_het['Group'] = 'After'
		het_dataframe['Group'] = 'Before'

		combine = pd.concat([het_dataframe, pass_het]) # concantenates dataframes before and after filterings to make boxplot comparisons by Group
		combine.boxplot(by='Group', column='het_score')
		plt.tight_layout(pad=2, w_pad=2, h_pad=2)
		plt.savefig(outDir+'/'+ str(population) +'_heterozygosity_plot.png')
		plt.close()

		# generate PDF of heterozygosity results
		pdf.set_font('Arial', '', 12)
		pdf.multi_cell(0, 5, 'Heterozygosity is calculated on the merged sample space.  Samples with extreme levels of heterozygosity as measured by \
			the heterozygosity score calculated using the following formula: het_score = 1 - [O(HOM)/N(NM)], may be indicative of a sample exhibiting poor quality.  The current het_score thresholds \
			are set to filter out any samples exhibiting excess heterozygosity of +/- ' + str(std) + ' standard deviations from the mean het_score.' , 0, 1, 'J')
		pdf.multi_cell(0, 5, '\n', 0, 1, 'J')
		pdf.set_font('Arial', 'B', 16)
		pdf.set_fill_color(200)
		pdf.multi_cell(0, 8, str(population), 1, 'L', True)
		pdf.multi_cell(0, 8, 'Total Number Samples Analyed: '+ str(len(het_dataframe.index)), 1, 'L', True)
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number Samples Failing: '+ str(len(fail_het.index)), 1, 1, 'L')
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Mean (Before): '+ str("{0:.5f}".format(round(het_mean,5))), 1, 1, 'L')
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Mean (After): '+ str("{0:.5f}".format(round(pass_het['het_score'].mean(),5))), 1, 1, 'L')
		pdf.image(outDir+'/'+ str(population) +'_heterozygosity_plot.png', x=10, y=130, w=190, h=150)
	
		sample_fails.flush()
		sample_fails.close()

	return sample_fails.name, pdf
コード例 #22
0
    def __init__(self):

        self.pdf = FPDF()
        self.pdf.set_font("Arial", size=9)
コード例 #23
0
def main():
    # reads input parameters
    form = cgi.FieldStorage()
    #h = HTMLParser.HTMLParser()

    data = form.getfirst("data")

    strParams = form.getfirst("strParams")

    pos = data.find(",")

    data = data[pos + 1:]

    arrayParams = strParams.split('<%%>')
    data = base64.b64decode(data)

    # output directory
    strOutputDirectory = _returnTempDirectory(0)
    # return filename
    strName = _returnUniqueFilename()
    # png and pdf extensions
    strOutFilenamePNG = strName + '.png'
    strOutFilenamePDF = strName + '.pdf'
    # open png file for writing
    f = open(strOutputDirectory + strOutFilenamePNG, 'w')
    f.write(data)
    f.close()
    # parameters

    # print arrayParams[1]
    # strText=arrayParams[1].encode("utf-8")

    # print strText
    # arrayParams[1]=h.unescape(arrayParams[1])
    #arrayParams[1]=arrayParams[1].replace("<br>", ", ");
    #arrayParams[1]=arrayParams[1].replace("Â", "");

    # variables
    arrayVars1 = arrayParams[2].split('#')
    arrayVars2 = arrayParams[3].split('#')

    # pdf istance
    pdf = FPDF()
    # add page
    pdf.add_page()

    #pdf.add_font('Arial', '', r'/var/lib/opengeo/geoserver/styles/ArialSansCondensed.ttf', uni=True)
    #pdf.set_font('Arial', '', 14)

    pdf.set_font('Arial', 'B', 16)
    cont = 0
    # add title
    strTitle = _returnIniValue('PDF_CONFIGURATION', 'PDF_TITLE')
    pdf.cell(200, 10, txt=strTitle, ln=1, align="L")
    pdf.set_font('Arial', '', 16)
    strHttp = _returnHttpAddress()
    # add ce ll for address
    pdf.cell(200, 10, strHttp, 0, 1, 'L')
    pdf.ln(10)
    cont = cont + 10
    # add cell for operation
    pdf.set_font('Arial', '', 12)
    pdf.cell(0, 0, 'Operation: ')
    pdf.ln(5)
    cont = cont + 5
    pdf.set_x(15)
    # add cell for coordinates
    # pdf.set_font('Arial','',12)
    pdf.cell(0, 0, arrayParams[0].decode('UTF-8'))
    pdf.ln(5)
    cont = cont + 5
    # add cell for coordinates
    pdf.set_font('Arial', '', 12)
    pdf.cell(0, 0, 'Coordinates: ')
    pdf.ln(5)
    cont = cont + 5
    pdf.set_x(15)
    # pdf.set_font('Arial','',12)
    pdf.cell(0, 0, arrayParams[1].decode('UTF-8'))

    #pdf.write(8, text)
    pdf.ln(5)
    cont = cont + 5
    pdf.set_font('Arial', '', 12)
    # variables list
    pdf.cell(0, 0, 'Variables Y1: ')
    pdf.ln(5)
    cont = cont + 5
    strAdditionalInfo = ''
    strTextCopyright = ''
    for value in arrayVars1:
        if (value != ""):
            arrayFName = returnVariableFeature(value)

            arrayVDataset = _returnDatasetAttributes(
                arrayFName["id"], arrayFName["type"])
            pdf.set_font('Arial', '', 12)
            strAdd = arrayFName["description"].decode('UTF-8')
            if (arrayVDataset["unit"] != ""):
                strAdd += ' (' + arrayVDataset["unit"].decode('UTF-8') + ')'

            pdf.set_x(15)
            pdf.cell(0, 0, strAdd)
            # for each variable add a description
            pdf.ln(5)
            cont = cont + 5
            # save the copyright for each variable in order to put the text
            # after the graph
            strTextCopyright += '\n\n' + strAdd + '\n' + \
                _returnPdfCopyright(arrayFName["id"])

            strAdditionalInfo += _returnMetadataAdditionalInfo(
                arrayFName["id"])
            strAdditionalInfo += '\n\nMetadata link: \n' + \
                _returnMetadataLink(arrayFName["id"])

    blnPrimaVolta = 1

    for value in arrayVars2:
        if (value != ""):
            if (blnPrimaVolta == 1):
                blnPrimaVolta = 0
                pdf.cell(0, 0, 'Variables Y2: ')
                pdf.ln(5)

            pdf.set_x(15)
            arrayFName = returnVariableFeature(value)
            arrayVDataset = _returnDatasetAttributes(
                arrayFName["id"], arrayFName["type"])
            pdf.set_font('Arial', '', 12)
            strAdd = arrayFName["description"].decode('UTF-8')
            if (arrayVDataset["unit"] != ""):
                strAdd += ' (' + arrayVDataset["unit"].decode('UTF-8') + ')'

            pdf.cell(0, 0, strAdd)
            # for each variable add a description
            pdf.ln(5)
            cont = cont + 5
            # save the copyright for each variable in order to put the text
            # after the graph
            strTextCopyright += '\n\n' + strAdd + '\n' + \
                _returnPdfCopyright(arrayFName["id"])
            strAdditionalInfo += '\n\n' + \
                _returnMetadataAdditionalInfo(arrayFName["id"])
            strAdditionalInfo += '\n\nMetadata link: \n' + \
                _returnMetadataLink(arrayFName["id"])
    # add graph image
    pdf.image(strOutputDirectory + strOutFilenamePNG,
              10, cont + 40, 180, 120, 'PNG')
    # add copyright
    if (strTextCopyright != ""):
        pdf.ln(130)
        pdf.set_font('Arial', '', 12)
        pdf.cell(0, 0, 'Use limitation: ')
        pdf.ln(1)
        pdf.set_font('Arial', '', 10)
        pdf.multi_cell(180, 5, strTextCopyright.decode('UTF-8'))
        strHTTPOutputDirectory = _returnTempDirectory(1)
    pdf.ln(5)
    if (strAdditionalInfo != ""):
        pdf.set_font('Arial', '', 10)
        pdf.multi_cell(180, 5, strAdditionalInfo.decode('UTF-8'))
        strHTTPOutputDirectory = _returnTempDirectory(1)
    pdf.ln(5)

    pdf.output(strOutputDirectory + strOutFilenamePDF, 'F')
    # print and return the output link
    print strHTTPOutputDirectory + strOutFilenamePDF
コード例 #24
0
explode = tuple(explode_list)
'''Plot'''
plt.pie(sizes,
        explode=explode,
        labels=labels,
        colors=colors,
        autopct='%1.1f%%',
        shadow=True,
        startangle=140)
plt.title('Score Distribution of %s' % app.upper())
# plt.show()
'''Plot save to .png'''
plt.savefig('%s' % app.upper() + '.png')
plt.close()
'''Create PDF'''
pdf = FPDF(orientation='L', unit='mm', format='A4')  #landscape
pdf.add_page()
pdf.set_font("Arial", size=12, style='')
pdf.cell(280, 10, txt="%s " % app.upper() + "Satisfication", ln=1,
         align="L")  # ln = add a line break
'''Title and Image'''
total_respondents_str = "Total respondents = " + str(total_respondents)
pdf.cell(280, 12, txt="{}".format(total_respondents_str), ln=1, align="L")
pdf.cell(280,
         12,
         txt="%.2f" % round(satisfaction, 2) +
         '% of people satisfied with the app ',
         ln=1,
         align="L")
pdf.image('%s' % app.upper() + '.PNG', x=120, y=0, w=100)
'''Generate table'''
コード例 #25
0
                   pos_x_pix:pos_x_pix + code_pixels] = code_ima

    if ii == 0:
        code_str = 'Front'
    elif ii == 511:
        code_str = 'Back'
    else:
        code_str = str(ii)

    cv2.putText(
        codes_page_ima, code_str,
        (pos_x_pix + code_pixels // 2 - 10, pos_y_pix + code_pixels + 30),
        cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2)

    print(ii, pos_y, pos_x)

    if (ii + 1) % codes_per_page == 0:
        page_name_jpg = '{}/{}_codes_page_{:04d}.png'.format(
            out_dir, dict_name, page_counter)
        cv2.imwrite(page_name_jpg, codes_page_ima)

        page_counter = page_counter + 1
        codes_page_ima.fill(255)

        page_name_pdf = '{}/{}_codes_page_{:04d}.pdf'.format(
            out_dir, dict_name, page_counter)
        pdf = FPDF('P', 'mm', 'A4')
        pdf.add_page()
        pdf.image(page_name_jpg, 5, 5, 200, 200)
        pdf.output(page_name_pdf)
コード例 #26
0
#for python 3 install fpdf package "pip3 install fpdf".

from fpdf import FPDF

#class object FPDF() which is predefiend in side the package fpdf.
document = FPDF(orientation='P', unit='mm', format='A4')
# pdf = FPDF('P', 'mm', (100, 150)) with custom size

document.set_title("This is custom title")

document.set_margins(25, 20, 20)
# left, top, right...... Define before creating page, otherwise will ruin formatting

#There is no page for the moment, so we have to add one with add_page.
document.add_page()

#the bottom margin is simply left out of predefinition because it is part of the page break calculation process.
#Therefore, setting a bottom margin in itself is not possible, but it can be done using
#SetAutoPageBreak(boolean auto, [float margin])

#font size setting of the page
document.set_font("Arial", size=20)

document.set_text_color(255, 255, 255)

document.set_fill_color(20, 50, 80)
# cell fill colour, visible if cell property fill set to true

document.set_draw_color(190, 9, 30)
# border color, used for all drawing operations (lines, rectangles and cell borders)
コード例 #27
0
    def add_files_to_pdf(self,
                         files: list = None,
                         target_document: str = None,
                         append: bool = False) -> None:
        """Add images and/or pdfs to new PDF document

        Image formats supported are JPEG, PNG and GIF.

        The file can be added with extra properties by
        denoting `:` at the end of the filename. Each
        property should be separated by comma.

        Supported extra properties for PDFs are:

        - page and/or page ranges
        - no extras means that all source PDF pages are added
          into new PDF

        Supported extra properties for images are:

        - format, the PDF page format, for example. Letter or A4
        - rotate, how many degrees image is rotated counter-clockwise
        - align, only possible value at the moment is center
        - orientation, the PDF page orientation for the image, possible
          values P (portrait) or L (landscape)
        - x/y, coordinates for adjusting image position on the page

        **Examples**

        **Robot Framework**

        .. code-block:: robotframework

            ***Settings***
            Library    RPA.PDF

            ***Tasks***
            Add files to pdf
                ${files}=    Create List
                ...    ${TESTDATA_DIR}${/}invoice.pdf
                ...    ${TESTDATA_DIR}${/}approved.png:align=center
                ...    ${TESTDATA_DIR}${/}robot.pdf:1
                ...    ${TESTDATA_DIR}${/}approved.png:x=0,y=0
                ...    ${TESTDATA_DIR}${/}robot.pdf:2-10,15
                ...    ${TESTDATA_DIR}${/}approved.png
                ...    ${TESTDATA_DIR}${/}landscape_image.png:rotate=-90,orientation=L
                ...    ${TESTDATA_DIR}${/}landscape_image.png:format=Letter
                Add Files To PDF    ${files}    newdoc.pdf

        **Python**

        .. code-block:: python

            from RPA.PDF import PDF

            pdf = PDF()

            list_of_files = [
                'invoice.pdf',
                'approved.png:align=center',
                'robot.pdf:1',
                'approved.png:x=0,y=0',
            ]
            def example_keyword():
                pdf.add_files_to_pdf(
                    files=list_of_files,
                    target_document="output/output.pdf"
                )

        :param files: list of filepaths to add into PDF (can be either images or PDFs)
        :param target_document: filepath of target PDF
        :param append: appends files to existing document if `append` is `True`
        """
        writer = PyPDF2.PdfFileWriter()

        if append:
            self._add_pages_to_writer(writer, target_document)

        for f in files:
            file_to_add = Path(f)
            namesplit = file_to_add.name.rsplit(":", 1)
            basename = namesplit[0]
            parameters = namesplit[1] if len(namesplit) == 2 else None
            file_to_add = file_to_add.parent / basename
            image_filetype = imghdr.what(str(file_to_add))
            self.logger.info("File %s type: %s" %
                             (str(file_to_add), image_filetype))
            if basename.lower().endswith(".pdf"):
                reader = PyPDF2.PdfFileReader(str(file_to_add), strict=False)
                pagecount = reader.getNumPages()
                pages = self._get_pages(pagecount, parameters)
                for n in pages:
                    try:
                        page = reader.getPage(n - 1)
                        writer.addPage(page)
                    except IndexError:
                        self.logger.warning("File %s does not have page %d" %
                                            (file_to_add, n))
            elif image_filetype in ["png", "jpg", "jpeg", "gif"]:
                temp_pdf = os.path.join(tempfile.gettempdir(), "temp.pdf")
                settings = self._get_image_settings(str(file_to_add),
                                                    parameters)
                if settings["format"]:
                    pdf = FPDF(format=settings["format"],
                               orientation=settings["orientation"])
                else:
                    pdf = FPDF(orientation=settings["orientation"])
                pdf.add_page()
                pdf.image(
                    name=settings["name"],
                    x=settings["x"],
                    y=settings["y"],
                    w=settings["width"],
                    h=settings["height"],
                )
                pdf.output(name=temp_pdf)

                reader = PyPDF2.PdfFileReader(temp_pdf)
                writer.addPage(reader.getPage(0))

        with open(target_document, "wb") as f:
            writer.write(f)
コード例 #28
0
def create_form3(personal_info,skill,languages,work_experience,education,font):
    pdf = FPDF()
    pdf.add_page()
    '''HEADER'''
    pdf.set_xy(10,0)
    pdf.set_font("Times", size=25, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255,128,0)
    pdf.cell(80, 10, fill=True, ln=1)

    pdf.set_xy(29,19)
    pdf.set_font("Times", size=25, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 128, 0)
    pdf.cell(42, 42, fill=True, ln=1)

    pdf.set_xy(30,20)
    pdf.image(personal_info[0], w=40, h=40)

    '''NAME AND FIELD'''
    pdf.set_xy(120, 30)
    pdf.set_font("Times", size=25, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(20, 10, personal_info[1], fill=True, ln=1)
    pdf.set_xy(120, 40)
    pdf.set_text_color(255, 128, 0)
    pdf.set_font("courier", size=15, style="B")
    pdf.cell(0, 10, personal_info[2], fill=True, ln=1, align="L")

    '''ABOUT ME'''
    pdf.set_xy(10,70)
    pdf.set_font("arial", size=15, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(80, 10, "ABOUT ME", fill=True, ln=1,align="C")

    pdf.set_line_width(1)
    pdf.set_draw_color(132,132,132)
    pdf.line(15, 80,43,80)

    pdf.set_line_width(1)
    pdf.set_draw_color(255, 128, 0)
    pdf.line(43, 80, 57, 80)

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(57, 80, 85, 80)

    x = 15
    y = pdf.get_y()+5
    pdf.set_font(font[0], size=font[1])
    pdf.set_text_color(128, 128, 128)
    for j in range(len(personal_info[3])):
        if j == 0:
            pass
        else:
            if x + pdf.get_string_width(personal_info[3][j]) > 80:
                x = 15
                y = y + font[1] / 2
            else:
                x = x + pdf.get_string_width(personal_info[3][j - 1]) + 2

        pdf.set_xy(x, y)
        pdf.cell(pdf.get_string_width(personal_info[3][j]) + 1, 5, personal_info[3][j], 0, 1, "C")


    '''CONTACT'''
    pdf.set_xy(10, pdf.get_y()+5)
    pdf.set_font("arial", size=15, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(80, 10, "CONTACT", fill=True, ln=1, align="C")

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(15, pdf.get_y(), 43, pdf.get_y())

    pdf.set_line_width(1)
    pdf.set_draw_color(255, 128, 0)
    pdf.line(43, pdf.get_y(), 57, pdf.get_y())

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(57, pdf.get_y(), 85, pdf.get_y())

    pdf.set_xy(15,pdf.get_y() + 3)
    pdf.set_font("times", size=15)
    pdf.set_text_color(0,0,0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(20, 5, "Address", fill=True, ln=1)
    pdf.set_text_color(132,132,132)
    pdf.set_xy(15, pdf.get_y())
    pdf.cell(20, 5, personal_info[4], fill=True, ln=1)

    pdf.set_xy(15, pdf.get_y() + 3)
    pdf.set_font("times", size=15)
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(20, 5, "Phone", fill=True, ln=1)
    pdf.set_text_color(132, 132, 132)
    pdf.set_xy(15, pdf.get_y())
    pdf.cell(20, 5, personal_info[5], fill=True, ln=1)

    pdf.set_xy(15, pdf.get_y() + 3)
    pdf.set_font("times", size=15)
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(20, 5, "E-Mail", fill=True, ln=1)
    pdf.set_text_color(132, 132, 132)
    pdf.set_xy(15, pdf.get_y())
    pdf.cell(20, 5, personal_info[6], fill=True, ln=1)

    pdf.set_xy(15, pdf.get_y() + 3)
    pdf.set_font("times", size=15)
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(20, 5, "WebSite", fill=True, ln=1)
    pdf.set_text_color(132, 132, 132)
    pdf.set_xy(15, pdf.get_y())
    pdf.cell(20, 5, personal_info[7], fill=True, ln=1)

    '''LANGUAGES'''
    pdf.set_xy(10, pdf.get_y() + 5)
    pdf.set_font("arial", size=15, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(80, 10, "LANGUAGES", fill=True, ln=1, align="C")

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(15, pdf.get_y(), 43, pdf.get_y())

    pdf.set_line_width(1)
    pdf.set_draw_color(255, 128, 0)
    pdf.line(43, pdf.get_y(), 57, pdf.get_y())

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(57, pdf.get_y(), 85, pdf.get_y())

    for i in range(len(languages[0])):
        pdf.set_xy(15, pdf.get_y() + 5)
        pdf.set_font("times", size=15)
        pdf.set_text_color(0, 0, 0)
        pdf.set_fill_color(255, 255, 255)
        pdf.cell(20, 5, languages[0][i], fill=True, ln=1)

        pdf.set_line_width(1)
        pdf.set_draw_color(0,0,128)
        pdf.line(15, pdf.get_y() + 2, languages[1][i] * 7 + 15, pdf.get_y() + 2)

        pdf.set_line_width(1)
        pdf.set_draw_color(132, 132, 132)
        pdf.line(languages[1][i] * 7 + 15, pdf.get_y() + 2, 85, pdf.get_y() + 2)

    '''SKILLS'''
    pdf.set_xy(10, pdf.get_y() + 5)
    pdf.set_font("arial", size=15, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(80, 10, "SKILLS", fill=True, ln=1, align="C")

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(15, pdf.get_y(), 43, pdf.get_y())

    pdf.set_line_width(1)
    pdf.set_draw_color(255, 128, 0)
    pdf.line(43, pdf.get_y(), 57, pdf.get_y())

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(57, pdf.get_y(), 85, pdf.get_y())

    for i in range(len(skill[0])):
        pdf.set_xy(15, pdf.get_y() + 5)
        pdf.set_font("times", size=15)
        pdf.set_text_color(0, 0, 0)
        pdf.set_fill_color(255, 255, 255)
        pdf.cell(20, 5,skill[0][i], fill=True, ln=1)

        pdf.set_line_width(1)
        pdf.set_draw_color(0,0,128)
        pdf.line(15, pdf.get_y()+2, skill[1][i]*7 + 15, pdf.get_y()+2)

        pdf.set_line_width(1)
        pdf.set_draw_color(132, 132, 132)
        pdf.line(skill[1][i]*7 + 15, pdf.get_y()+2, 85, pdf.get_y()+2)

    '''WORK EXPERIENCE'''
    pdf.set_xy(100, 70)
    pdf.set_font("arial", size=15, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(80, 10, "WORK EXPERIENCE", fill=True, ln=1, align="L")

    pdf.set_line_width(1)
    pdf.set_draw_color(255, 128, 0)
    pdf.line(100, 80, 114, 80)

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(114, 80, 200, 80)

    for i in range(len(work_experience[1])):
        pdf.set_xy(100,pdf.get_y()+3)
        pdf.set_font(font[0], size=font[1]+2,style="B")
        pdf.set_text_color(0, 0, 0)
        pdf.cell(20, 10, work_experience[1][i], fill=False, ln=1)
        pdf.set_xy(155, pdf.get_y() - 7)
        pdf.set_font(font[0], size=font[1])
        pdf.cell(25, 5, work_experience[2][i], fill=True, ln=1)
        pdf.set_xy(100, pdf.get_y() + 3)
        pdf.set_text_color(128, 128, 128)
        pdf.set_font(font[0], size=font[1])
        pdf.cell(20, 6, work_experience[0][i], fill=False, ln=1)
        x = 155
        y = pdf.get_y() - 6
        pdf.set_font(font[0], size=font[1])
        for j in range(len(work_experience[3][i])):
            if j == 0:
                pass
            else:
                if x + pdf.get_string_width(work_experience[3][i][j]) > 200:
                    x = 155
                    y = y + font[1] / 2
                else:
                    x = x + pdf.get_string_width(work_experience[3][i][j - 1]) + 2

            pdf.set_xy(x, y)
            pdf.cell(pdf.get_string_width(work_experience[3][i][j]) + 1, 5, work_experience[3][i][j], 0, 1, "C")

    '''EDUCATION'''
    pdf.set_xy(100, pdf.get_y())
    pdf.set_font("arial", size=15, style="B")
    pdf.set_text_color(0, 0, 0)
    pdf.set_fill_color(255, 255, 255)
    pdf.cell(80, 10, "EDUCATION", fill=True, ln=1, align="L")

    pdf.set_line_width(1)
    pdf.set_draw_color(255, 128, 0)
    pdf.line(100, pdf.get_y(), 114, pdf.get_y())

    pdf.set_line_width(1)
    pdf.set_draw_color(132, 132, 132)
    pdf.line(114, pdf.get_y(), 200, pdf.get_y())

    for i in range(len(education[1])):
        pdf.set_xy(100,pdf.get_y()+3)
        pdf.set_font(font[0], size=font[1]+2,style="B")
        pdf.set_text_color(0, 0, 0)
        pdf.cell(20, 10, education[2][i], fill=False, ln=1)
        pdf.set_xy(155, pdf.get_y() - 7)
        pdf.set_font(font[0], size=font[1])
        pdf.cell(25, 5, education[1][i], fill=True, ln=1,align="L")
        pdf.set_xy(100, pdf.get_y() + 3)
        pdf.set_text_color(128, 128, 128)
        pdf.set_font(font[0], size=font[1])
        pdf.cell(20, 6, education[0][i], fill=False, ln=1)
        x = 155
        y = pdf.get_y() - 6
        pdf.set_font(font[0], size=font[1])
        for j in range(len(education[3][i])):
            if j == 0:
                pass
            else:
                if x + pdf.get_string_width(education[3][i][j]) > 200:
                    x = 155
                    y = y + font[1] / 2
                else:
                    x = x + pdf.get_string_width(education[3][i][j - 1]) + 2

            pdf.set_xy(x, y)
            pdf.cell(pdf.get_string_width(education[3][i][j]) + 1, 5, education[3][i][j], 0, 1, "C")

    pdf.set_display_mode("fullpage")
    pdf.output(f"{personal_info[1]}_form3.pdf")
コード例 #29
0
# Python program to create
# a pdf file


from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=15)

pdf.cell(200, 10, txt="Macro Coder",
         ln=1, align='C')

pdf.cell(200, 10, txt="A Python Hub for geeks.",
         ln=2, align='C')

pdf.output("Macro.pdf")
コード例 #30
0
import glob

images_path = raw_input("Enter the path of the folder containing images : ")
images = images_path + "/*.*"

assert os.path.exists(
    images_path), "this diretory doesn't exist, " + str(images_path)
f = os.chdir(images_path)
print("Hooray we found your directory!")

image_list = []
for filename in glob.glob(images):

    image_list.append(filename)

pdf = FPDF(unit='mm')

imnames = [i.split("\\") for i in image_list]
imnames = [i[-1] for i in imnames]
imnums = [i.split('.') for i in imnames]
imnums = [i[0] for i in imnums]
imnums = [int(i) for i in imnums]

pos = 0
images_dict = dict(zip(image_list, imnums))
sorted_images = sorted(images_dict, key=images_dict.get)

for i in list(sorted_images):
    pdf.add_page()
    im = Image.open(i)
    pdf.image(i, pos, pos, 200, 250)